【发布时间】:2023-03-16 23:41:02
【问题描述】:
我正在绘制一个带有两个 y 轴的可视化图,每个轴代表一个数据框列。我使用了一个数据框(两个数据框具有相同的索引)索引作为 x 轴,但是 xticks 标签显示不正确。我应该有从 2000 年到 2018 年的年份
我使用以下代码来创建情节:
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(df1.index, df1, 'g-')
ax2.plot(df1.index, df2, 'b-')
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.set_ylabel('Y2 data', color='b')
plt.show()
df1的索引如下:
Index(['2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008',
'2009', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016',
'2017', '2018'],
dtype='object')
这是两个dfs的小sn-p:
df1.head()
gdp
2000 1.912873
2001 7.319967
2002 3.121450
2003 5.961162
2004 4.797018
df2.head()
lifeex
2000 68.684
2001 69.193
2002 69.769
2003 70.399
2004 71.067
我尝试了不同的解决方案,包括Set Xticks frequency to dataframe index 中的解决方案,但没有一个能够成功展示所有年份。 如果有人可以提供帮助,我真的很感激。提前致谢
当我尝试ax1.set_xticks(df1.index) 时出现以下错误:'<' not supported between instances of 'numpy.ndarray' and 'str'
【问题讨论】:
-
你能在这个问题中添加一些示例数据吗?
-
问题在于 matplotlib 将索引解释为数字数据,而不是日期时间对象。正如 Scott Boston 所说,没有样本数据,就无法给出好的建议。请阅读How to make good reproducible pandas examples 并使用建议的方法之一添加您的数据。
-
您可以尝试通过
pd.to_datetime()将您的年份转换为日期时间对象。另外,我推荐 Plotly 在 x 轴上使用 Datetime 对象进行绘图。它负责适当的缩放和刻度线。 -
感谢大家的帮助。我尝试了以下代码,它工作了
years = list(df1.index) for i in range(0, len(years)): years[i] = int(years[i]) ax1.xaxis.set_ticks(years) plt.setp(ax1.get_xticklabels(), rotation=30, horizontalalignment='right') -
很高兴解决了。你可以answer your own question and accept it.
标签: python pandas dataframe matplotlib