How to plot a dashed line on seaborn lineplot?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to plot a dashed line on seaborn lineplot in Python. So Here I am Explain to you all the possible Methods here.

How to plot a dashed line on seaborn lineplot?

1. How to plot a dashed line on seaborn lineplot?

It seems that linestyle= argument doesn't work with lineplot(), and the argument dashes= is a bit more complicated than it might seem.

2. plot a dashed line on seaborn lineplot

It seems that linestyle= argument doesn't work with lineplot(), and the argument dashes= is a bit more complicated than it might seem.

Method 1

It seems that linestyle= argument doesn’t work with lineplot(), and the argument dashes= is a bit more complicated than it might seem.

A (relatively) simple way of doing it might be to get a list of the Line2D objects on the plot using ax.lines and then set the linestyle manually:

import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

n = 11
x = np.linspace(0,2,n)
y = np.sin(2*np.pi*x)

ax = sns.lineplot(x,y)

# Might need to loop through the list if there are multiple lines on the plot
ax.lines.set_linestyle("--")

plt.show()

Update:

It appears the dashes argument applies only when plotting multiple lines (usually using a pandas dataframe). Dashes are specified the same as in matplotlib, a tuple of (segment, gap) lengths. Therefore, you need to pass a list of tuples.

n = 100
x = np.linspace(0,4,n)
y1 = np.sin(2*np.pi*x)
y2 = np.cos(2*np.pi*x)

df = pd.DataFrame(np.c_[y1, y2]) # modified @Elliots dataframe production

ax = sns.lineplot(data=df, dashes=[(2, 2), (2, 2)])
plt.show()

Method 2

As has been mentioned before, seaborn’s lineplot overrides the linestyle based on the style variable, which according to the docs can be a “name of variables in data or vector data“. Note the second option of directly passing a vector to the style argument. This allows the following simple trick to draw dashed lines even when plotting only single lines, either when providing the data directly or as dataframe:

If we provide a constant style vector, say style=True, it will be broadcast to all data. Now we just need to set dashes to the desired dash tuple (sadly, ‘simple’ dash specifiers such as ‘–‘, ‘:’, or ‘dotted’ are not supported), e.g. dashes=[(2,2)]:

import seaborn as sns
import numpy as np
x = np.linspace(0, np.pi, 111)
y = np.sin(x)
sns.lineplot(x, y, style=True, dashes=[(2,2)])

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.