簡體   English   中英

如何將圖例添加到 seaborn.scatterplot?

[英]How to add legend to seaborn.scatterplot?

我有一個多列的 dataframe。 我試圖在另外兩個因素的散點圖中添加一個關於性的圖例(無色調)。 我試圖將圖例參數傳遞給 sns.scatterplot() 並由 ax.legend(handles,labels) 手動設置。 但是,第一種方法未能顯示圖例,第二種方法引發 ValueError。
這是我當前的代碼

    bar=sns.barplot(x=df.loc[:,'Sex'],y=df.loc[:,'Salary'],ax=ax[0])
    bar.set(ylim=(10000,30000))
    sca=sns.scatterplot(data=df,x=df.loc[:,'yearsinrank'],y=df.loc[:,'Salary'],ax=ax[1])
    sca.legend(handles=df.loc[:,'Sex'],labels=['male','female'])
    sca.set(ylim=(10000,40000),xlim=(-5,30))
    plt.show()

這是樣品 output 在此處輸入圖像描述

太感謝了!

您可以通過添加一個hue參數來做到這一點。

fig, ax = plt.subplots(1, 2, figsize=(16, 5))

bar = sns.barplot(
    x=df.loc[:, 'Sex'],
    y=df.loc[:, 'Salary'],
    ax=ax[0]
)
bar.set(ylim=(10000, 30000))
sca = sns.scatterplot(
    data=df,
    x=df.loc[:, 'yearsinrank'],
    y=df.loc[:, 'Salary'],
    hue=df.loc[:, 'Sex'], # hue argument to specify grouping variable
    ax=ax[1]
)
sca.set(ylim=(10000, 40000), xlim=(-5, 30))
plt.show() 

在此處輸入圖像描述

散點圖返回軸 object。

因此,您可以使用第四種方式 label 一個軸 object : label 現有的情節(雖然不鼓勵)。 您可以使用:

sca.legend(['male','female')

或者

ax[1].legend(['male','female')

所以我通過使用hue屬性和legend setter方法解決了這個問題。 (似乎色調和圖例之間有某種關系?)這是我當前的代碼

f,ax = plt.subplots(nrows=1,ncols=2,sharex=False,sharey=False)
bar=sns.barplot(x=df.loc[:,'Sex'],y=df.loc[:,'Salary'],ax=ax[0])
bar.set(ylim=(10000,30000))
sca=sns.scatterplot(data=df,x=df.loc[:,'yearsinrank'],y=df.loc[:,'Salary'],ax=ax[1],hue=df.loc[:,'Sex'])
sca.legend(loc='lower right')
sca.set(ylim=(10000,40000),xlim=(-5,30))
plt.show()

這是最終的結果在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM