简体   繁体   中英

Scatter plot with different text at each data point that matches the size and colour of the marker

I have this scatter plot (I know it's a mess!) and I am trying to change the colour and size of the text adjacent to the marker to match that of the marker. In this case, text that is next to a green dot would be green and text that is next to an orange dot would be orange. Ideally, I would also be able to make the text smaller.

The code I use to generate the scatter plot below is:

  plot = plt.figure(figsize=(30,20))
ax = sns.scatterplot(x='Recipients', y='Donors', data=concatenated, hue = 'Cost of Transfer',
                     palette="Set2", s= 300)

def label_point(x, y, val, ax):
    a = pd.concat({'x': x, 'y': y, 'val': val}, axis=1)
    for i, point in a.iterrows():
        ax.text(point['x']+.1, point['y'], str(point['val']))

label_point(concatenated.Recipients, concatenated.Donors, concatenated.Species, plt.gca())

在此处输入图片说明

Any help is greatly appreciated :)

Text in plot is set by ax.text(), matplotlib axes.text .

# Before
ax.text(point['x']+.1, point['y'], str(point['val']))
# After
ax.text(point['x']+.1, point['y'], str(point['val']), {'color': 'g', 'fontsize': 20})

Try color and font size you like.

It would be pretty complicated and probably error-prone to try to find the colors of the points in a sns.scatterplot() . Do you really need to use scatterplot() ?

If not, I would suggest forgetting about seaborn and just creating the plot using matplotlib directly, which gives you much more control:

iris = sns.load_dataset("iris")
iris['label'] = 'label_'+iris.index.astype(str) # create a label for each point

df = iris
x_col = 'sepal_length'
y_col = 'sepal_width'
hue_col = 'species'
label_col = 'label'
palette = 'Set2'
size = 5

fig, ax = plt.subplots()
colors = matplotlib.cm.get_cmap(palette)(range(len(df[hue_col].unique())))
for (g,temp),c in zip(iris.groupby('species'),colors):
    print(g,c)
    ax.plot(temp[x_col], temp[y_col], 'o', color=c, ms=size, label=g)
    for i,row in temp.iterrows():
        ax.annotate(row[label_col], xy=(row[x_col],row[y_col]), color=c)
ax.set_xlabel(x_col)
ax.set_ylabel(y_col)
ax.legend(title=hue_col)

在此处输入图片说明

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