Understand the idea
Stacked bars add components with the same units. The bottom parameter sets where the upper segment starts.
A small example
A base count of 3 and upper count of 2 make a total height of 5; the upper segment starts at 3.
Follow the code
Apply the idea to the supplied table. Read from top to bottom; the final line displays the result.
import matplotlib.pyplot as plt
import seaborn as sns
fig, ax = plt.subplots(figsize=(6, 4))
first = df["Solo"]
second = df["Two players"]
ax.bar(df["genre"], first, label="Solo")
ax.bar(df["genre"], second, bottom=first, label="Two players")
ax.legend()
ax.set(title="Game sessions", xlabel="genre", ylabel="Count")
fig.tight_layout()
plt.show()What each part does
ax.bar(..., bottom=first)- stack above first
label=- name each component
ax.legend()- show component names
Your inputs
The editable setup on the right creates df. Run executes the setup and your work from top to bottom.
| genre | Solo | Two players |
|---|---|---|
| Puzzle | 2 | 1 |
| Strategy | 1 | 2 |
| Adventure | 0 | 2 |
| Family | 3 | 1 |
Your task · Follow
- Use df's actual Solo and Two players counts to draw stacked bars by genre, in table order.
- Put Solo at the base and Two players above it; label both components in a legend.
- Chart: title "Game sessions"; x "genre"; y "Count".
Hint
The upper bars need bottom equal to the lower component, not zero.
Reveal solution
One way to do it. Keep any supplied setup in the editor and use this in the Your work section.
import matplotlib.pyplot as plt
import seaborn as sns
fig, ax = plt.subplots(figsize=(6, 4))
first = df["Solo"]
second = df["Two players"]
ax.bar(df["genre"], first, label="Solo")
ax.bar(df["genre"], second, bottom=first, label="Two players")
ax.legend()
ax.set(title="Game sessions", xlabel="genre", ylabel="Count")
fig.tight_layout()
plt.show()