从 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