像的大小设置为8x5,布局如图所示: 数据如下(需要import calendar): months = [calendar.month_name[i] for i in range(1, 13)] price_a = [1000,1000, 1000, 1000, 1000, 1400, 1400, 1200, 1800, 1800, 1800, 1800] price_b = [1600, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1000, 1000, 1000, 1000] 在2023年的子图中,绘制颜色为蓝色的阶梯图,x轴表示月份,y轴表示价格。价格的范围设置为800到2000。设置标题为"2023年价格阶梯图"。如图所示添加注释'价格上涨',箭头颜色为红色。 对2022年的子图做出相似的处理(如图所示)。
时间: 2023-07-02 14:19:07 浏览: 25
```python
import matplotlib.pyplot as plt
import calendar
# 数据
months = [calendar.month_name[i] for i in range(1, 13)]
price_a = [1000, 1000, 1000, 1000, 1000, 1400, 1400, 1200, 1800, 1800, 1800, 1800]
price_b = [1600, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1000, 1000, 1000, 1000]
# 2023年子图
fig, ax1 = plt.subplots(figsize=(8, 5))
ax1.set_ylim(800, 2000)
ax1.set_ylabel('价格')
ax1.set_xticklabels(months)
ax1.set_xticks(range(1, 13))
ax1.set_title('2023年价格阶梯图')
ax1.plot(price_a, 'b', drawstyle='steps-post')
ax1.annotate('价格上涨', xy=(5, 1400), xytext=(7, 1600),
arrowprops=dict(facecolor='red', arrowstyle='->'))
# 2022年子图
ax2 = ax1.twiny()
ax2.set_xlim(ax1.get_xlim())
ax2.set_xticklabels(months)
ax2.set_xticks(range(1, 13))
ax2.plot(price_b, 'b', drawstyle='steps-post')
ax2.annotate('价格上涨', xy=(5, 1200), xytext=(7, 1400),
arrowprops=dict(facecolor='red', arrowstyle='->'))
plt.show()
```
输出结果如下图所示:
注:由于x轴标签较多,需要使用 `ax1.set_xticklabels(months)` 和 `ax2.set_xticklabels(months)` 来设置标签。由于两个子图的x轴标签相同,因此使用 `ax2 = ax1.twiny()` 来创建第二个x轴,再使用 `ax2.set_xticklabels(months)` 来设置标签。使用 `drawstyle='steps-post'` 来绘制阶梯图。