Search code examples
pandasmatplotlibbar-chartgrouped-bar-chart

How to produce a multiple group bar chart based on a specific dataframe column


I have a dataframe which has the following data:

Age A
5   True
5   True
10  False
15  False
15  True
20  False
25  True

How can I make a bar chart plot which has the values of the total number of rows in Age? So for example, 7 as the Y axis and the age as the X axis, with each Age having a True/False bar plot.

I would like something like this, however instead of it saying gender F/M, it does True/False, for each Age range:

enter image description here


Solution

  • We can use DataFrame.value_counts() (pandas > 1.1.0) or SeriesGroupBy.value_counts() (pandas < 1.1.0) + DataFrame.plot

    df.value_counts().unstack(fill_value=0).plot(kind='bar')
    #df.groupby('A')['Age']\
    #  .value_counts().unstack(fill_value=0, level=0).plot(kind='bar') # <1.1.0
    

    enter image description here

    Also we could use seaborn.countplot

    import seaborn as sns
    sns.countplot(data=df, x="Age", hue="A")
    

    enter image description here