Stacked bar chart
A stacked bar chart contains bars, where the height of each bar represents values. In addition, stacked on top of the first variable may be another variable. The additional height of this bar represents the value of this variable. And you can add more bars on top of that.
In this exercise, you will have access to a DataFrame called medals
that contains an index that holds the names of different countries, and three columns: "Gold"
, "Silver"
and "Bronze"
. You will also have a Figure, fig
, and Axes, ax
, that you can add data to.
You will create a stacked bar chart that shows the number of gold, silver, and bronze medals won by each country, and you will add labels and create a legend that indicates which bars represent which medals.
This exercise is part of the course
Introduction to Data Visualization with Matplotlib
Exercise instructions
- Call the
ax.bar
method to add the"Gold"
medals. Call it with thelabel
set to"Gold"
. - Call the
ax.bar
method to stack"Silver"
bars on top of that, using thebottom
key-word argument so the bottom of the bars will be on top of the gold medal bars, andlabel
to add the label"Silver"
. - Use
ax.bar
to add"Bronze"
bars on top of that, using thebottom
key-word andlabel
it as"Bronze"
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Add bars for "Gold" with the label "Gold"
____(____, ____, label=____)
# Stack bars for "Silver" on top with label "Silver"
____(____, ____, bottom=____, ____)
# Stack bars for "Bronze" on top of that with label "Bronze"
____
# Display the legend
ax.legend()
plt.show()