Ranking

Sorted horizontal bars.

Sorted horizontal bars.

Goal

Run every block and look at the Plot panel.

df = pd.DataFrame({
    "city": ["Nairobi", "Mombasa", "Kisumu", "Nakuru", "Eldoret"],
    "units": [21, 15, 15, 18, 12],
    "shillings": [2100, 1500, 1480, 1750, 1190],
})
ord_ = df.sort_values("units")
plt.barh(ord_["city"], ord_["units"])
plt.title("Quietest → busiest")
plt.show()
df = pd.DataFrame({
    "city": ["Nairobi", "Mombasa", "Kisumu", "Nakuru", "Eldoret"],
    "units": [21, 15, 15, 18, 12],
    "shillings": [2100, 1500, 1480, 1750, 1190],
})
ord_ = df.sort_values("units", ascending=False)
plt.barh(ord_["city"], ord_["units"])
plt.gca().invert_yaxis()
plt.title("Busiest at the top")
plt.show()
df = pd.DataFrame({
    "city": ["Nairobi", "Mombasa", "Kisumu", "Nakuru", "Eldoret"],
    "units": [21, 15, 15, 18, 12],
    "shillings": [2100, 1500, 1480, 1750, 1190],
})
ord_ = df.sort_values("shillings")
plt.barh(ord_["city"], ord_["shillings"], color="#1d4f7a")
plt.title("Ranked by shillings")
plt.show()
df = pd.DataFrame({
    "city": ["Nairobi", "Mombasa", "Kisumu", "Nakuru", "Eldoret"],
    "units": [21, 15, 15, 18, 12],
    "shillings": [2100, 1500, 1480, 1750, 1190],
})
plt.bar(df["city"], df["units"])
plt.title("Unsorted bars hide the ranking")
plt.show()
Pitfall

Always plt.show(). Paste the whole editor.