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

Python表格数据绘图X轴问题求助:需展示Time列而非行号

搞定X轴显示行号的问题!

嘿,我一眼就瞅出来问题出在哪儿了——你用loc选数据的时候搞反了行和列,导致Time列根本没被正确设成索引,所以Matplotlib只能拿默认的行号当X轴啦。

问题根源

你写的第一行代码:

df1 = populationReport.loc[['Time','VIC','NSW','QLD']]

loc里直接放列表是用来选行的,但Time是你的列名啊!这相当于你在找名叫Time的行,可你的数据里根本没有这种行,结果就是后续set_index('Time')根本没法把时间列设成索引,绘图自然就用行号当X轴了。

修正后的代码

把选列的方式改对就行,两种写法都可以:

# 方法1:直接用方括号选列
df1 = populationReport[['Time','VIC','NSW','QLD']]

# 方法2:用loc明确选所有行+指定列(更严谨)
# df1 = populationReport.loc[:, ['Time','VIC','NSW','QLD']]

# 然后正常设置索引
df1 = df1.set_index('Time')
print(df1)

plt.plot(df1)
plt.legend(df1.columns)
plt.ylabel ('Population')
plt.xlabel ('Timeline')
plt.show()

额外提个优化建议

你的Time列是字符串格式的日期,最好转成datetime类型,这样Matplotlib能更好地处理时间刻度,比如自动调整间隔、旋转标签避免重叠:

import pandas as pd

# 先转成datetime,注意你的日期是日/月/年格式,要加dayfirst=True
df1 = populationReport[['Time','VIC','NSW','QLD']]
df1['Time'] = pd.to_datetime(df1['Time'], dayfirst=True)
df1 = df1.set_index('Time')

plt.plot(df1)
plt.legend(df1.columns)
plt.ylabel ('Population')
plt.xlabel ('Timeline')
plt.xticks(rotation=45)  # 旋转X轴标签,避免挤在一起
plt.tight_layout()  # 调整布局,防止标签被截断
plt.show()

这样改完,X轴就会乖乖显示你要的Time列日期啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:23:27