【问题标题】:Using dataframe index containing the year as x axis使用包含年份的数据框索引作为 x 轴
【发布时间】: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


【解决方案1】:

我无法复制您的问题(mpl.version = 3.2.2):

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df1 = pd.DataFrame({'col1':np.random.randint(1,7 , 19)}, 
                   index=[str(i) for i in range(2000,2019)])

print(df1.index)

df2 = pd.Series(np.linspace(69,78, 19))

fig, ax1 = plt.subplots(figsize=(15,8))
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()

输出:

Index(['2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008',
       '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017',
       '2018'],
      dtype='object')

【讨论】:

  • 此处相同,版本 3.3.3
  • 我运行了 Scott 的代码,但仍然遇到同样的问题!
  • @houdabenhar 你运行的是什么版本的matplotlib?
  • @ScottBoston 2.0.0 我在 Coursera 的 jupyter notebook 系统上运行我的代码
  • 在 2.0.0 中,matplotlib 的行为确实是这样的。我认为更新 matplotlib 是不可能的,因此您必须手动处理刻度位置,例如使用 FixedLocator
【解决方案2】:

以下代码为我解决了这个问题:

years = list(df1.index) 
for i in range(0, len(years)):     
   years[i] = int(years[i]) 
ax1.xaxis.set_ticks(years)

【讨论】:

    猜你喜欢
    • 2021-06-17
    • 2014-04-16
    • 2013-07-07
    • 2021-11-05
    • 2017-08-18
    • 2018-11-15
    • 2015-12-25
    • 2018-12-08
    • 2012-07-20
    相关资源
    最近更新 更多