如何用泛统计方法绘制堆积条形图?

2024-05-21 00:48:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据框架主要是分类列:

df = pd.DataFrame({
     'col_to_group': ['A', 'A', 'B', 'B', 'A'],
     'col_1': ['a', 'b', 'c', 'a', 'a'],
     'col_2': ['x', 'y', 'y', 'y','x'],
     'col_3': [.1, .2, .1, .9, .7]
})

基本上,我想绘制col_1col_2的条形图,按col_to_group(A,B)的子组和整个数据帧(ALL)。你知道吗

以下是我目前的解决方案:

import pandas as pd
import matplotlib.pyplot as plt


df = pd.DataFrame({
     'col_to_group': ['A', 'A', 'B', 'B', 'A'],
     'col_1': ['a', 'b', 'c', 'a', 'a'],
     'col_2': ['x', 'y', 'y', 'y','x'],
     'col_3': [.1, .2, .1, .9, .7]
})

for i in ['col_1', 'col_2']: 
    L = df.groupby('col_to_group')[i].value_counts(normalize=True).unstack().T
    R = df[i].value_counts(normalize=True).rename('ALL')
    z = pd.concat([L, R], axis=1, sort=True).T
    #z.T.to_csv(i+'_bar.csv')
    #plotting:
    zz = z.plot.bar(stacked=True).legend(bbox_to_anchor=(1.0, 1.0)).get_figure()
    plt.title(i, fontsize = 12)
    zz.savefig(i+'_bar.png', dpi=300, bbox_inches='tight') 
    plt.show()

z创造是复杂的,而且我不是matplotlib的粉丝-它能在一行中完成吗?你知道吗

我在寻找潘多斯特的解决方案。你知道吗


Tags: to数据importtruedataframedfmatplotlibas
2条回答

在深入研究文档之后,我发现crosstabmarginsnormalize=index更巧妙地解决了我的问题。你知道吗

import pandas as pd


df = pd.DataFrame({
     'col_to_group': ['A', 'A', 'B', 'B', 'A'],
     'col_1': ['a', 'b', 'c', 'a', 'a'],
     'col_2': ['x', 'y', 'y', 'y','x'],
     'col_3': [.1, .2, .1, .9, .7]
})


for i in ['col_1', 'col_2']:
    (pd.crosstab(df['col_to_group'], df[i], margins=True, margins_name='ALL', normalize='index')
       .plot.bar(stacked=True).legend(title=i, bbox_to_anchor=(1.0, 1.0)).get_figure()
       .savefig(i + '_bar.png', dpi=300, bbox_inches='tight')
    )

我会这样做:

df1=df.groupby('col_to_group')['col_1','col_2'].apply(lambda x: x.apply(lambda x: x.value_counts(normalize=True),axis=0)).unstack(level=1).dropna(how='all',axis=1).fillna(0)
print(df1)

                 col_1                    col_2          
                     a         b    c         x         y
col_to_group                                             
A             0.666667  0.333333  0.0  0.666667  0.333333
B             0.500000  0.000000  0.5  0.000000  1.000000

df2=df[['col_1','col_2']].apply(lambda x: x.value_counts(normalize=True)).unstack().dropna().rename('ALL').to_frame().T
print(df2)


    col_1           col_2     
        a    b    c     x    y
ALL   0.6  0.2  0.2   0.4  0.6

plot_df=pd.concat([df1,df2])
print(plot_df)


        col_1                    col_2          
            a         b    c         x         y
A    0.666667  0.333333  0.0  0.666667  0.333333
B    0.500000  0.000000  0.5  0.000000  1.000000
ALL  0.600000  0.200000  0.2  0.400000  0.600000

plot_df['col_1'].plot(kind='bar',stacked=True)
plot_df['col_2'].plot(kind='bar',stacked=True)

enter image description here

enter image description here

相关问题 更多 >