Reputation: 1957
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
Reputation: 153560
Not sure exactly what you want but you can try this:
df.set_index(['X','Z'])['Y'].unstack().plot.barh()
Or
df.set_index(['X','Z'])['Y'].unstack().plot.bar()
Or
df.set_index(['X','Z'])['Y'].unstack().plot.barh(subplots=True, layout=(1,2))
or
df.set_index(['X','Z'])['Y'].unstack().plot.bar(subplots=True, layout=(1,2))
Upvotes: 2
Reputation: 30940
Use DataFrame.pivot
with DataFrame.plot.barh
:
df.pivot(*df).plot.barh()
or
df.pivot(*df).plot(kind = 'bar')
Upvotes: 2