Stacked Bar Charts
Stacked bar charts allow comparison of multiple categories within each x-axis group. For example, rather than showing only the total GDP of each country, they can illustrate the contribution of individual economic sectors to the total.
import matplotlib.pyplot as plt import numpy as np countries = ['USA', 'China', 'Japan'] primary_sector = np.array([1.4, 4.8, 0.4]) secondary_sector = np.array([11.3, 6.2, 0.8]) tertiary_sector = np.array([14.2, 8.4, 3.2]) # Calling the bar() function multiple times for each category (sector) plt.bar(countries, primary_sector) plt.bar(countries, secondary_sector, bottom=primary_sector) plt.bar(countries, tertiary_sector, bottom=primary_sector + secondary_sector) plt.show()
To create stacked bars, the bar()
function is called multiple times—once for each sector. In each call, the same countries
list is used for the x-axis, and the bottom
parameter ensures that each new segment is stacked on top of the previous one.
Study More
The bottom
parameter specifies the y coordinate(s) of the bottom side(s) of the bars. Here is the bar()
documentation.
Compito
Swipe to start coding
- Use the correct function for creating bar charts.
- Plot the lower bars for
yes_answers
. - Plot the bars for
no_answers
on top of the bars foryes_answers
with specifying the correct keyword argument.
Soluzione
Tutto è chiaro?
Grazie per i tuoi commenti!
Sezione 2. Capitolo 5