How can I plot a stacked graph in Python?

72 Views Asked by At
Group_1= {60: 2, 65: 2}
Group_2= {5: 2, 10: 2}
Group_3= {7: 2, 64: 2}
Group_4= {14: 2}

These are the 4 different dictionaries, and my aim is to plot a stacked graph on which

  • x-axis = Group Numbers
  • y-axis = values of the dictionaries only.

I do not want keys in the graph, and Group_4 has the only single key and value as a data. I've also attached the image.

I am getting an error:

ValueError: shape mismatch: objects cannot be broadcast to a single shape.

2

There are 2 best solutions below

0
mozway On

One option using :

import pandas as pd

groups = {1: Group_1, 2: Group_2, 3: Group_3, 4: Group_4}

pd.DataFrame.from_dict(groups, orient='index').plot.bar(stacked=True)

Output:

enter image description here

Variant:

(pd.DataFrame.from_dict({k: list(d.values())
                         for k, d in groups.items()},
                         orient='index')
   .plot.bar(stacked=True, legend=False)
)

Output:

enter image description here

0
thmslmr On

One option using matplotlib bar plot.

import matplotlib.pyplot as plt

# Create a single structure to hold your groups. Could work with a list as well.
groups = {"1": G1.values(), "2": G2.values(), "3": G3.values(), "4": G4.values()}

for x, values in groups.items():
    bottom = 0
    for value in values:
        plt.bar(x, value, bottom=bottom)
        bottom += value

enter image description here