Adler Müller
Adler Müller

Reputation: 248

Python bar chart with dataframe

I have the following dataframe:

df = pd.DataFrame(dict(
    A=[1, 0, 0, 1],
    B=[0, 1, 1, 1],
    C=[1, 0, 0, 0]
))

How to plot a barplot where I sea number of 1s and 0s in one graph see: enter image description here

Upvotes: 1

Views: 123

Answers (1)

Zephyr
Zephyr

Reputation: 12496

Starting from the dataset you provided:

df = pd.DataFrame(dict(
    A=[1, 0, 0, 1],
    B=[0, 1, 1, 1],
    C=[1, 0, 0, 0]
))

you should re-shape the dataframe with pandas.melt:

df = pd.melt(frame = df,
             var_name = 'class',
             value_name = 'survived')
   class  survived
0      A         1
1      A         0
2      A         0
3      A         1
4      B         0
5      B         1
6      B         1
7      B         1
8      C         1
9      C         0
10     C         0
11     C         0

So you can use seaborn.countplot to get the plot you want:

fig, ax = plt.subplots()

sns.countplot(ax = ax, data = df, x = 'class', hue = 'survived')

plt.show()

Complete Code

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns


df = pd.DataFrame(dict(
    A=[1, 0, 0, 1],
    B=[0, 1, 1, 1],
    C=[1, 0, 0, 0]
))

df = pd.melt(frame = df,
             var_name = 'class',
             value_name = 'survived')


fig, ax = plt.subplots()

sns.countplot(ax = ax, data = df, x = 'class', hue = 'survived')

plt.show()

enter image description here

Upvotes: 1

Related Questions