如何在seaborn的折线图中绘制虚线?

33

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

在此输入图片描述

我做错了什么?谢谢


1
既然你已经导入了matplotlib.pyplot,为什么不直接使用plt.plot(x,y, '--')呢? - Sheldore
5个回答

48

似乎在使用lineplot()时,linestyle=参数不起作用,而参数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()

这里输入图片描述


1
请注意,您还需要定义style参数才能使其正常工作。请参见:https://dev59.com/1VMH5IYBdhLWcg3w8l6b - Archie

22

在当前版本的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的lineplot基于样式变量覆盖了线条样式,根据文档,该变量可以是“数据中的变量名称或向量数据”的名称。请注意直接将向量传递给样式参数的第二个选项。这允许使用以下简单技巧即使在仅绘制单条线时也绘制虚线,无论是直接提供数据还是作为数据帧:
如果我们提供一个常量样式向量,比如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)])

simple lineplot with dashes


4
您想要去掉图例中显示的“True”,该怎么做? - Ravaging Care
1
根据文档,您可以将另一个选项 legend=False 传递给 sns.lineplot。 - Ben JW
1
+1。像 Ravaging Care 一样,我也在寻找一种方法来从图例中删除“True”,而不是删除整个图例。 - indigochild

4
实际上,您错误地使用了lineplot。对于您简化的情况,matplotlibplot函数比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()

收益率

enter image description here

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


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

这将产生以下图表。

plot result

如果您想查看有关线条的其他选项,请使用以下行查看。
[k for k in plt.rcParams.keys() if k.startswith('lines')]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接