gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:07:17 24 4
gpt4 key购买 nike

我正在尝试绘制一些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

最佳答案

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

关于python - Pandas dataframe + groupby = x 轴刻度缩放失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43242246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com