matplotlib在多個座標系下繪製折線圖像(模板)

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

# 設置中文顯示
mpl.rcParams["font.sans-serif"] = ["SimHei"]
mpl.rcParams["axes.unicode_minus"] = False

x = range(60)
y_shanghai = [random.uniform(15, 18) for i in x]
y_beijing = [random.uniform(1, 3) for i in x]

# 設置圖像大小及清晰度
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(20, 8), dpi=100)

# 繪製圖像
axes[0].plot(x, y_shanghai, label="上海")
axes[1].plot(x, y_beijing, color="r", linestyle="--", label="北京")

x_ticks_label = ["11點{}分".format(i) for i in x]
y_ticks = range(40)
x_ticks = x[::5]

# 設置座標軸刻度
axes[0].set_xticks(x_ticks)
axes[0].set_yticks(y_ticks[::5])
axes[0].set_xticklabels(x_ticks_label[::5])
axes[1].set_xticks(x_ticks)
axes[1].set_yticks(y_ticks[::5])
axes[1].set_xticklabels(x_ticks_label[::5])

# 設置網格
axes[0].grid(True, linestyle="--", alpha=1)
axes[1].grid(True, linestyle="--", alpha=1)

# 設置座標軸含義
axes[0].set_xlabel("時間")
axes[0].set_ylabel("溫度")
axes[0].set_title("中午溫度", fontsize=20)
axes[1].set_xlabel("時間")
axes[1].set_ylabel("溫度")
axes[1].set_title("中午溫度", fontsize=20)

# 添加圖例
axes[0].legend(loc="best")
axes[1].legend(loc="best")

# 圖像保存
plt.savefig("./test.png")

# 展示圖像
plt.show()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章