【问题标题】:3D scatter plot legend error from KMeans "No handles with labels found to put in legend"来自 KMeans 的 3D 散点图图例错误“找不到带有标签的句柄放入图例”
【发布时间】:2020-01-24 04:13:22
【问题描述】:

我为 KMeans 模型绘制了 3D 散点图,该模型已适合 RFM 分析。我将 KMeans 模型标签用于“颜色”组。 当我使用 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()      

【问题讨论】:

  • 你期待什么传奇?也许你把它和matplotlib.pyplot.colorbar混淆了
  • 我希望将客户标签(1,2,3...)分配给绘图上的每个“彩虹”颜色,作为图例
  • 但是如何将客户标签链接到数据 (x,y,z)?

标签: python legend k-means scatter3d


【解决方案1】:

您的代码的问题在于您没有为散点提供任何label,因此legend 没有任何作用。

按照 matplotlib 网站上的 Scatter plots 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()

结果是:

【讨论】:

  • 非常感谢Itay。不知何故,这段代码对我来说是一个错误;我使用 matplotlib.patches 制作的。
  • @Itay 请您检查类似的question。提前致谢。
猜你喜欢
  • 1970-01-01
  • 2021-02-09
  • 1970-01-01
  • 2014-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-30
  • 2019-05-23
相关资源
最近更新 更多