如何将Matplotlib图表X轴设置为仅显示年份并解决日期轴重叠问题
解决Matplotlib日期轴重叠并仅显示年份的问题
嘿,新手遇到日期轴重叠太正常啦,这主要是因为Matplotlib默认会把所有日期都塞进X轴,加上如果你的日期是字符串格式的话,它没法智能优化刻度。给你两个实用的解决思路,直接改代码就能搞定:
方法一:规范处理时间轴(推荐,适合后续分析)
这种方法会先把日期转成datetime类型,让Matplotlib能正确识别时间逻辑,再自定义刻度只显示年份:
import matplotlib.pyplot as plt import pandas as pd from matplotlib.dates import YearLocator, DateFormatter # 第一步:把日期列转成datetime类型(核心!不然Matplotlib认不出时间) df_temp['Mes'] = pd.to_datetime(df_temp['Mes']) # 创建画布和轴对象,方便自定义X轴 fig, ax = plt.subplots() ax.plot(df_temp['Mes'], df_temp['data science'], label='data science') ax.plot(df_temp['Mes'], df_temp['machine learning'], label='machine learning') ax.plot(df_temp['Mes'], df_temp['deep learning'], label='deep learning') # 设置X轴只显示每年的刻度,格式化为四位年份 ax.xaxis.set_major_locator(YearLocator()) # 只保留每年的刻度点 ax.xaxis.set_major_formatter(DateFormatter('%Y')) # 把刻度显示成纯年份 # 旋转X轴标签,彻底解决重叠问题(角度可以按需调,45度比较常用) plt.xticks(rotation=45) # 其他图表美化设置 plt.xlabel('Year') plt.ylabel('Popularity') plt.title('Popularity of AI terms by year') plt.grid(True) plt.legend() plt.tight_layout() # 自动调整布局,防止标签被画布边缘截断 plt.show()
方法二:直接提取年份作为X轴(简单粗暴)
如果不需要保留完整的时间信息,也可以直接从日期里提取年份当X轴,操作更简单:
import matplotlib.pyplot as plt import pandas as pd # 提取年份(先确保Mes是datetime类型,要是字符串格式比如'2020-03',也可以用str[:4]直接截取) df_temp['Year'] = pd.to_datetime(df_temp['Mes']).dt.year # 用提取的年份列做X轴绘图 plt.plot(df_temp['Year'], df_temp['data science'], label='data science') plt.plot(df_temp['Year'], df_temp['machine learning'], label='machine learning') plt.plot(df_temp['Year'], df_temp['deep learning'], label='deep learning') # 同样可以旋转标签预防拥挤(年份少的话可能不需要,但加上更稳妥) plt.xticks(rotation=45) plt.xlabel('Year') plt.ylabel('Popularity') plt.title('Popularity of AI terms by year') plt.grid(True) plt.legend() plt.tight_layout() plt.show()
关键细节提醒
- 一定要转datetime类型:如果你的
Mes列是字符串,Matplotlib会把它当成普通文本,只会一股脑把所有内容堆在X轴,这就是重叠的根源。转成datetime后,它会自动识别时间顺序并优化刻度。 - tight_layout()很重要:旋转标签后容易出现标签被截断的情况,加这个方法能自动调整画布边缘,让所有内容都显示完整。
内容的提问来源于stack exchange,提问作者Sean
相关产品推荐
相关产品推荐

