Matplotlib subplots绘制时间序列时x轴日期拥挤如何设置等间距可读刻度
解决方法
核心思路
通过Matplotlib内置的日期定位器控制x轴刻度的数量和间隔,搭配自动格式调整实现等间距清晰可读的日期刻度。
前置检查
首先确保x轴的日期数据为datetime类型,若为字符串格式需先转换:
df_area['index'] = pd.to_datetime(df_area['index'])
具体修改步骤
- 导入日期定位器工具:使用
matplotlib.dates下的AutoDateLocator可自动计算合适的刻度间隔,也可选用固定间隔的定位器如DayLocator、WeekLocator、MonthLocator。 - 配置定位器限制最大刻度数,避免刻度过多拥挤。
- 可选调用
fig.autofmt_xdate()自动调整刻度的旋转和对齐方式,避免边缘日期被截断。
修改后的完整代码
import pandas as pd import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter, AutoDateLocator def plot_time_series(area): df_area = df.loc[df.area== str(area)] df_area.reset_index(inplace = True) # 转换为datetime类型,保证日期定位器正常生效 df_area['index'] = pd.to_datetime(df_area['index']) fig, ax = plt.subplots(figsize=(10, 7)) # 配置日期定位器,最多显示6个刻度,可根据图表宽度调整数值 locator = AutoDateLocator(maxticks=6) ax.xaxis.set_major_locator(locator) # 配置日期显示格式 formatter = DateFormatter('%Y-%m-%d') ax.xaxis.set_major_formatter(formatter) p1 , = plt.plot(df_area['index'], (df_area.feature1 * 1000), color='#15B01A', label='Feature 1') p2 , = plt.plot(df_area['index'], df_area.feature_2, color='red', label='feature_2') # 自动调整x轴刻度的旋转和对齐,效果优于手动设置rotation fig.autofmt_xdate(rotation=30, ha='right') ax.tick_params(axis='x', labelsize=10) plt.title(str(market)) lgd = plt.legend(handles=[p1, p2], title='Legend', bbox_to_anchor=(1.05, 1), loc='upper left') plt.show()
自定义间隔配置参考
如果需要固定时间间隔展示刻度,可替换定位器配置:
# 每7天显示一个刻度 from matplotlib.dates import DayLocator ax.xaxis.set_major_locator(DayLocator(interval=7)) # 每个月显示一个刻度 from matplotlib.dates import MonthLocator ax.xaxis.set_major_locator(MonthLocator(interval=1))
内容的提问来源于stack exchange,提问作者Rahul Anand
相关产品推荐
相关产品推荐

