sns.barplot aggregates a numeric column (mean by default). sns.countplot counts rows. Error bars on barplot are a confidence interval around that mean.
Goal
Draw mean revenue by city, grouped bars by product, and a count of rows.
Mean bars
df = pd.DataFrame(
{
"city": ["Nairobi", "Nairobi", "Mombasa", "Mombasa", "Kisumu", "Kisumu"] * 2,
"product": ["A", "B"] * 6,
"units": [12, 7, 9, 4, 11, 3, 10, 8, 6, 5, 14, 2],
"price": [10.5, 22.0, 10.5, 22.0, 10.5, 22.0] * 2,
}
)
df["revenue"] = df["units"] * df["price"]
sns.barplot(data=df, x="city", y="revenue")
plt.title("Mean revenue")
plt.show()Hue
df = pd.DataFrame(
{
"city": ["Nairobi", "Nairobi", "Mombasa", "Mombasa", "Kisumu", "Kisumu"] * 2,
"product": ["A", "B"] * 6,
"units": [12, 7, 9, 4, 11, 3, 10, 8, 6, 5, 14, 2],
"price": [10.5, 22.0, 10.5, 22.0, 10.5, 22.0] * 2,
}
)
df["revenue"] = df["units"] * df["price"]
sns.barplot(data=df, x="city", y="revenue", hue="product")
plt.title("Mean revenue by product")
plt.show()Sum, no error bar
df = pd.DataFrame(
{
"city": ["Nairobi", "Nairobi", "Mombasa", "Mombasa", "Kisumu", "Kisumu"] * 2,
"product": ["A", "B"] * 6,
"units": [12, 7, 9, 4, 11, 3, 10, 8, 6, 5, 14, 2],
"price": [10.5, 22.0, 10.5, 22.0, 10.5, 22.0] * 2,
}
)
df["revenue"] = df["units"] * df["price"]
sns.barplot(data=df, x="city", y="revenue", estimator="sum", errorbar=None)
plt.title("Total revenue")
plt.show()Counts
df = pd.DataFrame(
{
"city": ["Nairobi", "Nairobi", "Mombasa", "Mombasa", "Kisumu", "Kisumu"] * 2,
"product": ["A", "B"] * 6,
}
)
sns.countplot(data=df, x="city", hue="product")
plt.title("Rows per city")
plt.show()countplot has no y= — it counts rows. Use it for categories; use barplot for a numeric column you want to average or sum.
Pitfall
Default barplot is the mean, not the sum. For a sales total, pass estimator="sum" or groupby first.