【问题标题】:How to create a grouped bar plot of categorical counts如何创建分类计数的分组条形图
【发布时间】:2021-10-24 20:56:54
【问题描述】:

这可能是一项简单的任务,但我是 Python 绘图新手,很难将逻辑转换为代码。我正在使用下面的代码,但我想将橙色和蓝色线分开(不叠加)。我需要创建一个将 2 个条分开的水平条图吗?

df = pd.DataFrame({'a':[1,2,3,1,2,2,2],
             'b':[1,1,1,3,2,2,2]})
ax = df['a'].value_counts().plot(kind='barh', color='skyblue', width=.75, legend=True, alpha=0.8)
df['b'].value_counts().plot(kind='barh', color='orange', width=.5, alpha=1, legend=True)

【问题讨论】:

    标签: python pandas matplotlib seaborn bar-chart


    【解决方案1】:
    import seaborn as sns
    import matplotlib.pyplot as plt
    import pandas as pd
    
    df = pd.DataFrame({'a':[1,2,3,1,2,2,2], 'b':[1,1,1,3,2,2,2]})
    
    # convert to long form
    df = df.melt()
    
    # pivot_table and aggregate
    df = df.pivot_table(index='value', columns='variable', values='value', aggfunc='size')
    
    # plot
    df.plot(kind='barh', figsize=(4, 3))
    ax.legend(bbox_to_anchor=(1, 1.02), loc='upper left')
    plt.show()
    

    seaborn.countplot

    df = pd.DataFrame({'a':[1,2,3,1,2,2,2], 'b':[1,1,1,3,2,2,2]})
    
    plt.figure(figsize=(4, 3))
    p = sns.countplot(data=df.melt(), y='value', hue='variable')
    p.legend(bbox_to_anchor=(1, 1.02), loc='upper left')
    plt.show()
    

    【讨论】:

      【解决方案2】:

      试试这个:

      df['a'].value_counts().to_frame('a').join(df['b'].value_counts().to_frame('b')).plot(kind='barh')
      

      【讨论】:

        猜你喜欢
        • 2018-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-14
        • 1970-01-01
        相关资源
        最近更新 更多