简体   繁体   中英

Retrieve color label mapping from a seaborn scatterplot hue

I have the following code to plot my seaborn scatterplot

plt.figure(figsize=(120,120))
p1 = sn.scatterplot('tsne1', # Horizontal axis
       'tsne2', # Vertical axis
       data=data, # Data source
       hue='label',
       size = 30,
       legend=False)  

for line in range(0,data.shape[0]):
     p1.text(data.tsne1[line]+0.01, data.tsne2[line], 
     data.label[line], horizontalalignment='left', 
     size='medium', color='black', weight='semibold')

After plotting the scatterplot I loop on my data in order to display the text label beside its data points. Currently, my text is displayed in black but I wish to display it in the right color.

How can I retrieve a mapping between my labels and the hue chosen by seaborn in order to reuse the color when displaying the text?

You can set the palette using sns.color_palette , and if your labels are numeric, it is a matter of calling them out:

from sklearn.datasets import make_blobs
import seaborn as sns

X, y = make_blobs(n_samples=100, centers=5, shuffle=False,random_state=42)
data = pd.DataFrame(X,columns=['tsne1','tsne2'])
data['label'] = y

pal = sns.color_palette("hls",len(data['label'].unique()))

p1 = sns.scatterplot('tsne1', # Horizontal axis
                     'tsne2', # Vertical axis
                     data=data, # Data source
                     hue='label',
                     legend=False,
                     palette=pal)

for line in range(0,data.shape[0]):
    p1.text(data.tsne1[line]+0.01, data.tsne2[line], 
            data.label[line], horizontalalignment='left', 
            size='medium', color=pal[data.label[line]], weight='semibold')

在此处输入图像描述

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM