從 Python 中的 Seaborn 圖中刪除圖例
Manav Narula
2023年1月30日
2021年7月16日
-
使用
legend
引數從 Python 中的 Seaborn 圖中刪除圖例 -
使用
legend()
函式從 Python 中的 Seaborn 圖中刪除圖例 -
使用
remove()
函式從 Python 中的 Seaborn 圖中刪除圖例
![從 Python 中的 Seaborn 圖中刪除圖例](/img/Seaborn/feature%20image%20-%20remove%20legend%20seaborn%20plot.png)
在本教程中,我們將學習如何從 Python 中的 seaborn 圖中刪除圖例。
使用 legend
引數從 Python 中的 Seaborn 圖中刪除圖例
seaborn 中的大多數繪圖函式都接受 legend
引數。我們可以將其設定為 False 並在最終圖中隱藏圖例。
例如,
import random
import seaborn as sns
import matplotlib.pyplot as plt
s_x = random.sample(range(0,100),20)
s_y = random.sample(range(0,100),20)
cat = [i for i in range(2)]*10
sns.scatterplot(y = s_y, x = s_x, hue = cat, legend = False)
使用 legend()
函式從 Python 中的 Seaborn 圖中刪除圖例
matplotlib.pyplot.legend()
函式可用於向 seaborn 圖中新增自定義圖例。我們可以使用這個函式,因為 seaborn 模組建立在 matplotlib 模組之上。我們可以向圖中新增一個空圖例並刪除其框架。這樣,我們就對最終圖形隱藏了圖例。
以下程式碼片段實現了這一點。
import random
import seaborn as sns
import matplotlib.pyplot as plt
s_x = random.sample(range(0,100),20)
s_y = random.sample(range(0,100),20)
cat = [i for i in range(2)]*10
sns.scatterplot(y = s_y, x = s_x, hue = cat)
plt.legend([],[], frameon=False)
如果我們正在處理包含子圖的圖形並希望從每個子圖中刪除圖例,我們可以遍歷軸物件並使用上述函式將空圖例新增到每個軸。
使用 remove()
函式從 Python 中的 Seaborn 圖中刪除圖例
此方法適用於屬於不同類的物件,例如來自 seaborn 模組的 PairGrid 類。我們可以使用 _legend()
函式呼叫圖例並使用 remove()
方法將其刪除。
請參考下面的程式碼。
import random
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
s_x = random.sample(range(0,100),20)
s_y = random.sample(range(0,100),20)
cat = [i for i in range(2)]*10
df = pd.DataFrame({'s_x':s_x,'s_y':s_y,'cat':cat})
g = sns.pairplot(data = df,x_vars='s_x', y_vars='s_y', hue = 'cat')
g._legend.remove()
pairplot()
函式返回 PairGrid 類的物件。此方法也適用於 seaborn 模組的 FacetGrid
物件。
Author: Manav Narula
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
LinkedIn