Skip to content Skip to sidebar Skip to footer

Python Pandas - Plotting Multiple Bar Plots By Category From Dataframe

I have dataframe which looks like df = pd.DataFrame(data={'ID':[1,1,1,2,2,2], 'Value':[13, 12, 15, 4, 2, 3]}) Index ID Value 0 1 13 1 1 12 2 1 15 3 2 4 4 2 2

Solution 1:

2 options are possible, one using matplotlib and the other seaborn that you should absolutely now as it works well with Pandas.

Pandas with matplotlib

You have to create a subplot with a number of columns and rows you set. It gives an array axes in 1-D if either nrows or ncols is set to 1, or in 2-D otherwise. Then, you give this object to the Pandas plot method.

If the number of categories is not known or high, you need to use a loop.

import pandas as pd
import matplotlib.pyplot as plt

fig, axes = plt.subplots( nrows=1, ncols=2, sharey=True )

df.loc[ df["ID"] == 1, 'Value' ].plot.bar( ax=axes[0] )
df.loc[ df["ID"] == 2, 'Value' ].plot.bar( ax=axes[1] )

plt.show()

Output matplotlib/Pandas

Pandas with seaborn

Seaborn is the most amazing graphical tool that I know. The function catplot enables to plot a series of graph according to the values of a column when you set the argument col. You can select the type of plot with kind.

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

sns.set_style('white')

df['index'] = [1,2,3] * 2
sns.catplot(kind='bar', data=df, x='index', y='Value', col='ID')
plt.show()

Output Pandas/Seaborn

I added a column index in order to compare with the df.plot.bar. If you don't want to, remove x='index' and it will display an unique bar with errors.

Seaborn combines the values by category


Post a Comment for "Python Pandas - Plotting Multiple Bar Plots By Category From Dataframe"