Seaborn Barplot – Make Bar Charts with sns.barplot

In this tutorial, you’ll learn all you need to know about the Seaborn barplot. We’ll explore the sns.barplot() function and provide examples of how to customize your plot.

Check out the sections below If you’re interested in something specific. If you want to learn more about Seaborn, check out my other Seaborn tutorials, like the scatterplot tutorial.

What are bar plots?

A bar chart is a chart or graph that represents categorical data. It does this by using rectangular bars with both heights (or lengths) that are proportional to different values.

You would generally use a barplot when you you have at least one categorical variable and one numeric variable. In this case, barplots are used to display the differences (and similarities) between the categories.

By default, Seaborn will calculate the mean (the “average”) of a value, split into different categories. Later in this tutorial, you’ll learn how to also display the counts (the “frequencies”) of the categories.

What's in a barplot?

Seaborn countplot() versus barplot()

Seaborn has two different functions that it can use to create bar charts: sns.barplot() and sns.countplot(). They both produce bar charts, though the logic behind these charts are fundamentally different.

The sns.barplot() creates a bar plot where each bar represents a summary statistic for each category. By default, it generates the mean for each category. This means that the height of each bar represents the mean of that category.

The sns.countplot() on the other hand generates a bar for each category, where the height represents, well, the count (frequency) of each category.

Check out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!

Making a simple Seaborn barplot

Let’s create a simple barplot in Seaborn. To get this started, we can load one of the datasets that come bundled with Seaborn. To do this, we can use the sns.load_dataset() function. We’ll use the titanic dataset for this tutorial. Let’s see how we can do this with a simple bit of Python:

import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset('titanic')
print(df.head())

This returns the following:

   survived  pclass     sex   age  sibsp  parch     fare embarked  class    who  adult_male deck  embark_town alive  alone
0         0       3    male  22.0      1      0   7.2500        S  Third    man        True  NaN  Southampton    no  False
1         1       1  female  38.0      1      0  71.2833        C  First  woman       False    C    Cherbourg   yes  False
2         1       3  female  26.0      0      0   7.9250        S  Third  woman       False  NaN  Southampton   yes   True
3         1       1  female  35.0      1      0  53.1000        S  First  woman       False    C  Southampton   yes  False
4         0       3    male  35.0      0      0   8.0500        S  Third    man        True  NaN  Southampton    no   True

We need to import pyplot as well in order to customize our charts.

Now, to be able to create a simple barplot(), we can simply write:





This returns follow:





Adding Titles and Axis Labels to Seaborn Barplots

We use matplotlib to change the tile and axis labels. We can use the plt.title(), plt.xlabel(), and plt.ylabel() functions to change our titles.

Let’s give this a shot and add some descriptive labels:

sns.barplot(data=df, x="class", y="age")

plt.title('Age and Class of Titanic Passengers')
plt.xlabel('Class')
plt.ylabel('Mean Age')

plt.show()

This returns the following image:

Adding a title to a Seaborn bar chart

Seaborn also has a very handy function to make your plots prettier by removing the right and top borders of the axes. We can use the sns.despine() function to accomplish this:

df = sns.load_dataset('titanic')

sns.barplot(data=df, x="class", y="age")
plt.title('Age and Class of Titanic Passengers')
plt.xlabel('Class')
plt.ylabel('Mean Age')

sns.despine()

plt.show()

This returns the following image:

Removing spines Seaborn

Adjust Seaborn barplot Confidence Internal

You might find yourself wondering what the bars in the barplots represent. By default, they show the confidence interval of the mean. Seaborn uses a bootstrapping technique to calculate (by default, a 95%) confidence interval that this mean will be replicated with different samples. By this logic, a confidence interval of 95% indicates that Seaborn estimates that 95% of the time, similar means will fall within the range of the bar.

You can adjust this confidence interval by using the ci= parameter. For example, if we wanted to use 90% instead, we could write:

df = sns.load_dataset('titanic')

sns.barplot(data=df, x="class", y="age", ci=0.9)
plt.title('Age and Class of Titanic Passengers')
plt.xlabel('Class')
plt.ylabel('Mean Age')

sns.despine()

plt.show()

This returns the following image:

Changing error bars Seaborn

Alternatively, you can show the standard deviation of the data by using ci='sd' argument:

df = sns.load_dataset('titanic')

sns.barplot(data=df, x="class", y="age", ci='sd')
plt.title('Age and Class of Titanic Passengers')
plt.xlabel('Class')
plt.ylabel('Mean Age')

sns.despine()

plt.show()

This returns the following image.

Seaborn show standard deviation

If you don’t want to see the confidence interval at all (which can tremendously speed up your plotting, as Seaborn doesn’t need to calculate anything extra), you can pass in ci=None :

df = sns.load_dataset('titanic')

sns.barplot(data=df, x="class", y="age", ci=None)
plt.title('Age and Class of Titanic Passengers')
plt.xlabel('Class')
plt.ylabel('Mean Age')

sns.despine()

plt.show()

This returns the following image:

Style Seaborn Barplots

One of the perks of Seaborn is that it’s much easier to make your plots look prettier than Matplotlib allows.

In this tutorial, we use two functions: sns.set_style() and sns.set_palette() to style our plot.

You can find the available styles on the official Seaborn website here and see what the available palettes are here.

Let’s apply the darkgrid style and the Set2 palette:

df = sns.load_dataset('titanic')

sns.set_style('darkgrid')
sns.set_palette('Set2')

sns.barplot(data=df, x="class", y="age", ci=None)

plt.title('Age and Class of Titanic Passengers')
plt.xlabel('Class')
plt.ylabel('Mean Age')

sns.despine()

plt.show()

This returns the following image:

Seaborn add style barchart

Countplot – Showing counts in Seaborn barplots

A fairly conventional use of the barplot is to show how often an item occurs in a given category. For this, we can use the sns.countplot() .

For example, based on the dataset we loaded above, we may want to graph our the count of people per class on the Titanic. This is a perfect use case for the sns.countsplot() function.

Let’s give this a try:

df = sns.load_dataset('titanic')

sns.set_style('darkgrid')
sns.set_palette('Set2')

sns.countplot(data=df, x="class")

plt.title('Number of passengers, by class')
plt.xlabel('Class')
plt.ylabel('# of Passengers')

sns.despine()

plt.show()

This returns the following image:

Seaborn count plot

Here, we’ve been able to create a countplot() using Seaborn.

Create a Grouped Seaborn Barplot

Another thing that Seaborn makes easy that Matplotlib makes difficult is the creation of grouped bar charts. We can accomplish this with both the sns.barplot() and the sns.countplot() functions.

Let’s try this first with the barplot we had created above with age, but split by gender and class:

df = sns.load_dataset('titanic')

sns.set_style('darkgrid')
sns.set_palette('Set2')

sns.barplot(data=df, x="class", y='age', hue='sex')

plt.title('Age and Class of Titanic Passengers')
plt.xlabel('Class')
plt.ylabel('Mean Age')

sns.despine()

plt.show()

This returns the following chart:

Seaborn grouped barplot

Now we can accomplish a similar chart using the sns.countplot() function. Let’s split our earlier chart by gender as well:

df = sns.load_dataset('titanic')

sns.set_style('darkgrid')
sns.set_palette('Set2')

sns.countplot(data=df, x="class", hue='sex')

plt.title('Number of passengers, by class')
plt.xlabel('Class')
plt.ylabel('# of Passengers')

sns.despine()

plt.show()

This returns the following image:

Seaborn grouped countplot

Create a Horizontal Seaborn Barplot

Creating a horizontal bar chart in Seaborn is also very easy. In fact, it uses the same sns.barplot() function, and simply replaces the x and y parameters with categorical and numerical values.

What this means, is that when earlier we passed in x='class' and y='age', now we switch these parameters around:

df = sns.load_dataset('titanic')

sns.set_style('darkgrid')
sns.set_palette('Set2')

sns.barplot(data=df, x="age", y='class', hue='sex')

plt.title('Age and Class of Titanic Passengers')
plt.xlabel('Mean Age')
plt.ylabel('Class')

sns.despine()

plt.show()

This returns the following plot:

Seaborn horizontal barchart

Conclusion

In this post, you learned all about how to create barplots in Seaborn. In particular, you learned how to created statistical estimation barplots as well as categorical countplots. You also learned how to customize your barplots by removing and altering confidence interval markers, as well as customizing plots with titles, legends, colours.