[英]Pandas dataframe + groupby = failed zooming for x-axis ticks
我正在嘗試繪制一些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
函數,它可以正常工作,但我需要能夠總結月份等。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.