可视化 3d 集群

Visualising 3d clusters

所以我有 3 个集群,我想在 3d 图形上可视化。我不确定如何添加第三个轴。

X = np.array(X)
plt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s = 100, c = 'red', label = 'Cluster 1')
plt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s = 100, c = 'blue', label = 'Cluster 2')
plt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s = 100, c = 'green', label = 'Cluster 3')
plt.xlabel("Recency")
plt.ylabel("Frequency")
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1],s = 300, c = 'yellow', label = 'Centroids')
plt.show()

这就是我所做的,但我知道这仅适用于 2d。 y_kmeans 包含与我的 X 数据集中的行号对应的集群。 X 数据集有 3 列。 我想知道是否有人可以指导我如何做到这一点? 更新: 能够在以下答案的帮助下使其工作。

随时根据您的需要进行调整

from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
import random


fig = pyplot.figure()
ax = Axes3D(fig)

x_vals = np.random.rand(1000)
y_vals = np.random.rand(1000)
z_vals = np.random.rand(1000)



ax.scatter(x_vals, y_vals, z_vals, color='red')
ax.scatter(x_vals+0.2, y_vals-0.8, z_vals, color='blue')
pyplot.show()

输出: