[英]Seaborn Hue and Size Legend
I'm trying to change the Bins in the legend of a plot created with Seaborn.我正在尝试更改使用 Seaborn 创建的 plot 的图例中的垃圾箱。 The data is from 0 to 100, however Seaborn bins from 1 to 120 and 0 to 80. I've tried using hue_norm
and size_norm
but to no avail.数据是从 0 到 100,但是 Seaborn 从 1 到 120 和 0 到 80 分箱。我尝试使用hue_norm
和size_norm
但无济于事。
Please see code below and picture attached:请看下面的代码和附图:
import matplotlib.pyplot as plt
import seaborn as sns
from import_portfolio import df, portfolio
import numpy as np
from adjustText import adjust_text
df_factor = df[df.columns[df.columns.str.contains('Factor Percentile')]]
columns = []
for column in df_factor.columns:
split = str.split(column, sep=' ')
fac = split[split.index('Factor') - 1]
columns.append(fac)
df_factor.columns = columns
df_factor['Symbol'] = df['Symbol'].copy()
df_factor = df_factor.replace(' ', np.NaN)
plt.figure(figsize=(13,7))
ax = sns.scatterplot(data=df_factor.dropna(), x='Valuation', y='Quality', hue='Momentum', size='Growth', palette='RdYlGn', sizes=(20,150))
plt.xlim(0,100)
plt.ylim(0,100)
adjust_text(texts, arrowprops=dict(arrowstyle='-', color='k', lw=0.5))
plt.legend(bbox_to_anchor=(1.05,1), loc=2, borderaxespad=0.)
Anyone any idea how to resolve this issue?有人知道如何解决这个问题吗?
Thank you谢谢
You can alter the legend, but since you are working with a data.frame and seaborn, one option is to make your hue
and size
categorial to start, with provide the matching label or colors to sns.scatterplot
您可以更改图例,但由于您使用的是 data.frame 和 seaborn,因此一种选择是让您的hue
和size
分类开始,并提供匹配的 label 或sns.scatterplot
For example:例如:
import matplotlib.pyplot as plt import seaborn as sns import numpy as np导入 matplotlib.pyplot 作为 plt 导入 seaborn 作为 sns 导入 numpy 作为 np
np.random.seed(999) df_factor = pd.DataFrame(np.random.uniform(0,100,(20,4)),columns=['Valuation','Quality','Growth','Momentum']) np.random.seed(999) df_factor = pd.DataFrame(np.random.uniform(0,100,(20,4)),columns=['估值','质量','增长','动量'])
Here we introduce another column that discretizes the two columns.在这里,我们介绍另一个将两列离散化的列。 You can also overwrite it or use a function.您也可以覆盖它或使用 function。 Below I use pd.cut to assign values between 0 to 20 (including 20) to have a label 20, 21-40 to have a label40 and so on:下面我使用 pd.cut 分配 0 到 20(包括 20)之间的值来获得 label 20、21-40 来获得 label40 等等:
df_factor['Growth_lvl'] = pd.cut(df_factor['Growth'],[0,20,40,60,80,100],labels=[20,40,60,80,100])
df_factor['Momentum_lvl'] = pd.cut(df_factor['Momentum'],[0,20,40,60,80,100],labels=[20,40,60,80,100])
plt.figure(figsize=(13,7))
ax = sns.scatterplot(data=df_factor.dropna(), x='Valuation', y='Quality', hue='Momentum_lvl',
size ='Growth_lvl', palette='RdYlGn',
sizes = list(np.arange(10,100,20)),
hue_order= [20,40,60,80,100])
plt.xlim(0,100)
plt.ylim(0,100)
plt.legend(bbox_to_anchor=(1.05,1), loc=2, borderaxespad=0.)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.