Histograms

histplot, bins, hue, and stacking.

sns.histplot counts values into bins. hue splits the fill. multiple="stack" stacks groups; "dodge" places them side by side.

Goal

Draw a histogram of units, then stack by city.

One sample

rng = np.random.default_rng(0)
df = pd.DataFrame({"units": rng.integers(1, 20, size=80)})
sns.histplot(data=df, x="units", bins=10)
plt.title("Units")
plt.show()

Hue and stack

rng = np.random.default_rng(0)
df = pd.DataFrame(
    {
        "city": rng.choice(["Nairobi", "Mombasa", "Kisumu"], size=80),
        "units": rng.integers(1, 20, size=80),
    }
)
sns.histplot(data=df, x="units", hue="city", multiple="stack", bins=10)
plt.title("Stacked by city")
plt.show()

Density instead of counts

rng = np.random.default_rng(1)
df = pd.DataFrame(
    {
        "city": rng.choice(["Nairobi", "Mombasa"], size=100),
        "units": np.concatenate(
            [rng.normal(8, 2.5, size=50), rng.normal(14, 3, size=50)]
        ),
    }
)
sns.histplot(data=df, x="units", hue="city", stat="density", common_norm=False, bins=12)
plt.title("Density")
plt.show()

stat="density" makes the area of each group 1 when common_norm=False, so two cities with different row counts still compare fairly.

Tip

Too few bins hide shape; too many look noisy. Start around 10 for this toy data.