Understand the idea
Bar length represents magnitude, so use a zero baseline. Choose an order that supports the comparison without changing the values.
A small example
Values 4 and 5 differ by 25%. A y-axis beginning at 3 exaggerates their apparent bar-length ratio.
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))
means = df.groupby("flavour")["price"].mean().sort_values(ascending=False)
ax.bar(means.index, means.values)
ax.set_ylim(bottom=0)
ax.set(title="Candy shop", xlabel="flavour", ylabel="Mean price")
fig.tight_layout()
plt.show()What each part does
sort_values(ascending=False)- a meaningful category order
ax.set_ylim(bottom=0)- honest bar-length baseline
Other choices for later exercises
alpha=- transparency for overlapping points
order=[...]- set a deliberate category order
Your inputs
The editable setup on the right creates df. Run executes the setup and your work from top to bottom.
| candy | flavour | price | rating | shelf |
|---|---|---|---|---|
| Gummy Bear | fruity | 1.2 | 4.1 | A |
| Choco Pop | chocolate | 2.1 | 4.6 | B |
| Mint Bite | mint | 1.5 | 3.8 | A |
| Berry Loop | fruity | 2.8 | 4.4 | B |
| Cocoa Cube | chocolate | 3.4 | 4.9 | A |
| Lemon Drop | fruity | 1.8 | 4 | B |
Your task · Follow
- Using df, compare mean price by flavour as bars, highest mean first.
- Start the y-axis at zero so lengths represent the price comparison fairly.
- Chart: title "Candy shop"; x "flavour"; y "Mean price".
Hint
Choose the observations first, then map the requested measurements to the chart.
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))
means = df.groupby("flavour")["price"].mean().sort_values(ascending=False)
ax.bar(means.index, means.values)
ax.set_ylim(bottom=0)
ax.set(title="Candy shop", xlabel="flavour", ylabel="Mean price")
fig.tight_layout()
plt.show()