pyplot 怎么使用

pyplot 是 matplotlib 库中的一个模块,它用于绘制各种类型的图表。以下是一些使用 pyplot 的基本步骤:

导入 pyplot 模块:

python:
import matplotlib.pyplot as plt


创建图表:

python:
plt.figure()


绘制图表:

python:
plt.plot([1, 2, 3, 4], [1, 4, 2, 3]) # 绘制折线图
plt.scatter([1, 2, 3, 4], [1, 4, 2, 3]) # 绘制散点图
plt.bar([1, 2, 3, 4], [1, 4, 2, 3]) # 绘制条形图
plt.hist([1, 2, 3, 4], bins=3) # 绘制直方图
# 等等


添加图表元素:

python:
plt.title('My Chart') # 添加标题
plt.xlabel('X Label') # 添加 X 轴标签
plt.ylabel('Y Label') # 添加 Y 轴标签
plt.legend(['Line 1']) # 添加图例
plt.grid(True) # 添加网格线


显示图表:

python:
plt.show()


这是一个简单的示例,演示了如何使用 pyplot 绘制一个简单的折线图:

import matplotlib.pyplot as plt

# 创建图表
plt.figure()

# 绘制折线图
x = [1, 2, 3, 4]
y = [1, 4, 2, 3]
plt.plot(x, y)

# 添加标题和轴标签
plt.title('My Line Chart')
plt.xlabel('X Label')
plt.ylabel('Y Label')
# 设置画布大小
plt.rcParams['figure.figsize'] = [4, 4]
# 显示图表
plt.show()