使用 Python 的 Matplotlib 库可以轻松绘制折线图。以下是一个简单的例子:

import matplotlib.pyplot as plt

# 定义数据
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# 绘制折线图
plt.plot(x, y)

# 添加标题和标签
plt.title('My Line Chart')
plt.xlabel('X Axis Label')
plt.ylabel('Y Axis Label')

# 显示图形
plt.show()

这将绘制一个简单的折线图,其中 x 轴上的标签为 1 到 5,y 轴上的标签为 2 到 10。你可以使用其他函数来自定义图形,例如添加颜色,样式等。

另外,如果需要绘制多条折线图,可以重复调用 plt.plot() 函数,并在每次调用时传递不同的数据和参数。例如,下面的代码绘制了两条折线图,分别用红色和蓝色表示:

import matplotlib.pyplot as plt

# 定义数据
x1 = [1, 2, 3, 4, 5]
y1 = [2, 4, 6, 8, 10]
x2 = [1, 2, 3, 4, 5]
y2 = [1, 3, 5, 7, 9]

# 绘制折线图
plt.plot(x1, y1, color='red', linestyle='--', label='Line 1')
plt.plot(x2, y2, color='blue', linestyle='-', label='Line 2')

# 添加标题和标签
plt.title('My Line Chart')
plt.xlabel('X Axis Label')
plt.ylabel('Y Axis Label')
plt.legend()

# 显示图形
plt.show()

在这个例子中,我们使用了 colorlinestyle 参数来设置线条的颜色和样式,使用 label 参数来设置每条线的标签,最后使用 plt.legend() 函数来显示图例。

Python Matplotlib 折线图绘制教程:入门指南及多线示例

原文地址: https://www.cveoy.top/t/topic/mRCd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录