Проблема с вашим кодом заключается в том, что вы не указали label
для рассеянных точек, поэтому нет причины для legend
.
После диаграмм разброса с легендой учебник на веб-сайте matplotlib, следующий код рандомизирует данные с тремя "классами" и наносит их на карту с легендой:
from matplotlib import pyplot as plt
import numpy as np
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
xs = np.random.normal(0, 1, (20,))
ys = np.random.normal(0, 1, (20,))
zs = np.random.normal(0, 1, (20,))
labels = np.random.choice(["First", "Second", "Third"], (20,))
for lbl in np.unique(labels):
indices = np.where(labels == lbl)
x = xs[indices]
y = ys[indices]
z = zs[indices]
print(x,y,z,lbl)
ax.scatter(x, y, z, s=50, alpha=0.6, label=str(lbl), cmap='rainbow')
ax.legend()
plt.show()
Результат:
![Code output](https://i.stack.imgur.com/9bp9R.png)