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)

seaborn add horizontal line to scatter plot

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)

seaborn add vertical line to scatter plot

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:

How to Add a Title to Seaborn Plots
How to Change Font Size in Seaborn Plots
How to Adjust Number of Ticks in Seaborn Plots

Leave a Reply

Your email address will not be published. Required fields are marked *