matplotlib 是 Python 中的一个绘图库,它提供了一个类似于 MATLAB 的绘图框架,可以生成各种静态、动态、交互式和 3D 的图像。以下是 matplotlib 库的一些基本用法:
1. 导入库
首先,需要导入 matplotlib.pyplot 模块,这通常是 matplotlib 最常用的模块。
import matplotlib.pyplot as plt
2. 绘制折线图
# 数据
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
# 绘制图像
plt.plot(x, y)
# 显示图像
plt.show()
3. 添加标题和轴标签
plt.plot(x, y)
plt.title('Square Numbers') # 添加标题
plt.xlabel('Value') # x轴标签
plt.ylabel('Square of Value') # y轴标签
plt.show()
4. 绘制多个图像
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [2, 5, 10, 17, 26]
plt.plot(x, y1, label='Square') # 绘制第一个图像并添加标签
plt.plot(x, y2, label='Square + 1') # 绘制第二个图像并添