Draw a line chart using Matplotlib

introduce

Line charts are a common way of visualizing data to show trends in data over time or other continuous variables. Matplotlib is a popular Python plotting library that makes it easy to create various types of charts, including line charts.

Install Matplotlib

Before starting, make sure you have the Matplotlib library installed. If it is not installed, you can install it using the following command:

pip install matplotlib

Draw a simple line chart

The following is a simple Python example that demonstrates how to draw a basic line chart using the Matplotlib library:

import matplotlib.pyplot as plt

# 数据
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]

# 创建折线图
plt.plot(x, y)

# 添加标题和标签
plt.title("Simple Line Chart")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")

# 显示图表
plt.show()

Insert image description here

Add multiple polylines

You can draw multiple polylines simultaneously to show comparisons between different data sets. Here is an example:

import matplotlib.pyplot as plt

# 数据
x = [1, 2, 3, 4, 5]
y1 = [10, 20, 15, 30, 25]
y2 = [5, 15, 10, 25, 20]

# 创建折线图
plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2')

# 添加标题和标签
plt.title("Multiple Lines Chart")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")

# 添加图例
plt.legend()

# 显示图表
plt.show()

Insert image description here

Custom polyline style

You can customize the line color, line style, and markers to make the chart more attractive. Here is an example of a custom style:

import matplotlib.pyplot as plt

# 数据
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]

# 创建折线图
plt.plot(x, y, color='blue', linestyle='dashed', marker='o', label='Line 1')

# 添加标题和标签
plt.title("Customized Line Style")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")

# 添加图例
plt.legend()

# 显示图表
plt.show()

Insert image description here

in conclusion

Matplotlib is a powerful Python plotting library that makes it easy to create various types of charts, including line charts. With a simple API and various customization options, you can create beautiful data visualization charts.

In the next blog, we will delve into more features of Matplotlib, such as bar charts, scatter plots, pie charts, etc. Stay tuned.

Guess you like

Origin blog.csdn.net/Silver__Wolf/article/details/132347396