【问题标题】:add count column in time series plot在时间序列图中添加计数列
【发布时间】:2020-02-13 10:23:54
【问题描述】:

我想根据月份和年份绘制平均值。

我的数据有两列(计数、平均值)和日期作为索引。

这里显示的图类似于我的图,其中 x 是年,y 是平均值

这是我的代码

    import matplotlib.pyplot as plt
    diet = df[['mean']]
    diet.plot(figsize=(20,10), linewidth=5, fontsize=20 ,marker='<')
    plt.xlabel('Year', fontsize=20);
    plt.xlabel('Month/Year')
    plt.ylabel('mean')

有没有办法像这样在所有点线上添加计数列以了解每个月的计数。

【问题讨论】:

  • 这能回答你的问题吗? Annotate Time Series plot in Matplotlib
  • @DizietAsahi 不多,因为我想添加列而不是一个词
  • 好吧,你必须运行一个循环来为你的 df 的每一行添加一个单词。对不起。

标签: python matplotlib


【解决方案1】:
idx = pd.date_range(start='1901-01-01', end='1903-12-31', freq='1M')
df = pd.DataFrame({"mean": np.random.random(size=(idx.size,)), "count": np.random.randint(0,10, size=(idx.size,))}, index=idx)

plt.figure()
ax = df['mean'].plot(figsize=(8,4))
for d,row in df.iterrows():
    ax.annotate('{:.0f}'.format(row['count']), xy=(d,row['mean']), ha='center')

【讨论】:

  • 你的例子有效,但我的数据我得到了这个错误TypeError: float() argument must be a string or a number, not 'tuple'
  • 提供你的数据框的 sn-p
  • 我认为因为我的数据是按年和月分组的,所以我必须取消分组
  • 是的,和我想的一样,所以我不得不重置索引,它工作了,谢谢
猜你喜欢
  • 2017-07-13
  • 2019-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-12
  • 1970-01-01
相关资源
最近更新 更多