How to Create Seaborn Horizontal Bar Plot

Ammar Ali Feb 02, 2024
How to Create Seaborn Horizontal Bar Plot

This tutorial will discuss creating a horizontal bar graph using Seaborn’s barplot() function in Python.

Horizontal Bar Graph Using Seaborn

A bar graph shows the data as rectangular bars whose height is equal to the value of it represents. We can use Seaborn’s barplot() function to create a horizontal bar plot.

A bar graph contains two axes. One axis represents the data as rectangular bars, and the other axis represents the labels. We can convert a vertical bar graph to a horizontal bar graph by interchanging the axes.

We have to pass the data as well as the labels inside the barplot() function to create the bar graph. For example, let’s create a horizontal bar graph of random data. See the code below.

import seaborn as snNew
import matplotlib.pyplot as pltNew

labels = ["One", "Two", "Three"]
value = [10, 50, 100]
snNew.barplot(x=value, y=labels)
pltNew.show()

Output:

seaborn horizontal bar graph

By default, the barplot() function will give each bar a different color, but we can change the color of all the bars using the color argument and setting its value to the name of the color or the first letter of the color name.

We can also use the palette argument to change the default color palette used to color each bar like a bright color palette for bright colors and a dark color palette for dark colors. The color won’t change if we set the palette argument after the color argument.

We can also set the color saturation to any floating-point number using the saturation property.

We can give different colors to the face and edges of each bar using the facecolor and edgecolor parameters.

We can change the line with the edge color line using the linewidth parameter.

For example, let’s change the parameters mentioned above. See the code below.

import seaborn as snNew
import matplotlib.pyplot as pltNew

labels = ["One", "Two", "Three"]
value = [10, 50, 100]
snNew.barplot(
    x=value,
    y=labels,
    color="r",
    palette="bright",
    saturation=0.9,
    edgecolor="r",
    linewidth=5,
)
pltNew.show()

Output:

changing parameters of bar graph

If we flip the axis values, the graph will become vertical. For example, to make the above graph vertical, we can flip the values of the first two parameters x and y, like x=labels and y=value.

Author: Ammar Ali
Ammar Ali avatar Ammar Ali avatar

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.

LinkedIn Facebook

Related Article - Seaborn Plot