Adding a horizontal line in a Seaborn plot in Python
This tutorial will teach you how to add a horizontal line to any plot created using Seaborn in Python.
For this purpose, we will be using the seaborn and matplotlib libraries. Seaborn is a data visualization library, while matplotlib is a library used to plot graphs in Python.
If you already have seaborn and matplotlib installed in your system, you may skip this step. Otherwise, you should follow the steps in the following link:
Importing the requires libraries
We import the seaborn and matplotlib libraries using the following piece of code:
import seaborn as sns import matplotlib.pyplot as plt
pyplot is a module in matplotlib that allows us to plot graphs in a simple manner (similar to MATLAB).
We use the ‘as’ keyword to create aliases for both libraries. This helps in calling functions from the libraries and makes the code look cleaner and more readable.
You may use any dataset. You can even input the data from the keyboard. However, I will be using the ‘iris’ dataset for the sake of this example.
To use this library, make sure you are connected to the internet. Seaborn will automatically download the dataset while running the code. This implies that you do not need to have the dataset saved locally on your computer.
The ‘iris’ dataset contains information on the iris flower. Beginners commonly use this dataset for testing purposes.
Python program to add a horizontal line in a Seaborn plot
A barplot will be used in this tutorial and we will put a horizontal line on this bar plot using the axhline() function.
#Importing the necessary libraries import seaborn as sns import matplotlib.pyplot as plt #Loading the dataset into the variable 'dataset' dataset = sns.load_dataset("iris") dataset.head() #Graph is created and stored in the variable 'graph' graph = sns.barplot(x="sepal_width",y="petal_width",data=dataset) #Drawing a horizontal line at point 1.25 graph.axhline(1.25) #The plot is shown plt.show()
First, we import the seaborn and matplotlib.pyplot libraries using aliases ‘sns’ and ‘plt’ respectively.
Next, we use the sns.load_dataset() function to load the ‘iris’ dataset into the variable, ‘dataset’. The dataset.head() function takes only the first 5 rows of data from the dataset.
The sns.barplot() function creates a bar plot between the columns ‘sepal_width’ and ‘petal_width’ and stores it in the variable, ‘graph’.
Next, the graph.axhline() function creates a horizontal line in the bar plot. For this tutorial example, I have taken the horizontal line to be at the point 1.25 on the y-axis.
Finally, the plt.show() function shows the plot.
Now if we run our program, we will able to get the plot that you can see below:
We can clearly see a horizontal line plot.
In conclusion, I advise you to explore more about the Seaborn library and plotting graphs in Python. For this purpose, I recommend the following links: