Seaborn Barplot: Estimators, Error Bars, and Colors in sns.barplot()

What sns.barplot() actually draws (a mean and a 95% bootstrap confidence interval), and how to change it: estimator= for sums and medians, errorbar= for standard deviation or no bars, horizontal bars, colors, and the parameters deprecated in Seaborn 0.13.

sns.barplot(data=df, x="category", y="value") draws one bar per category, and the bar height is the mean of that category's rows, not their sum. The black line on each bar is a 95% confidence interval for that mean. Change the statistic with estimator= ("sum", "median") and the line with errorbar= ("sd", "se", or None). The examples use Seaborn 0.13.

Quick Example

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

rng = np.random.default_rng(57)
frames = []
for service, mean, sd, n in [("Dash", 34, 9, 120), ("Swift", 29, 6, 90),
                             ("Parcelo", 41, 15, 60), ("Bikebox", 26, 5, 45)]:
    day = rng.choice(["Weekday", "Weekend"], n, p=[0.7, 0.3])
    minutes = rng.gamma((mean / sd) ** 2, sd**2 / mean, n) + np.where(day == "Weekend", 4, 0)
    frames.append(pd.DataFrame({"service": service, "day": day, "minutes": minutes.round(1)}))
orders = pd.concat(frames, ignore_index=True)  # one row per delivery

sns.set_theme(style="ticks")
fig, ax = plt.subplots(figsize=(7, 4.5))
sns.barplot(data=orders, x="service", y="minutes", color="#5b8e7d", capsize=0.2, ax=ax)
ax.set(title="Average delivery time", xlabel="", ylabel="Minutes")
sns.despine()
plt.show()

Seaborn bar plot of average delivery time with 95 percent confidence interval error bars: Dash about 35 minutes, Swift 30, Parcelo 42 with the widest interval, and Bikebox 27

orders has 315 rows, one per delivery. Seaborn groups them by service, averages minutes, and bootstraps the interval. Parcelo's interval is the widest because its delivery times vary the most (standard deviation 15.6 minutes, against 4.8 for Bikebox) and it has only 60 orders.

What does sns.barplot show?

Part Default Change it with
Bar height Mean of each category's rows estimator="sum", "median", "max", or any function
Error bar 95% bootstrap confidence interval of the estimate errorbar="sd", "se", ("pi", 50), ("ci", 90), or None
Bootstrap samples 1,000, random each run n_boot=, and seed= for repeatable intervals
Bar order Order of first appearance in the data order=[...]
Colors One color for every bar, or the palette with hue= color=, or hue= plus palette=

Because the default interval comes from random resampling, it can shift slightly each time you draw the chart. Pass seed=0 (any number) when the chart has to be identical between runs.

How do I plot the sum instead of the mean?

Pass estimator="sum". Any string that pandas understands as an aggregation works ("median", "max", "count"), and so does a function such as np.median:

fig, axs = plt.subplots(1, 3, figsize=(12, 4), layout="constrained")
for ax, estimator in zip(axs, ["mean", "median", "sum"]):
    sns.barplot(data=orders, x="service", y="minutes", estimator=estimator,
                errorbar=None, color="#5b8e7d", ax=ax)
    ax.bar_label(ax.containers[0], fmt="{:,.0f}", padding=2)
    ax.set(title=f'estimator="{estimator}"', xlabel="", ylabel="")
sns.despine()
plt.show()

Three bar charts of the same deliveries: the mean is 35, 30, 42, and 27 minutes, the median is 34, 30, 40, and 27, and the sum is 4,212, 2,704, 2,529, and 1,210 minutes for Dash, Swift, Parcelo, and Bikebox

The mean and median agree except for Parcelo (42 vs 40 minutes), whose few very slow deliveries pull its mean up. The sum ranks the services differently, because it mostly reflects how many orders each one handled: Dash has the most total minutes with 120 deliveries. To count rows rather than add a column, sns.countplot is simpler.

Change or remove the error bars

errorbar= picks what the line on each bar shows. The four common choices, on the same data:

options = [("ci", 95), "se", "sd", ("pi", 50)]

fig, axs = plt.subplots(1, 4, figsize=(14, 4), sharey=True, layout="constrained")
for ax, errorbar in zip(axs, options):
    sns.barplot(data=orders, x="service", y="minutes", errorbar=errorbar, seed=0,
                capsize=0.25, color="#d1b47a", err_kws={"color": "#333333", "linewidth": 1.5},
                ax=ax)
    ax.set(title=f"errorbar={errorbar!r}", xlabel="", ylabel="")
sns.despine()
plt.show()

Four bar charts with the same bar heights but different error bars: the 95 percent confidence interval and standard error are short, while the standard deviation and the 50 percent percentile interval are much longer, especially for Parcelo

errorbar= The line shows Use it to say
("ci", 95) (default) Bootstrap 95% confidence interval of the mean How precisely the mean is known
"se" Mean ± one standard error The same idea, a shorter bar, no resampling
"sd" Mean ± one standard deviation How spread out the individual values are
("pi", 50) The middle 50% of the values (25th to 75th percentile) The typical range of single values
None Nothing The bars only; use this for already-summarized data

The confidence interval and standard error shrink as you add rows; the standard deviation and percentile interval don't. If readers will ask "how long will my delivery take?", show the spread ("sd" or "pi"). If they'll ask "which service is faster on average?", show the interval. err_kws= styles the lines, and capsize= adds the caps (as a fraction of the bar width). The confidence interval bands post covers the same options for line plots.

Plot data that's already summarized

If each category already has one row, such as a table of totals, there's nothing for Seaborn to average and no interval to compute. Pass errorbar=None so it doesn't try:

totals = (orders.groupby("service", as_index=False)["minutes"].count()
          .rename(columns={"minutes": "deliveries"})
          .sort_values("deliveries", ascending=False))

fig, ax = plt.subplots(figsize=(7, 3.6))
sns.barplot(data=totals, x="deliveries", y="service", errorbar=None,
            hue="service", palette="crest", legend=False, ax=ax)
for container in ax.containers:  # one container per hue level
    ax.bar_label(container, padding=3)
ax.set(xlabel="Deliveries", ylabel="")
sns.despine(left=True)
plt.show()

Horizontal Seaborn bar chart of delivery counts sorted from largest to smallest: Dash 120, Swift 90, Parcelo 60, and Bikebox 45, each bar a different shade of the crest palette

This also shows two other common requests:

  • Horizontal bars: put the numbers on x and the categories on y. Seaborn works out the orientation from the column types; orient="h" forces it.
  • Bars sorted by value: sort the DataFrame first, since bars follow the order of first appearance, or pass order=. See ordering categories.

hue="service" gives each bar its own color, and it also splits the bars into one container per service, which is why the labels loop over ax.containers. More label options are in bar plot value labels.

How do I give each bar its own color?

In Seaborn 0.13, set hue to the same column as the categories and turn the legend off: sns.barplot(data=df, x="service", y="minutes", hue="service", palette="Set2", legend=False). Passing palette= without hue= still works but raises a warning:

FutureWarning: Passing `palette` without assigning `hue` is deprecated and will be removed in v0.14.0.
Assign the `x` variable to `hue` and set `legend=False` for the same effect.

To color one bar differently, give palette= a dictionary: palette={"Parcelo": "#c8553d", "Dash": "#bbbbbb", "Swift": "#bbbbbb", "Bikebox": "#bbbbbb"}. For a single color on every bar, use color=. Custom color palettes covers building palettes.

Compare groups side by side with hue

When hue is a different column from x, Seaborn draws grouped bars, each with its own interval:

fig, ax = plt.subplots(figsize=(8, 4.5))
sns.barplot(data=orders, x="service", y="minutes", hue="day",
            palette=["#8fb3a6", "#3d6b5c"], errorbar="se", capsize=0.15, gap=0.1, ax=ax)
ax.set(xlabel="", ylabel="Average minutes (± 1 SE)")
sns.move_legend(ax, "upper left", title=None, frameon=False)
sns.despine()
plt.show()

Grouped Seaborn bar chart of average delivery time on weekdays and weekends: weekends are slower for Dash, Swift, and Bikebox by about 2.5 to 4.5 minutes, while Parcelo is about 42 minutes on both

gap=0.1 leaves a little space between the bars in a group. Grouped bar charts in Seaborn covers the ordering and spacing options.

Deprecated barplot parameters

Seaborn 0.12 and 0.13 renamed several arguments. Old tutorials still use them, and they now raise a FutureWarning:

Old Use instead
ci=95 errorbar=("ci", 95)
ci="sd" errorbar="sd"
ci=None errorbar=None
errwidth=1.5 err_kws={"linewidth": 1.5}
errcolor="black" err_kws={"color": "black"}
palette= without hue= hue= the same column as x, plus legend=False

sns.barplot vs countplot, histplot, catplot, and df.plot.bar

Use When
sns.barplot() Raw rows, and each bar is a mean (or other statistic) with an error bar
sns.countplot() Each bar is the number of rows in a category
sns.histplot() Bars are bins of a numeric column
sns.catplot(kind="bar") The same bars, split into panels with col= or row=
df.plot.bar() Data is already one row per bar, in wide format (pandas plotting)
ax.bar() Full control in Matplotlib (beautiful bar charts)

Similar Topics