「matplotlib」单个坐标轴,绘制多个图像

31 阅读1分钟

单个坐标轴上绘制多个图像

  • 准备数据

  • 创建画布

  • 绘制多个图像

  • 修饰图像

  • 展示图像

单个坐标多个图像.png

import matplotlib.pyplot as plt
import matplotlib
import random
from pylab import mpl

# 设置显示中文字体
mpl.rcParams["font.sans-serif"] = ["SimSun"]  # 宋体 = SimSun
# 设置正常显示符号
mpl.rcParams["axes.unicode_minus"] = False

matplotlib.use('Qt5Agg')

# 1、准备数据
x = range(60)
y_shanghai = [random.uniform(15, 18) for i in x]
y_beijing = [random.uniform(1, 3) for i in x]

# 2、创建画布
plt.figure(figsize=(10, 6), dpi=120)

# 3、绘制图像
plt.plot(x, y_shanghai, label="shanghai")
plt.plot(x, y_beijing, color="red", label="beijing", linestyle="--")

# 4、设置自定义刻度
# 构造x,y轴刻度标签
x_ticks_label = ["11点{}分".format(i) for i in x]
y_ticks = range(40)
# 设置刻度
plt.xticks(x[::5], x_ticks_label[::5])
plt.yticks(y_ticks[::5])

# 5、显示网格
plt.grid(True, linestyle='--', alpha=0.5)

# 6、添加描述信息
plt.xlabel("时间", fontsize=20)
plt.ylabel("温度", fontsize=20)
plt.title("中午11点--12点某城市温度变化图", fontsize=20)

# 7、显示图例
plt.legend()

# 8、图像显示
plt.show()

更多绘图请关注该专栏内容