如何将图例移到seaborn散点图之外? [重复]

问题描述 投票:0回答:1
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
sns.set(style="darkgrid")

g = sns.scatterplot(x="Area", y="Rent/Sqft", hue="region", style="availability", data=df)

当我运行这个时,我得到下面的图。

我想将图例移到情节之外。我用谷歌搜索并尝试了以下

g.legend(loc='right', bbox_to_anchor=(1.25, 0.5), ncol=1)
plt.show()

但我没有得到任何输出。而且,我无法理解对象 plt 是如何连接到我的 sns 对象的

我正在使用 Jupyter Notebook、Python 3.6 和 Seaborn 0.9.0。

python matplotlib seaborn legend scatter-plot
1个回答
40
投票

请尝试以下操作:

g.legend(loc='center left', bbox_to_anchor=(1.25, 0.5), ncol=1)

如果需要,您可以将第一个数字更改为负数,将图例放在左侧。

如果您使用 Jupyter IDE,则需要将两行代码放在同一个单元格中并一起运行它们以获得输出。另外,不存在

sns
对象。 seaborn 中的大多数函数都会返回一个 matplotlib
Axes
对象,您可以在其中使用与
Axes
对象关联的所有方法,例如您在此处使用的方法(即
.legend()
)。

© www.soinside.com 2019 - 2024. All rights reserved.