CHRD
CHRD

Reputation: 1957

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?

Upvotes: 4

Views: 7064

Answers (3)

Scott Boston
Scott Boston

Reputation: 153560

Not sure exactly what you want but you can try this:

df.set_index(['X','Z'])['Y'].unstack().plot.barh()

enter image description here

Or

df.set_index(['X','Z'])['Y'].unstack().plot.bar()

enter image description here

Or

df.set_index(['X','Z'])['Y'].unstack().plot.barh(subplots=True, layout=(1,2))

enter image description here

or

df.set_index(['X','Z'])['Y'].unstack().plot.bar(subplots=True, layout=(1,2))

enter image description here

Upvotes: 2

ansev
ansev

Reputation: 30940

Use DataFrame.pivot with DataFrame.plot.barh:

df.pivot(*df).plot.barh()

enter image description here

or

df.pivot(*df).plot(kind = 'bar')

enter image description here

Upvotes: 2

Andrea
Andrea

Reputation: 3077

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

Upvotes: 6

Related Questions