matplotlib绘制日期折线图时第二个x轴刻度标签无法旋转怎么办?
问题原因
- 你设置x轴刻度样式的时机有误:调用
ax.get_xticklabels()获取刻度标签时,还未执行ax.plot()绘制数据,matplotlib尚未完成所有刻度标签的初始化,仅部分标签被创建,因此第二个刻度的旋转配置没有生效。
修复方法
你可以任选以下任意一种方案解决问题:
方案一:调整代码执行顺序
将x轴刻度样式设置的代码移动到ax.plot()之后、plt.show()之前,确保获取刻度标签时所有标签已经完成初始化,修改后的代码如下:
import datetime import matplotlib.pyplot as plt from matplotlib.dates import MonthLocator, DateFormatter import matplotlib.ticker as ticker plt.rcdefaults() fig, ax = plt.subplots() fig.set_size_inches(6.5, 3) # Example data values = [ 270, 318, 349, 322, 433, 444, 459, 481, 449, 558, 575, 843] dlist = [ datetime.datetime(2020,10,1), datetime.datetime(2020,11,1), datetime.datetime(2020,12,1), datetime.datetime(2021,1,1), datetime.datetime(2021,2,1), datetime.datetime(2021,3,1), datetime.datetime(2021,4,1), datetime.datetime(2021,5,1), datetime.datetime(2021,6,1), datetime.datetime(2021,7,1), datetime.datetime(2021,8,1), datetime.datetime(2021,9,1)] ax.set_box_aspect(.25) ax.xaxis.set_major_locator(MonthLocator(interval=1)) ax.xaxis.set_major_formatter(DateFormatter('%b %Y')) ax.yaxis.set_major_locator(ticker.FixedLocator([0, 200, 400, 600, 800, 1000])) ax.set_ylabel('Attack Volume', fontsize=10) ax.set_xlim(dlist[0], dlist[-1]) ax.set_ylim(0,1000) ax.grid(True) ax.set_title('Figure 1: Attack Volume Trend', fontsize=12) ax.plot(dlist, values, 'o-') # 刻度样式设置移到plot之后 plt.setp(ax.get_xticklabels(), fontsize=8, rotation=45, ha='right') plt.setp(ax.get_yticklabels(), fontsize=8) plt.show()
方案二:使用内置日期格式化方法
直接调用fig.autofmt_xdate()方法自动完成所有日期刻度的旋转设置,无需手动获取刻度标签,代码更简洁:
只需在原有代码的plt.show()前增加一行fig.autofmt_xdate(rotation=45, ha='right')即可,原有的plt.setp(ax.get_xticklabels(), ...)行可以删除。
两种方案在matplotlib 3.4.3版本中均可正常生效,所有x轴刻度标签都会正确旋转。
内容的提问来源于stack exchange,提问作者John M. Wilson III
相关产品推荐
相关产品推荐

