首页 > 解决方案 > 每月每一天的子图,按月分组,X 轴按小时分组

问题描述

我需要创建一个 6x5 的子图,其中每个图代表一个月中的一天(1-30)并按月分组。

下面的示例数据有一些虚拟变量“September-December”,如果是那个月,则存在 1(可能在分组时有帮助)。每行代表一天中那个小时的销售数量。

样本数据:

在此处输入图像描述

这是 1 个图的示例,但是这已将所有数据汇总到 1 个图中,我想按月中的日期将其分解,因此应该有 30 个图,其中 X 轴是一天中的小时(1-24 ),并且图例包含月份 9-12(基本上按月份分组),并且这些值是 count 变量的聚合(总和)。

fig, ax = plt.subplots()
ax.set_xticks(df['hour'].unique())
df.groupby(["hour", "month"]).sum()['count'].unstack().plot(ax=ax)

在此处输入图像描述

我发现一些可能有用的代码是:

fig = plt.figure(figsize=(20, 20))
ax.set_ylabel('aggregated (sum) of count variable')
for i in range(1,31):
    df_daily = df[df['day'] == i] # select dataframe with day = i
    ax = fig.add_subplot(30,1,i) # add subplot in the i-th position on a grid 30x1   
    ax.plot(df_daily['day'], df_daily['count'])
    ax.set_xticks(df_daily['hour'].unique()) # set x axis 

但它输出了一个奇怪的子图:

在此处输入图像描述

标签: pythonmatplotlibsubplottimeserieschart

解决方案


推荐阅读