Pandas dataframe + groupby = x 轴刻度缩放失败

Pandas dataframe + groupby = failed zooming for x-axis ticks

我正在尝试绘制一些 pandas 数据帧数据,但是当使用 groupby 将其组织成 daily/monthly/yearly 总和时,生成的图无法正确缩放。

缩放确实有效,但 x 轴刻度线未正确更新。我无法找到解决方案。

示例代码:

import datetime
import pandas as pd
import numpy as np

arraya = np.random.rand(1,100)[0]
arrayb = np.random.rand(1,100)[0]
arrayc = np.random.rand(1,100)[0]
arrayd = np.random.rand(1,100)[0]

day_counts = {'A': arraya,
              'B': arrayb,
              'C': arrayc,
              'D': arrayd}

#prepare data
df_days = pd.DataFrame(day_counts, index=pd.date_range('2012-01-01', periods=100))
#df_use = df_days.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day]).sum()
df_use = df_days.groupby([lambda x: x.year, lambda x: x.month]).sum()

#prepare percentages
df_use_perc = df_use.divide(df_use.sum(axis=1), axis=0).multiply(100) #percentages

my_colors = list(['orange', 'blue', 'purple', 'red'])

#plot the main subfigure (relative event types)
ax = df_use_perc.plot(kind='area', stacked=True, color=my_colors)

导致失败的是这一行:

df_use = df_days.groupby([lambda x: x.year, lambda x: x.month]).sum()

我可以只使用数据框 df_days 绘制它,而不使用 groupby 函数,它工作正常,但我需要能够总结月份等

剧情:

大规模放大后绘制(整个x轴可能只有几秒宽):

IIUC 您可以执行以下操作:

x = df_days.groupby(pd.TimeGrouper('MS')).sum()
x.div(x.sum(1), 0).mul(100).plot(kind='area', stacked=True, color=my_colors)

缩放后:

解释:

In [35]: x
Out[35]:
                    A          B          C          D
2012-01-01  14.739981  18.306502  11.659834  13.990243
2012-02-01  13.180681  12.487874  15.367421  16.877128
2012-03-01  14.528299  16.936493  16.467844  16.668185
2012-04-01   4.190121   3.110165   5.165066   3.086899

In [36]: x.div(x.sum(1), 0).mul(100)
Out[36]:
                    A          B          C          D
2012-01-01  25.112171  31.188374  19.864594  23.834861
2012-02-01  22.759411  21.563123  26.535309  29.142158
2012-03-01  22.489341  26.217149  25.491695  25.801815
2012-04-01  26.942217  19.998167  33.211047  19.848569