Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib side by side bar plot

I am trying to plot the following dataframe using matplotlib:

df = pd.DataFrame({'X': ["A", "A", "B", "B"], 'Z': ["a", "b", "a", "b"], 'Y': [5, 1, 10, 5]})
df

    X   Z   Y
0   A   a   5
1   A   b   1
2   B   a   10
3   B   b   5

What I want is two bar plots where the bars are next to each other rather than on top of each other. When I run this the bars are placed on top of each other:

plt.barh(df['X'][df['Z'] == "a"], df['Y'][df['Z'] == "a"], color = 'blue')
plt.barh(df['X'][df['Z'] == "b"], df['Y'][df['Z'] == "b"], color = 'red')

And whe I try changing the position of the bars I get the error: can only concatenate str (not "float") to str. How can I work around this?

like image 397
CHRD Avatar asked Sep 19 '25 00:09

CHRD


1 Answers

If you want to have the bars side by side you can use the seaborn library:

import seaborn as sns
sns.barplot(data=df, x='Y', hue='Z', y='X')

enter image description here

like image 168
Andrea Avatar answered Sep 20 '25 14:09

Andrea