如何在seaborn lineplot上绘制虚线?

cra*_*ash 7 python matplotlib seaborn

我只是想用seaborn绘制一条虚线.这是我正在使用的代码和我得到的输出

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我究竟做错了什么?谢谢

Jim*_*Jim 23

在当前版本的seaborn 0.11.1中,您的代码工作得很好。

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();
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Dav*_*idG 8

看起来这个linestyle=论点不起作用lineplot(),而且这个论点dashes=比它看起来要复杂得多.

一个(相对)简单的方法可能是使用绘图上的Line2D对象列表,ax.lines然后手动设置linestyle:

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

更新:

看来该dashes参数仅在绘制多条线时适用(通常使用pandas数据帧).破折号的指定与matplotlib相同,后者是(段,间隙)长度的元组.因此,您需要传递元组列表.

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Ben*_* JW 7

正如之前提到的,seaborn 的 lineplot 会覆盖基于style变量的线型,根据文档,它可以是“数据或矢量数据中的变量名称”。请注意将向量直接传递给style参数的第二个选项。这允许使用以下简单的技巧来绘制虚线,即使只绘制单条线,无论是直接提供数据还是作为数据框:

如果我们提供一个常量样式向量,比如style=True,它将被广播到所有数据。现在我们只需要设置dashes所需的破折号元组(遗憾的是,不支持“简单”破折号说明符,例如 '--'、':' 或 'dotted'),例如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)])
Run Code Online (Sandbox Code Playgroud)

带破折号的简单线图

  • 您现在如何删除传说中出现的“True”? (3认同)