How to plot a dashed line on seaborn lineplot?
Asked Answered
N

6

34

I'm simply trying to plot a dashed line using seaborn. This is the code I'm using and the output I'm getting

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)

sns.lineplot(x,y, linestyle='--')
plt.show()

enter image description here

What am I doing wrong? Thanks

Neuberger answered 22/8, 2018 at 9:27 Comment(1)
Why don't you just do plt.plot(x,y, '--') since you are anyway import matplotlib.pyplotGisser
J
48

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[0].set_linestyle("--")

plt.show()

enter image description here

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()

enter image description here

Johnsten answered 22/8, 2018 at 9:49 Comment(1)
Note that you also need to define the style parameter to let it work. See: #57485926Phenazine
C
25

In the current version of seaborn 0.11.1, your code works perfectly fine.

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)

sns.lineplot(x=x,y=y, linestyle='--')
plt.show();

enter image description here

Corey answered 12/3, 2021 at 22:44 Comment(0)
A
8

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)])

simple lineplot with dashes

Acicular answered 18/8, 2020 at 11:41 Comment(3)
How would you now remove "True" that shows up in legend?Leiker
According to the docs, you could just pass another option legend=False to sns.lineplot.Acicular
+1. Like Ravaging Care, I'm also looking for a way to remove 'True' from the legend, without removing the entire legend.Auroora
C
4

You are in fact using lineplot the wrong way. Your simplified case is more appropriate for matplotlib's plot function than anything from seaborn. seaborn is more for making the plots more readable with less direct intervention in the script, and generally gets the most mileage when dealing with pandas dataframes

For example

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

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

df = pd.DataFrame(np.c_[y1, y2, y3], index=x)

ax = sns.lineplot(data=df)
plt.show()

yields

enter image description here

As to how to set the styles the way you want for the variables you're trying to show, that I'm not sure how to handle.

Caius answered 22/8, 2018 at 10:7 Comment(0)
V
1

While the other answers work, they require a little bit more handiwork.


You can wrap your seaborn plot in an rc_context.

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)

with plt.rc_context({'lines.linestyle': '--'}):
    sns.lineplot(x, y)
plt.show()

This results in the following plot.

plot result

If you would like to see other options regarding lines, have a look using the following line.

[k for k in plt.rcParams.keys() if k.startswith('lines')]
Vietnam answered 27/10, 2021 at 23:56 Comment(0)
H
0
sns.lineplot(df_input, x='value x', y='value y', linestyle='dashed')
Howdy answered 26/3 at 11:52 Comment(1)
Welcome to Stack Overflow! With 5 other answers here (all much better explained), what makes yours a "good answer" and worth upvoting (or even trying)? You can find more information in How do I write a good answer? - "Brevity is acceptable, but fuller explanations are better." It might be helpful to review some highly upvoted answers as examples to follow. Thanks!Bixler

© 2022 - 2024 — McMap. All rights reserved.