如何获取所有的x轴刻度标签?
我想知道怎么让x轴显示所有的年份和月份。下面是我生成的图像。之后我可能还需要旋转一下和缩小字体大小。
df_estimated_months = df.groupby(['Year', 'Month'])['Estimated_fire_area'].mean()
plt.figure(figsize=(20,6))
df_estimated_months.plot(kind='line', title='Mean Estimated Fire Area over Time')
plt.xlabel('Year, Month')
plt.ylabel('Average Estimated Fire Area (km²)')
plt.show()
我试过用 plt.xticks(df_estimated_months.index.values)
。
1 个回答
1
把你的索引改成日期时间格式。之后,你就可以使用定位器来设置你的刻度参数。我还没有测试过,可能会有一些问题,但你可以把它放到你的代码里。我希望这对你有帮助。如果在测试过程中遇到任何问题,告诉我,我会尽力帮你解决。
fig, ax1 = plt.subplots(figsize=(24, 6), sharex=True)
df_estimated_months.index = pd.to_datetime(df_estimated_months.index)
ax1.set_ylabel('Average Estimated Fire Area (km²)')
plt.xlabel('Year, Month')
date_formatter = DateFormatter("%Y - %b")
ax1.xaxis.set_major_formatter(date_formatter)
ax1.xaxis.set_major_locator(mdates.MonthLocator(interval=1)) #Change interval depends on your dataframe
ax1.plot(df_estimated_months.index, {set your y tick}. label=name, marker='o', markersize=2)
plt.xticks(rotation=45) #Rotate
ax1.tick_params(axis='x', colors='gray',labelsize=18,width=2) # Set x-axis tick color to gray
ax1.tick_params(axis='y', colors='gray',labelsize=18,width=2) # Set y-axis tick color to gray