sns.heatmap colors a 2-D table. Pivot first so rows are cities and columns are months (or products). annot=True writes the numbers on the cells.
Goal
Pivot rainfall into a city × month table, draw a heatmap, and label the colorbar.
Pivot then heat
df = pd.DataFrame(
{
"month": ["Jan", "Feb", "Mar", "Apr"] * 3,
"city": ["Nairobi"] * 4 + ["Mombasa"] * 4 + ["Kisumu"] * 4,
"rain": [50, 40, 80, 150, 20, 15, 30, 90, 70, 80, 120, 180],
}
)
table = df.pivot(index="city", columns="month", values="rain")
table = table[["Jan", "Feb", "Mar", "Apr"]]
print(table)
sns.heatmap(table, annot=True, fmt=".0f", cmap="Blues")
plt.title("Rainfall (mm)")
plt.show()pivot needs unique city–month pairs. Select month columns so January is not sorted after April.
Correlation
rng = np.random.default_rng(0)
n = 80
df = pd.DataFrame(
{
"units": rng.integers(1, 20, size=n),
"price": rng.choice([10.5, 22.0, 31.0], size=n),
}
)
df["revenue"] = df["units"] * df["price"]
df["cost"] = df["units"] * rng.uniform(4, 9, size=n)
print(df.corr(numeric_only=True).round(2))
sns.heatmap(df.corr(numeric_only=True), annot=True, fmt=".2f", cmap="vlag", center=0)
plt.title("Correlation")
plt.show()center=0 on "vlag" puts white at zero so positive and negative correlations read as two colors.
Colorbar label
df = pd.DataFrame(
{
"city": ["Nairobi", "Nairobi", "Mombasa", "Mombasa", "Kisumu", "Kisumu"],
"product": ["A", "B"] * 3,
"units": [12, 7, 9, 4, 11, 3],
}
)
table = df.pivot(index="city", columns="product", values="units")
ax = sns.heatmap(table, annot=True, cmap="YlOrBr")
ax.collections[0].colorbar.set_label("units")
plt.title("Units")
plt.show()Pitfall
heatmap wants a matrix, not a long table. If you pass the raw sales log you will color every cell including city names and fail. pivot or pivot_table first.