If we want to compare two sets of data while preserving knowledge of the total between them, we can also stack the bars instead of putting them side by side. For instance, if someone was plotting the hours they’ve spent on entertaining themselves with video games and books in the past week, and wanted to also get a feel for total hours spent on entertainment, they could create a stacked bar chart:


We do this by using the keyword bottom. The top set of bars will have bottom set to the heights of the other set of bars. So the first set of bars is plotted normally:

video_game_hours = [1, 2, 2, 1, 2] plt.bar(range(len(video_game_hours)), video_game_hours)

and the second set of bars has bottom specified:

book_hours = [2, 3, 4, 2, 1] plt.bar(range(len(book_hours)), book_hours, bottom=video_game_hours)

This starts the book_hours bars at the heights of the video_game_hours bars. So, for example, on Monday the orange bar representing hours spent reading will start at a value of 1 instead of 0, because 1 hour was spent playing video games.

Let’s try this out with the MatplotSip data from the last exercise.



You just made a chart with two sets of sales data plotted side by side. Let’s instead make a stacked bar chart by using the keyword bottom. Put the sales1 bars on the bottom and set the sales2 bars to start where the sales1 bars end.


We should add a legend to make sure we know which set of bars corresponds to which location. Label the bottom set of bars as “Location 1” and the top set of bars as “Location 2” and add a legend to the chart.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?