gpt4 book ai didi

python - KMeans "No handles with labels found to put in legend"的 3D 散点图图例错误

转载 作者:太空宇宙 更新时间:2023-11-03 20:22:23 26 4
gpt4 key购买 nike

我已经为 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()

最佳答案

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

遵循 Scatter plots with a 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

关于python - KMeans "No handles with labels found to put in legend"的 3D 散点图图例错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58073489/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com