Python Pandas - Plotting Multiple Bar Plots By Category From Dataframe
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()
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()
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.
Post a Comment for "Python Pandas - Plotting Multiple Bar Plots By Category From Dataframe"