1

I have plotted 3D scatter plot for a KMeans model which I had fitted for RFM analysis. I used KMeans model labels for "color" groups. when I used legend(), it pops an error, "No handles with labels found to put in legend"

from mpl_toolkits.mplot3d import Axes3D     
%matplotlib notebook     

fig = plt.figure(figsize=(8, 6))     
ax = fig.add_subplot(111, projection='3d')      

xs = RFM['Recency'].dt.days      
ys = RFM['Frequency']      
zs = RFM['Value']      
ax.scatter(xs, ys, zs, s=50, alpha=0.6, c=final_model.labels_, cmap='rainbow')      

ax.set_xlabel('Recency(days)')      
ax.set_ylabel('Frequency')      
ax.set_zlabel('Value')      

ax.legend()      
Erandi
  • 11
  • 5
  • What legend do you expect? Maybe you are confusing it with [matplotlib.pyplot.colorbar](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.colorbar.html) – Itay Sep 24 '19 at 05:27
  • I want customer labels(1,2,3...) assigned to each "rainbow" colors on the plot, as legend – Erandi Sep 24 '19 at 05:42
  • But how do you link the customer labels to the data (x,y,z)? – Itay Sep 24 '19 at 06:25

1 Answers1

1

The problem with your code is that you didn't provide any label for the scattered points, so there's no reason legend would work.

Following the Scatter plots with a legend tutorial on matplotlib's website, the following code randomize data with three "classes" and plot them with a legend:

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()

The result is:

Code output

Itay
  • 16,601
  • 2
  • 51
  • 72
  • thank you very much Itay. Somehow this code ended up with an error for me; I made it using matplotlib.patches. – Erandi Sep 24 '19 at 17:20
  • @Itay May I ask you kindly to check similar [question](https://stackoverflow.com/questions/68895380/automated-legend-creation-for-3d-plot). Thanks in advance. – Mario Sep 01 '21 at 18:58