- How to Add Line to Scatter Plot in Seaborn
- Example 1: Add Horizontal Line to Seaborn Scatter Plot
- Example 2: Add Vertical Line to Seaborn Scatter Plot
- Example 3 : Add Custom Line to Seaborn Scatter Plot
- Additional Resources
- Lines and segments in seaborn
- Horizontal lines with axhline and hlines functions
- Lines customization
- Add vertical line to seaborn plot in Python
- Import required libraries
- Dataset
- Lets Code
- How to Add Vertical/Horizontal Lines to Subplots with Seaborn
- Small multiples with Seaborn’s displot()
- Seaborn’s refline() function to add horizontal/vertical lines in subplots
How to Add Line to Scatter Plot in Seaborn
You can use the following methods to add a line to a scatter plot in seaborn:
Method 1: Add Horizontal Line
#add horizontal line at y=15 plt.axhline(y=15)
Method 2: Add Vertical Line
#add vertical line at x=4 plt.axvline(x=4)
Method 3: Add Custom Line
#add straight line that extends from (x,y) coordinates (2,0) to (6, 25) plt.plot([2, 6], [0, 25])
The following examples show how to use each method in practice.
Example 1: Add Horizontal Line to Seaborn Scatter Plot
The following code shows how to create a scatter plot in seaborn and add a horizontal line at y = 15:
import seaborn as sns import matplotlib.pyplot as plt #create DataFrame df = pd.DataFrame(x': [1, 2, 3, 4, 5, 6, 7, 8], 'y': [18, 22, 19, 14, 14, 11, 20, 28]>) #create scatterplot sns.scatterplot(x=df.x, y=df.y) #add horizontal line to scatterplot plt.axhline(y=15)
Example 2: Add Vertical Line to Seaborn Scatter Plot
The following code shows how to create a scatter plot in seaborn and add a vertical line at x = 4:
import seaborn as sns import matplotlib.pyplot as plt #create DataFrame df = pd.DataFrame(x': [1, 2, 3, 4, 5, 6, 7, 8], 'y': [18, 22, 19, 14, 14, 11, 20, 28]>) #create scatterplot sns.scatterplot(x=df.x, y=df.y) #add vertical line to scatterplot plt.axvline(x=4)
Example 3 : Add Custom Line to Seaborn Scatter Plot
The following code shows how to create a scatter plot in seaborn and add a straight line that extends from (x,y) coordinates (2,0) to (6, 25)
import seaborn as sns import matplotlib.pyplot as plt #create DataFrame df = pd.DataFrame(x': [1, 2, 3, 4, 5, 6, 7, 8], 'y': [18, 22, 19, 14, 14, 11, 20, 28]>) #create scatterplot sns.scatterplot(x=df.x, y=df.y) #add custom line to scatterplot plt.plot([2, 6], [0, 25])
Note: You can find the complete documentation to the seaborn scatter() function here.
Additional Resources
The following tutorials explain how to perform other common tasks using seaborn:
Lines and segments in seaborn
If you want to add a vertical line to a plot made with seaborn you can use the axvline function and set where you want to display the vertical line with the x argument. The arguments ymin and ymax range from 0 to 1 and represent the starting point and the end point of the line.
import numpy as np import seaborn as sns # Data simulation x = np.random.RandomState(1).normal(0, 1, size = 50) ax = sns.kdeplot(x = x, fill = True, color = "limegreen", alpha = 0.1) ax.axvline(x = 2, # Line on x = 2 ymin = 0, # Bottom of the plot ymax = 1) # Top of the plot
If you set other values to the ymin and ymax arguments you can create a segment. Recall that those values don’t represent the values of the Y-axis.
import numpy as np import seaborn as sns # Data simulation x = np.random.RandomState(1).normal(0, 1, size = 50) ax = sns.kdeplot(x = x, fill = True, color = "limegreen", alpha = 0.1) ax.axvline(x = 2, # Line on x = 2 ymin = 0.2, # Bottom of the plot ymax = 0.8) # Top of the plot
In case you want to add several lines at once you can use the vlines function. The main advantage of this function is that you can set the minimum and maximum values according to the values to the Y-axis. Note that you can also create a single line with this function.
import numpy as np import seaborn as sns # Data simulation x = np.random.RandomState(1).normal(0, 1, size = 50) ax = sns.kdeplot(x = x, fill = True, color = "limegreen", alpha = 0.1) ax.vlines(x = [-2, 0, 2], # Line on x = [-2, 0, 2] ymin = 0, # Starting point for all lines ymax = [0.05, 0.4, 0.05]) # End point for each line
Horizontal lines with axhline and hlines functions
Similarly, the axhline function allows adding horizontal lines to the seaborn plots, but now you need to set the value with the y argument and the minimum and maximum values from 0 to 1 with the xmin and xmax arguments.
import numpy as np import seaborn as sns # Data simulation x = np.random.RandomState(1).normal(0, 1, size = 50) ax = sns.kdeplot(x = x, fill = True, color = "limegreen", alpha = 0.1) ax.axhline(y = 0.2, # Line on y = 0.2 xmin = 0.1, # From the left xmax = 0.9) # To the right
In case you want to add several horizontal lines at once or if you prefer specifying the minimum and maximun values of the line based on the values of the X-axis you can use the hlines function, as shown below.
import numpy as np import seaborn as sns # Data simulation x = np.random.RandomState(1).normal(0, 1, size = 50) ax = sns.kdeplot(x = x, fill = True, color = "limegreen", alpha = 0.1) ax.hlines(y = [0.1, 0.2, 0.3], # Y-axis values xmin = -2, # From x = -2 xmax = 2) # To x = 2
The main difference between the axvline , axhline and vlines , hlines functions is that the first pair of functions can only be used to add lines one by one and the specified minimum and maximum values must be between 0 and 1, while using the second pair functions you can add several lines at the same time and specify the exact points where you want to draw them.
Lines customization
The lines can be customized in several ways. Depending on the type of function you are using the names or the arguments are slightly different, as the style and color of the lines made with vlines and hlines can be customized with linestyles and colors , respectively, while the axhline and axvline functions provide the linestyle and color arguments.
import numpy as np import seaborn as sns # Data simulation x = np.random.RandomState(1).normal(0, 1, size = 50) ax = sns.kdeplot(x = x, fill = True, color = "limegreen", alpha = 0.1) ax.vlines(x = [-2, 2], ymin = 0, ymax = 0.4, linestyles = ["dashed", "solid"], colors = ["red", "blue"]) ax.axhline(y = 0.2, xmin = 0, xmax = 1, color = "black", linestyle = "dashed")
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.
We can see vertical lines plotted at x-axis values of 10 and 50.
How to Add Vertical/Horizontal Lines to Subplots with Seaborn
In this tutorial, we will learn how to add vertical or horizontal lines to “small multiples” i.e. multiple subplots of similar kind using Seaborn’s refline() function (h/t to Chris Moffitt of @pbpython). Vertical/Horizontal lines are often useful to show where the mean or median values of the variables of interest and in a simple plot we can use axvline/axhline to add the lines.
Let us get started with loading the packages needed.
import seaborn as sns import matplotlib.pyplot as plt
We will use Palmer penguin dataset available from Seaborn’s built-in datasets.
penguins = sns.load_dataset("penguins")
Small multiples with Seaborn’s displot()
We can make a small multiple or facetted plot, in this example multiple histograms, using Seaborn’s displot() function with “col” argument. In this example, we are plotting the distributions of flipper lengths of different penguin species.
plt.figure(figsize=(12,6)) g = sns.displot(data = penguins, x = "flipper_length_mm", col = "species") plt.savefig("Seaborn_small_multiples_With_displot.png", format='png',dpi=150)
Seaborn’s refline() function to add horizontal/vertical lines in subplots
To add a horizontal and vertical line we can use Seaborn’s refline() function with x and y y co-ordinates for the locations of the horizontal and vertical lines.
plt.figure(figsize=(12,6)) g.refline(x = penguins.flipper_length_mm.mean(), y = 20, color = "red", lw = 3) plt.savefig("Seaborn_small_multiples_refline_example.png", format='png',dpi=150)
Here we have the small multiples with horizontal and vertical lines at the specified locations in “red” color”.
To add horizintal/vertical lines in different colors or different shapes, we can use two reflline() statements, one for horizontal and one for vertical lines as shown below.
g.refline(x=penguins.flipper_length_mm.mean(), color = "red", lw = 3) g.refline(y = 20, color = "blue", lw = 3) plt.savefig("Seaborn_small_multiples_refline_add_vertical_horizontal_lines.png", format='png',dpi=150)
An additional plot of the similar flavor is to add the group specific horizontal or vertical lines instead of common ones. I may be wrong about it, but it does not look like Seaborn’s refline() can do that readily yet.