I'm trying to change the Bins in the legend of a plot created with Seaborn. 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.
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
For example:
import matplotlib.pyplot as plt import seaborn as sns import numpy as np
np.random.seed(999) df_factor = pd.DataFrame(np.random.uniform(0,100,(20,4)),columns=['Valuation','Quality','Growth','Momentum'])
Here we introduce another column that discretizes the two columns. You can also overwrite it or use a 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:
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.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.