You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib柱状图X轴标签显示错误,如何修改为年份值?

问题描述

我有一个包含国家、年份和数值的DataFrame,先执行以下代码设置索引:

data = data.set_index(data['Country or Area'])
data.drop(['Country or Area'], axis=1, inplace=True)
data.head()

随后尝试绘制阿尔巴尼亚的降水柱状图,代码如下:

%matplotlib inline
albania = data.loc['Albania']
ax = albania[['Year','Value']].plot(kind='bar', figsize=(8,5), title="Precipitation of Albania between 1990 and 2015")
ax.set_ylabel("Precipitation")
ax.set_xlabel("Years")

但柱状图的X轴标签显示为索引名'Albania',而非正确的年份范围,请问该如何修改为正确的年份标签?

解决方法

问题核心是:筛选出的albania数据默认索引是重复的'Albania',而plot方法默认用当前数据的索引作为X轴标签,所以才会显示错误内容。以下两种方式可以快速解决:

方式一:直接指定X轴数据

在plot方法中通过x参数明确指定用Year列作为X轴,无需修改原有数据结构:

%matplotlib inline
albania = data.loc['Albania']
ax = albania.plot(x='Year', y='Value', kind='bar', figsize=(8,5), title="阿尔巴尼亚1990-2015年降水量")
ax.set_ylabel("降水量")
ax.set_xlabel("年份")

方式二:将Year设为临时索引

先把Year列设为albania数据的索引,再针对Value列绘制柱状图:

%matplotlib inline
albania = data.loc['Albania'].set_index('Year')
ax = albania['Value'].plot(kind='bar', figsize=(8,5), title="阿尔巴尼亚1990-2015年降水量")
ax.set_ylabel("降水量")
ax.set_xlabel("年份")

两种方式都能让X轴正确显示年份标签,第一种更简洁适合快速绘图;第二种适合后续需要基于年份索引做更多操作的场景。

内容的提问来源于stack exchange,提问作者FriendlyUser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 23:40:23