如何去除Pandas直方图X轴年份的小数格式
解决直方图X轴年份显示小数的问题
问题出在matplotlib的自动刻度生成逻辑——即便你的年份数据是整数类型,它仍可能默认输出浮点格式的刻度。以下是几种直接有效的解决方法:
方法1:转换现有刻度为整数
先绘制直方图,再获取当前X轴刻度,将其转为整数后重新设置:
import pandas as pd import matplotlib.pyplot as plt # 提取年份并转为整数 df['Year'] = pd.DatetimeIndex(df['INCI_DATE']).year.astype(int) # 绘制直方图 hist = df.Year.hist(bins=3, figsize=(10,10)) # 重置X轴刻度为整数格式 current_xticks = hist.get_xticks() hist.set_xticks(current_xticks) hist.set_xticklabels([int(tick) for tick in current_xticks]) plt.show()
方法2:直接指定数据中的唯一年份作为刻度
如果你的年份是离散的,直接用数据里的唯一值设置刻度:
import pandas as pd import matplotlib.pyplot as plt df['Year'] = pd.DatetimeIndex(df['INCI_DATE']).year.astype(int) hist = df.Year.hist(bins=3, figsize=(10,10)) # 设置刻度为数据中的唯一年份(已排序) hist.set_xticks(sorted(df['Year'].unique())) plt.show()
方法3:使用matplotlib原生绘图更灵活控制
绕开pandas的hist封装,直接用matplotlib绘图,精准控制刻度:
import pandas as pd import matplotlib.pyplot as plt df['Year'] = pd.DatetimeIndex(df['INCI_DATE']).year.astype(int) plt.figure(figsize=(10,10)) plt.hist(df['Year'], bins=3) # 设置X轴刻度为整数年份 plt.xticks(df['Year'].unique()) plt.xlabel('Year') plt.ylabel('Count') plt.show()
内容的提问来源于stack exchange,提问作者GEobserver
相关产品推荐
相关产品推荐

