【问题标题】:How can I draw Yearly series using monthly data from a DateTimeIndex in Matplotlib?如何使用 Matplotlib 中 DateTimeIndex 的月度数据绘制年度系列?
【发布时间】:2020-01-04 09:01:59
【问题描述】:

我在一个数据集中有从 2014 年到 2018 年的 6 个变量的月度数据。 我正在尝试使用每月 X 轴(1 月、2 月 ....)和 5 个系列(每年一个)用 legend 绘制 6 个子图(每个变量一个)。

这是数据的一部分:

我为每个变量(总共 30 个)创建了 5 个系列(每年一个),我得到了预期的输出,但使用了许多代码行。

使用更少的代码行来实现这一目标的最佳方法是什么?

这是我如何创建系列的示例:

CL2014 = data_total['Charity Lottery'].where(data_total['Date'].dt.year == 2014)[0:12]

CL2015 = data_total['Charity Lottery'].where(data_total['Date'].dt.year == 2015)[12:24]

这是我如何绘制系列的示例: axCL.plot(xvals, CL2014)

axCL.plot(xvals, CL2015)

axCL.plot(xvals, CL2016)

axCL.plot(xvals, CL2017)

axCL.plot(xvals, CL2018)

【问题讨论】:

  • 不看你的数据很难说,你能举个例子吗?
  • 感谢您的回复!我添加了数据预览

标签: pandas datetime matplotlib python-datetime


【解决方案1】:

我会尝试使用 .groupby(),它对于解析这样的事情非常强大:

for _, group in data_total.groupby([year, month])[[x_variable, y_variable]]:
    plt.plot(group[x_variables], group[y_variables])

所以这里 groupby 会将您的 data_total DataFrame 分成年/月子集,最后用 [[]] 将其解析为 x_variable(假设它在您的 data_total DataFrame 中)和您的 y_variable,您可以制作您感兴趣的任何功能。

我会将您的日期时间列分解为单独的年和月列,然后使用该 groupby 中的这些新列作为 [年、月]。您也许可以像以前一样传递 dt.year 和 dt.month...不确定,两种方式都试一下!

【讨论】:

    【解决方案2】:

    无需在命名空间中乱扔 30 个变量。 Seaborn 使这项工作变得非常容易,但您需要先规范化您的数据框。这就是“规范化”或“未透视”的样子(Seaborn 称之为“长形式”):

    Date        variable         value
    2014-01-01  Charity Lottery  ...
    2014-01-01  Racecourse       ...
    2014-04-01  Bingo Halls      ...
    2014-04-01  Casino           ...
    

    您的屏幕截图是“透视”或“宽格式”数据框。

    df_plot = pd.melt(df, id_vars='Date')
    df_plot['Year'] = df_plot['Date'].dt.year
    df_plot['Month'] = df_plot['Date'].dt.strftime('%b')
    
    import seaborn as sns
    plot = sns.catplot(data=df_plot, x='Month', y='value',
                       row='Year', col='variable', kind='bar',
                       sharex=False)
    plot.savefig('figure.png', dpi=300)
    

    结果(所有数字都是随机生成的):

    【讨论】:

      猜你喜欢
      • 2017-09-29
      • 1970-01-01
      • 1970-01-01
      • 2019-09-11
      • 2017-11-16
      • 2012-10-17
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      相关资源
      最近更新 更多