将多个柱状图子图叠加到一个PDF中 (python, matplotlib)

问题描述 投票:0回答:1

我正在为疯狂的副图而苦恼。我做了一堆条形图,我想依次保存到一个PDF中。每张图都总结了一个二进制变量(通常是堆叠的,但如果简单点的话,不堆叠也可以)。这些图表都很好,但是当我尝试将它们放入子图的网格中时,我把它搞乱了!我的问题是:1)我是在做一个子图。

我的问题是:1)我没有正确地迭代数据,2)我似乎不能堆叠一列图表--只能堆叠2列以上。

对不起,我问了这么一个蹩脚的问题,但这是我最接近的问题了!有什么建议吗?有什么建议吗?

df = pd.DataFrame(np.random.randint(0,2,size=(100, 12)), columns=list('ABCDEFGHIJKL')) #load data
key_vars = list('ABCDEFGH') #variables to plot
num_plots = len(key_vars) #number of subplots

fig, ax = plt.subplots(num_plots, 2, sharex='col', sharey='row') #create figure

for i in range(num_plots):
    for j in range(2):
        ax[i,j].barh(df[key_vars[i]].value_counts(),10) #create subplots

fig.savefig('binary_barcharts.pdf') #save to .pdf
python pandas matplotlib bar-chart subplot
1个回答
1
投票

你正在寻找这样的东西。

(df[key_vars].apply(pd.Series.value_counts
   .T.plot.bar(stacked=True)
)

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.