如何在seaborn lineplot上绘制虚线?

问题描述 投票:0回答:6

我只是想用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()

我做错了什么?谢谢

python matplotlib seaborn
6个回答
48
投票

似乎

linestyle=
论证不适用于
lineplot()
,并且
dashes=
论证比看起来要复杂一些。

(相对)简单的方法可能是使用

ax.lines
获取绘图上的 Line2D 对象列表,然后手动设置线条样式:

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

更新:

看来

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


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


8
投票

正如之前提到的,seaborn 的线图覆盖了基于

style
变量的线型,根据文档,该变量可以是“数据中变量的名称或矢量数据”。 请注意直接将向量传递给
style
参数的第二个选项。 这允许以下简单的技巧即使在仅绘制单线时也可以绘制虚线,无论是直接提供数据还是作为数据框:

如果我们提供一个恒定样式向量,例如

style=True
,它将被广播到所有数据。现在我们只需要将
dashes
设置为所需的 dash tuple (遗憾的是,不支持“简单”破折号说明符,例如“--”、“:”或“点”),例如
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)])


4
投票

您实际上使用了

lineplot
的方式是错误的。您的简化案例比
matplotlib
中的任何内容更适合
plot
seaborn
函数。
seaborn
更多的是为了使绘图更具可读性,减少对脚本的直接干预,并且通常在处理
pandas
数据帧

时获得最大的收益

例如

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

产量

至于如何按照您想要的方式设置要显示的变量的样式,我不确定如何处理。


1
投票

虽然其他答案有效,但它们需要更多的手工工作。


您可以将您的seaborn情节包装在

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

这会产生以下情节。

如果您想查看有关线条的其他选项,请使用以下线条查看。

[k for k in plt.rcParams.keys() if k.startswith('lines')]

0
投票
sns.lineplot(df_input, x='value x', y='value y', linestyle='dashed')
© www.soinside.com 2019 - 2024. All rights reserved.