Python中如何调整Matplotlib图表X轴的年份排列顺序?
解决X轴年份降序问题
修改后的代码
import pandas as pd from pandas_datareader import wb import matplotlib.pyplot as plt import numpy as np import statsmodels.formula.api as smf # 下载2000-2020年德国人口数据 G_pop = wb.download(indicator='SP.POP.TOTL', country="DEU", end=2020, start=2000) G_pop = G_pop.reset_index(1) # 重命名列 G_pop.columns = ["year", "Population in Germany"] # 转换年份为整数类型并按升序排序 G_pop['year'] = G_pop['year'].astype(int) G_pop = G_pop.sort_values('year', ascending=True) # 设置显示参数(可选) pd.set_option("display.max.columns", 100000) pd.set_option("display.max.rows", 300000) pd.set_option("display.width", 1000000) # 提取绘图数据 x = G_pop["year"] y = G_pop["Population in Germany"] # 绘图配置 plt.xticks(rotation=45, ha='left') plt.plot(x,y) plt.show()
问题原因与解决逻辑
世界银行API返回的数据默认按年份降序排列,且年份字段为字符串类型,直接绘图会导致X轴从2020到2000反向显示。invert_xaxis()报错是因为字符串类型的轴无法被matplotlib识别为连续数值轴,无法执行反转操作。
核心修复步骤:
- 将
year列转换为整数类型,确保排序遵循数值逻辑 - 使用
sort_values('year', ascending=True)对数据按年份升序排序,绘图时X轴自然呈现从2000到2020的顺序 - 把
wb.download的start参数改为2000,匹配你需要展示的时间范围
内容的提问来源于stack exchange,提问作者Ricca
相关产品推荐
相关产品推荐

