具有DatetimeIndex的DataFrame,如何每年进行绘制?

时间:2019-02-03 21:13:23

标签: python pandas matplotlib time-series

我有一个名为df的数据框和一个月中的第一天的datetimeIndex和一个名为Val的列,其中包含一些数值。

df.head()


+------------+-----+
|            | Val |
+------------+-----+
| DateTime   |     |
| 2011-10-01 |  11 |
| 2011-11-01 |  85 |
| 2011-12-01 |  12 |
| 2012-01-01 |  91 |
| 2012-02-01 |  44 |
+------------+-----+

dataFrame在2010年至2017年之间的月份中每个月包含一行。我的目标是在同一图中绘制所有值,其中每一行代表一年,在x轴上我有月份(Jan或01为并不重要),并且在y轴上Val的数量。

我的第一个想法是使用类似df.groupby(df.index.year)['Val'].agg('sum').unstack()的东西,但这会产生错误。 AttributeError:

  

“ Int64Index”对象没有属性“ remove_unused_levels”

然后,我编写了以下代码,该代码虽然有效,但存在一些问题:

  • 我必须列出所有年份;
  • 我必须列出线条的所有颜色
  • 创建图例很困难

fig, ax1 = plt.subplots(figsize=(20,7))
months = df['2018'].index
ax1.set_xlabel('months')
ax1.set_ylabel('Sales')
ax1.plot(months, df['2018'], color='navy')
ax1.plot(months, df['2017'], color='blue')
ax1.plot(months, df['2016'], color='lightblue')
ax1.plot(months, df['2015'], color='lime')
plt.grid()

fig.tight_layout()
plt.title('Sales per year', loc='center')

plt.show()

是否有一种更聪明的方式来绘制图?

1 个答案:

答案 0 :(得分:0)

由于您没有以可复制的格式提供DataFrame,所以我无法生成任何数字。不过,您可以尝试以下方式。可能还有其他方法可以在DataFrame上使用某种groupby

start = 2015
end = 2018
years = map(str, range(start, end+1))
colors = ['lime', 'lightblue', 'blue', 'navy']

for year, c in zip(years, colors):
    ax1.plot(months, df[year], color=c)

plt.grid()
fig.tight_layout()