Can we stack more than 2 bars in a bar chart?


#1

Question

In the context of this exercise, can we stack more than 2 bars on top of each other?

Answer

Yes, you can absolutely stack more than 2 bars on a bar chart.

In order to do this, the bottom of each subsequent set of bars should equal the total heights of the bars below them.

Example

# Given the follow y values for 3 groups of data
group1 = [1, 1, 1, 1]
group2 = [2, 2, 2, 2]
group3 = [3, 3, 3, 3]

x = [0, 1, 2, 3] # x positions

# First layer of bars
plt.bar(x, group1)

# Second layer of bars
plt.bar(x, group2, bottom=group1)

# Adding a third layer of bars.
# Calculate the bottom height of the third layer
# by adding together all lower layer heights.
bottom_of_3 = [1+2, 1+2, 1+2, 1+2] # [3, 3, 3, 3]

# Third layer of bars
plt.bar(x, group3, bottom=bottom_of_3)