gpt4 book ai didi

python - 使用 matplotlib 子图绘制 pandas groupby 输出

转载 作者:行者123 更新时间:2023-12-01 02:16:36 24 4
gpt4 key购买 nike

我有一个数据框,df2,有 6 行和 1591 列

           0.0.0   10.1.21  1.5.12   3.7.8  3.5.8  1.7.8 ...        
June 1 1 4 0 0 4
July 0 0 0 0 0 0
August 54 0 9 0 5 0
September 22 0 6 0 0 1
October 0 9 5 1 4 0

我想将图中每个面板中的 3 列中的多个绘制为堆叠条形。即列:0.0.0 到 1.5.12 将在单独的面板中绘制,而列:3.7.8 到 1.7.8 将在另一个面板中绘制。这是代码:

df= df2
df['key1'] = 0
df.key1.loc[:, ['0.0.0', '10.1.21', '1.5.12']].values = 1
df.key1.loc[:,['3.7.8', '3.5.8', '1.7.8']].values = 2
df.key1.loc[:,['4.4.3', '2.2.0', '2.8.0']].values = 3

# Plot in Three Panels
distinct_keys = df['key1'].unique()
fig, axes = pyplot.subplots(len(distinct_keys), 1, sharex=True, figsize= (3,5))

#{df_subset groups the rows with the same key in other to plot them in the same panel}

for i, key in enumerate(distinct_keys):
df_subset =df[df['key1']==key]

# plot
axes[i] = df_subset.plot(kind='bar', stacked=True)
pyplot.legend(bbox_to_anchor=(1.04,1), loc="upper right")
pyplot.subplots_adjust(right=0.7)
pyplot.tight_layout(rect=[0,0,0.75,1])
pyplot.savefig("output.png", bbox_inches="tight")

但我得到:IndexingError:索引器太多

最佳答案

初始化子图 -

fig, axs = plt.subplots(len(df.columns) // 3, 1, sharex=True) 

接下来,沿第一个轴执行 groupby,但先不要绘制。

gs = df.groupby(np.arange(len(df.columns)) // 3, axis=1)

最后,zip 轴和 groupby 输出,并一次绘制每一个。

for (_, g), ax in zip(gs, axs):
g.plot.bar(stacked=True, ax=ax)

plt.show()

enter image description here

关于python - 使用 matplotlib 子图绘制 pandas groupby 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48326627/

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