stacked bar plot using matplotlib

You need the bottom of each dataset to be the sum of all the datasets that came before. you may also need to convert the datasets to numpy arrays to add them together.

p1 = plt.bar(ind, dataset[1], width, color="r")
p2 = plt.bar(ind, dataset[2], width, bottom=dataset[1], color="b")
p3 = plt.bar(ind, dataset[3], width, 
             bottom=np.array(dataset[1])+np.array(dataset[2]), color="g")
p4 = plt.bar(ind, dataset[4], width,
             bottom=np.array(dataset[1])+np.array(dataset[2])+np.array(dataset[3]),
             color="c")

enter image description here

Alternatively, you could convert them to numpy arrays before you start plotting.

dataset1 = np.array(dataset[1])
dataset2 = np.array(dataset[2])
dataset3 = np.array(dataset[3])
dataset4 = np.array(dataset[4])

p1 = plt.bar(ind, dataset1, width, color="r")
p2 = plt.bar(ind, dataset2, width, bottom=dataset1, color="b")
p3 = plt.bar(ind, dataset3, width, bottom=dataset1+dataset2, color="g")
p4 = plt.bar(ind, dataset4, width, bottom=dataset1+dataset2+dataset3,
             color="c")

Or finally if you want to avoid converting to numpy arrays, you could use a list comprehension:

p1 = plt.bar(ind, dataset[1], width, color="r")
p2 = plt.bar(ind, dataset[2], width, bottom=dataset[1], color="b")
p3 = plt.bar(ind, dataset[3], width,
             bottom=[sum(x) for x in zip(dataset[1],dataset[2])], color="g")
p4 = plt.bar(ind, dataset[4], width,
             bottom=[sum(x) for x in zip(dataset[1],dataset[2],dataset[3])],
             color="c")

Leave a Comment