如何在seaborn lineplot上绘制虚线? [英] How to plot a dashed line on seaborn lineplot?

查看:39
本文介绍了如何在seaborn lineplot上绘制虚线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我做错了什么?谢谢

推荐答案

linestyle = 参数似乎不适用于 lineplot(),而参数dashes= 比看起来要复杂一些.

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

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

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

更新:

看来 dashes 参数仅适用于绘制多条线(通常使用 Pandas 数据框).破折号的指定与 matplotlib 中的相同,这是一个(段,间隙)长度的元组.因此,您需要传递一个元组列表.

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

这篇关于如何在seaborn lineplot上绘制虚线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆