[英]How to plot a dashed line on seaborn lineplot?
似乎lineplot()
linestyle=
參數不適用於lineplot()
,並且參數dashes=
比看起來要復雜一些。
一種(相對)簡單的方法可能是使用ax.lines
獲取繪圖上 Line2D 對象的列表,然后手動設置ax.lines
:
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
參數僅在繪制多條線時適用(通常使用熊貓數據框)。 破折號的指定與 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()
正如之前提到的,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)])
實際上,您以錯誤的方式使用lineplot
。 您的簡化案例比seaborn
任何內容都更適合matplotlib
的plot
函數。 seaborn
更在腳本使曲線更易讀用更少的直接干預,一般得到最多的里程與打交道時pandas
dataframes
例如
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()
產量
至於如何以您想要的方式為您嘗試顯示的變量設置樣式,我不確定如何處理。
雖然其他答案有效,但它們需要更多的手工。
您可以將您的 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')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.