【问题标题】:How do I change the index of x axis [duplicate]如何更改x轴的索引[重复]
【发布时间】:2021-08-13 18:36:47
【问题描述】:

我正在尝试绘制区域图。然而,图表的 x 轴显示 1、2、3 而不是年份。我怎样才能改变这个?我在这里看到了一些相关的问题,但是那里的代码对我来说有点太复杂了。 我的代码是:

import matplotlib as mpl
import matplotlib.pyplot as plt
areaplot=r'data.xlsx'
df_areaplot = pd.read_excel(areaplot)
df_areaplot.plot(kind='area')
plt.title('SDG Spending Trend')
plt.ylabel('Amount Spent')
plt.xlabel('Years')
plt.show()

【问题讨论】:

  • 您的数据框中是否有包含年份的列?如果是这样,您可以执行以下操作:df_areaplot.plot(kind='area', x='Year', y='Amount Spent')(显然用您的列名称编辑这些标签)
  • 我想我需要索引列?如果我输入 x='2015' 则显示错误。基本上我不想在我的区域图上有 SDG(现在它是 x 轴顶部的一条蓝线)并且希望有几年而不是 1、2、3。我认为这意味着跳过 1 行和 1 列。我添加了一张名为“数据”的图片,显示了我正在使用的内容。
  • 在绘图前设置以年份为索引的列。 df.set_index('SDG', inplace=True)
  • 这成功了!谢谢
  • df_areaplot.plot(kind='area', x='SDG') 也将像在副本中一样工作,而无需设置索引。

标签: python pandas matplotlib


【解决方案1】:

正如@tmdavison 在评论中指出的那样,您可以使用列名来确定轴,即使是指定的列列表,即:

df_areaplot.plot(kind='area',
  x='BDG',
  y=['Citizen Initiatives',
     'Education and Employability',
     'Enviromental Sustainability',
     'Woman Empowerment'])

【讨论】:

    猜你喜欢
    • 2013-01-12
    • 2021-11-28
    • 2017-08-20
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    相关资源
    最近更新 更多