Home > Software design >  Making a grouped barchart with matplotlib,
Making a grouped barchart with matplotlib,

Time:02-23

I want to make a bar chart where netwrok is in the x axis and spend is in the y axis, but I also want to group the bar chart of the same network together, even if they have the same month, how can i do this? some of the networks do not have spend one whole month This will be run monthly so separating by month in this one instance will not work, I want to make it as automated as possible

month network spend
9 CNBC 24
9 BBC 10
10 BBC 10
9 Com 10
9 BLOM 10

CodePudding user response:

You can try to pivot your dataframe and then plot. Consider this code:

import pandas as pd
import matplotlib.pyplot as plt

d = {'month': [9,9,10,9,9], 'network': ['CNBC', 'BBC', 'BBC', 'Com', 'BLOM'], 'spend': [24,10,10,10,10]}
df = pd.DataFrame(data=d)

df = df.pivot(index='network', columns='month', values='spend')
df.plot.bar()
plt.show(block=True)

This will show you the grouped plot as

Grouped Plot

In my opinion, stacked plot looks even better for your data. If you want stacked plot. Just change it to df.plot.bar(stacked=True)
Stacked Plot

  • Related