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

时间:2017-04-05 21:50:30

标签: python pandas plot zoom

我正在尝试绘制一些pandas数据框数据,但是当使用groupby将其组织为每日/每月/每年总和时,生成的图无法正确缩放。

缩放确实有效,但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函数,它可以正常工作但我需要能够总结几个月等。

简介: enter image description here

大幅放大后的绘图(整个x轴可能只有几秒宽): enter image description here

1 个答案:

答案 0 :(得分:2)

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)

enter image description here

缩放后

enter image description here

说明:

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