python - 3D scatter plot legend error from KMeans "No handles with labels found to put in legend"
问题描述
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()
解决方案
您的代码的问题在于您没有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()
结果是:
推荐阅读
- azure - Azure 函数 - 将消息从 TimerTrigger 广播到 Azure SignalR 服务
- java - 如何知道 HAProxy 是否从 java 代码中关闭?
- python - 在 matplotlib 中将日期时间序列绘制为分类数据
- .htaccess - 使用 htaccess 将子域重定向到 url 并将子域内容重定向到 root
- javascript - 防止用户在刷新并停留在同一页面时被重定向到主页 React JS
- python - 将python数组存储在列的每个条目中
- php - 将 woocommerce 产品变体显示为商店页面上的单个产品和 ajax 加载更多
- qt - 将项目动态添加到 StackLayout
- excel - 提取项目符号并粘贴到 Excel 工作表
- swagger - 是否可以在 Swagger 中引用路径定义