首页 > 解决方案 > 如何将图例移到 seaborn 散点图之外?

问题描述

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。

标签: pythonmatplotlibseabornscatter-plot

解决方案


请尝试以下方法:

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

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

如果您使用的是 Jupyter IDE,则需要将两行代码放在同一个单元格中并一起运行以获得输出。此外,没有sns对象这样的东西。seaborn中的大多数函数都返回一个 matplotlibAxes对象,您可以在其中使用与该对象关联的所有方法Axes,例如您在此处使用的方法(即.legend())。


推荐阅读