如何获取所有xtick标签并让Matplotlib x轴显示全部年月?
Pandas绘图问题解决方法
1. 获取所有xtick标签
要获取x轴的全部刻度标签,有两种简单方法:
- 方法一:通过matplotlib获取当前坐标轴对象后提取标签文本
import matplotlib.pyplot as plt # 绘图完成后执行这段代码 ax = plt.gca() xtick_labels = [label.get_text() for label in ax.get_xticklabels()] print(xtick_labels)
- 方法二:如果是用Pandas的plot方法绘图,直接从返回的轴对象提取
ax = df_estimated_months.plot(kind='line', title='Mean Estimated Fire Area over Time') xtick_labels = [label.get_text() for label in ax.get_xticklabels()] print(xtick_labels)
2. 让x轴显示全部Year和Month并优化显示
你当前的代码里,分组后的索引是(Year, Month)的多级索引,matplotlib会自动省略部分标签。结合你试过的plt.xticks,可以按以下方式修改代码,确保所有年份和月份都显示,同时解决标签重叠问题:
完整修改代码
import pandas as pd import matplotlib.pyplot as plt # 分组计算平均过火面积 df_estimated_months = df.groupby(["Year", "Month"])["Estimated_fire_area"].mean() # 把多级索引转成"YYYY-MM"格式的字符串,让标签更清晰 df_estimated_months.index = df_estimated_months.index.map(lambda x: f"{x[0]}-{x[1]:02d}") plt.figure(figsize=(20,6)) ax = df_estimated_months.plot(kind='line', title='Mean Estimated Fire Area over Time') plt.xlabel('Year, Month') plt.ylabel('Average Estimated Fire Area (km²)') # 设置每个位置都显示标签,旋转45度并缩小字体 ax.set_xticks(range(len(df_estimated_months))) ax.set_xticklabels(df_estimated_months.index, rotation=45, fontsize=8) plt.tight_layout() # 自动调整布局,避免标签被截断 plt.show()
效果说明
- 转换索引格式后,x轴标签会显示为类似“2020-01”的清晰格式;
set_xticks指定了每个数据点都显示标签,不会被自动省略;- 旋转标签和缩小字体能避免标签重叠,提升可读性;
tight_layout确保标签不会被图表边缘挡住。
你之前生成的图表如下:
内容的提问来源于stack exchange,提问作者Uzor
相关产品推荐
相关产品推荐

