matlplotlib scatterplot with numbers as symbols + legend

Viewed 281

I would like to draw a scatterplot that has colored numbers instead of points as symbols. I did as follow

n=np.arange(1,14,1)

fig, axs = plt.subplots(1, 2)

axs[0].scatter(x, y, linestyle='None', color="white")

for i, txt in enumerate(n):
     axs[0].annotate(txt, (x[i], y[i]), color=x_y_colours[i], ha="center", va="center")
       

It worked but now I don't know how to create the legend! I would like to have colored numbers as the symbol and then the label.

Thank you all!

1 Answers

You can use markers in latex form, using text or digits as marker. For this, you can write marker='$...$', similar to how latex is used in matplotlib labels. Note that these markers get centered automatically.

import matplotlib.pyplot as plt
import numpy as np

n = np.arange(1, 14)
theta = np.pi * n * (3 - np.sqrt(5))
r = np.sqrt(n)
x = r * np.cos(theta)
y = r * np.sin(theta)
x_y_colours = plt.get_cmap('hsv')(n / n.max())
x_y_labels = [*'abcdefghijklm']

fig, ax = plt.subplots()
for xi, yi, color_i, label_i, txt in zip(x, y, x_y_colours, x_y_labels, n):
    ax.scatter(xi, yi, marker=f'${txt}$', s=200, color=color_i, label=label_i)
ax.legend(markerscale=0.5, bbox_to_anchor=[1.01, 1.01], loc='upper left')
plt.tight_layout()
plt.show()

text or digits as scatter markers

Related