Home > Enterprise >  Creating a multi-bar plot in MatplotLib
Creating a multi-bar plot in MatplotLib

Time:09-30

Given a simple pd.Dataframe df that looks like this:

                                                      workflow  blocked_14  blocked_7  blocked_5  blocked_2  blocked_1
au_in_service_order_response      au_in_service_order_response       12.00      11.76      15.38       25.0        0.0
au_in_cats_sync_billing_period  au_in_cats_sync_billing_period        3.33       0.00       0.00        0.0        0.0
au_in_MeterDataNotification        au_in_MeterDataNotification        8.70       0.00       0.00        0.0        0.0

I want to create a bar-chart that shows the blocked_* columns as the x-axis.

Since df.plot(x='workflow', kind='bar') obviously puts the workflows on the x-axis, I tried ax = blocked_df.plot(x=['blocked_14','blocked_7',...], kind='bar') but this gives me

ValueError: x must be a label or position

How would I create 5 y-Values and have each bar show the according value of the workflow?

CodePudding user response:

Since pandas interprets the x as the index and y as the values you want to plot, you'll need to transpose your dataframe first.

import matplotlib.pyplot as plt

ax = df.set_index('workflow').T.plot.bar()
plt.show()

enter image description here

But that doesn't look too good does it? Let's ensure all of the labels fit on the Axes and move the legend outside of the plot so it doesn't obscure the data.

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(14, 6), layout='constrained')
ax = df.set_index('workflow').T.plot.bar(legend=False, ax=ax)
ax.legend(loc='upper left', bbox_to_anchor=(1, .8))
plt.show()

enter image description here

  • Related