Python 3.x 使用;“色调”;对于Seaborn visual:如何在一个图形中获得图例?

Python 3.x 使用;“色调”;对于Seaborn visual:如何在一个图形中获得图例?,python-3.x,pandas,matplotlib,seaborn,Python 3.x,Pandas,Matplotlib,Seaborn,我使用seaborn.relplot在seaborn中创建了一个散点图,但是我无法将图例全部放在一个图形中 当我这样做时,一切都很好: import pandas as pd import numpy as np from scipy import stats import matplotlib.pyplot as plt import seaborn as sns df2 = df[df.ln_amt_000s < 700] sns.relplot(x='ln_amt_000s', y

我使用seaborn.relplot在seaborn中创建了一个散点图,但是我无法将图例全部放在一个图形中

当我这样做时,一切都很好:

import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import seaborn as sns

df2 = df[df.ln_amt_000s < 700]
sns.relplot(x='ln_amt_000s', y='hud_med_fm_inc', hue='outcome', size='outcome', legend='brief', ax=ax, data=df2)
将熊猫作为pd导入
将numpy作为np导入
从scipy导入统计信息
将matplotlib.pyplot作为plt导入
导入seaborn作为sns
df2=df[df.ln\u金额\u 000s<700]
sns.relplot(x='ln\u amt\u 000s',y='hud\u med\u fm\u inc',hue='output',size='output',legend='brief',ax=ax,data=df2)
结果是所需的散点图,图例位于右侧

但是,当我尝试提前生成matplotlib地物和轴对象以指定地物尺寸时,遇到了以下问题:

a4_dims = (10, 10) # generating a matplotlib figure and axes objects ahead of time to specify figure dimensions
df2 = df[df.ln_amt_000s < 700]
fig, ax = plt.subplots(figsize = a4_dims)
sns.relplot(x='ln_amt_000s', y='hud_med_fm_inc', hue='outcome', size='outcome', legend='brief', ax=ax, data=df2)
a4_dims=(10,10)#提前生成matplotlib地物和轴对象以指定地物尺寸
df2=df[df.ln\u金额\u 000s<700]
图,ax=plt.子批次(图尺寸=a4尺寸)
sns.relplot(x='ln\u amt\u 000s',y='hud\u med\u fm\u inc',hue='output',size='output',legend='brief',ax=ax,data=df2)
结果是两个图形——一个具有预期的散点图,但缺少图例,另一个在其下方,除了右侧的图例外,其余均为空白。

我如何解决这个问题?我想要的结果是一个图形,在该图形中,我可以指定图形尺寸,并将图例放在x轴下方的两行底部(如果这太难或不受支持,那么同一图形右侧的默认图例位置也可以)?我知道问题出在“ax=ax”上,我将尺寸指定为matplotlib figure,但我想知道具体原因,以便从中学习


感谢您的时间。

问题在于
sns.relplot
是一个“图形级界面,用于在FacetGrid上绘制关系图”(请参阅)。使用简单的
sns.scatterplot
(sns.relplot使用的默认绘图类型),您的代码可以工作(更改为使用可复制数据):


对图例的进一步编辑 Seaborn的传奇有点挑剔。您可能希望采用的一些调整:

  • 通过获取并切片句柄和标签,删除默认的seaborn标题(实际上是图例条目)
  • 设置一个实际为标题的新标题
  • 移动位置并使用
    bbox\u to\u锚定
    移动到绘图区域之外(请注意,
    bbox
    参数需要根据绘图大小进行一些调整)
  • 指定列数
fig,ax=plt.子批次(figsize=(5,5))
散点图(x='萼片长度',y='萼片宽度',
色调='物种',图例='简短',
ax=ax,数据=df)
句柄,标签=ax.get\u legend\u handles\u labels()
ax.图例(句柄=句柄[1]、标签=标签[1]、loc=8、,
ncol=2,bbox_至_锚=[0.5,-.3,0,0])
plt.show()

谢谢你,布伦丹!你的解释很有见地——我从中学到了很多,不仅仅是为了解决我的一个问题。非常感谢。
df = pd.read_csv("https://vincentarelbundock.github.io/Rdatasets/csv/datasets/iris.csv", index_col=0)
fig, ax = plt.subplots(figsize = (5,5))
sns.scatterplot(x = 'Sepal.Length', y = 'Sepal.Width', 
            hue = 'Species', legend = 'brief',
            ax=ax, data = df)
plt.show()