【问题标题】:How to plot a grouped bar plot of count from pandas如何绘制熊猫计数的分组条形图
【发布时间】:2021-10-24 06:09:14
【问题描述】:

我有一个包含以下列的数据框:

gender     class

male       A
female     A
male       B
female     B
male       B
female     A

我想绘制一个双条形图,其中列作为每种性别,值分别作为 A 类和 B 类中每种性别的数量。

因此,条形应该按性别分组,并且应该有 2 个条 - 每个类别一个。

我如何将其可视化?我看到了这个例子,但我真的很困惑

speed = [0.1, 17.5, 40, 48, 52, 69, 88]
lifespan = [2, 8, 70, 1.5, 25, 12, 28]
index = ['snail', 'pig', 'elephant',
         'rabbit', 'giraffe', 'coyote', 'horse']
df = pd.DataFrame({'speed': speed,
                   'lifespan': lifespan}, index=index)

          speed  lifespan
snail       0.1       2.0
pig        17.5       8.0
elephant   40.0      70.0
rabbit     48.0       1.5
giraffe    52.0      25.0
coyote     69.0      12.0
horse      88.0      28.0

ax = df.plot.bar(rot=0)

我的索引只是第 0 行到行数,所以我很困惑如何配置 df.plot.bar 以使用我的用例。任何帮助将不胜感激!

【问题讨论】:

    标签: python pandas matplotlib seaborn bar-chart


    【解决方案1】:
    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    data = {'gender': ['male', 'female', 'male', 'female', 'male', 'female'], 'class': ['A', 'A', 'B', 'B', 'B', 'A']}
    df = pd.DataFrame(data)
    
    # pivot the data and aggregate
    dfp = df.pivot_table(index='gender', columns='class', values='class', aggfunc='size')
    
    # plot
    dfp.plot(kind='bar', figsize=(5, 3), rot=0)
    plt.show()
    

    plt.figure(figsize=(5, 3))
    sns.countplot(data=df, x='gender', hue='class')
    plt.show()
    

    sns.catplot(kind='count', data=df, x='gender', hue='class', height=3, aspect=1.4)
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-29
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 2016-09-27
      相关资源
      最近更新 更多