Add vertical line to seaborn plot in Python

Hello Programmers! In this tutorial we will learn to add a vertical line to any plot created using Seaborn in Python.

We will be using seaborn and matplotlib Python libraries. Seaborn is a data visualization library, while matplotlib is a library used to plot graphs in Python.

To install matplotlib and seaborn library on your local machine, open command prompt/terminal and write:

pip install matplotlib

pip install seaborn

Import required libraries

# Importing seaborn
import seaborn as sns
# Importing matplotlib
import matplotlib.pyplot as plt

Dataset

Dataset contains data that can be used by seaborn to generate a visual presentation/graph in form of a histogram, bar graph, pie chart, etc. In this tutorial, I will be using ‘titanic’ dataset. Seaborn automatically downloads the dataset from the internet, we don’t have to download it on our local machine.

We will be plotting the age of all members from the titanic dataset, in form of a histogram.

Lets Code

# Importing seaborn
import seaborn as sns
# Importing matplotlib
import matplotlib.pyplot as plt 
 
# Load dataset
titanic = sns.load_dataset("titanic")
 
# Plot histogram
graph= sns.histplot(data = titanic, x = "age")

#  Draw vertical line with values
graph.axvline(50)
graph.axvline(10)

# Plot the graph
plt.show()

After importing matplotlib and seaborn, we will be loading our dataset. sns.load_dataset(“titanic”) function is used to load the dataset.

To plot the graph in form of histogram we will use sns.histplot(data = titanic, x = “age”) which will take up dataset and column as parameters and store them in a variable named as “graph”.

In order to plot vertical lines on the histogram, we will use graph.axvline() function. This function will take up axis points to be plotted on x-axis. In this example, I have used 10 and 50 as axis points.

Finally, plt.show() is used to plot the graph.

Output:

We can see vertical lines plotted at x-axis values of 10 and 50.

Leave a Reply

Your email address will not be published.