2017-04-18 415 views
0

我已经聚集了3个要素Feature1,Feature2和Feature3,并提出了2个聚类。 我正在尝试使用matplotlib可视化3D集群。使用matplotlib可视化3D聚类

在下面的表中,有在其上执行的聚类三个特征。集群的个数为2

Feature1  Feature2 Feature3 ClusterIndex 
    0 1.349656e-09 1.000000 1.090542e-09 0 
    1 1.029752e-07 1.000000 6.040669e-08 0 
    2 2.311729e-07 1.000000 1.568289e-11 0 
    3 1.455860e-08 6.05e-08 1.000000  1 
    4 3.095807e-07 2.07e-07 1.000000  1 

尝试这种代码:

fig = plt.figure() 
    ax = fig.add_subplot(111, projection='3d') 
    x = np.array(df['Feature1']) 
    y = np.array(df['Feature2']) 
    z = np.array(df['Feature3']) 
    ax.scatter(x,y,z, marker=colormap[kmeans.labels_], s=40) 

但是,我得到的错误"ValueError: could not convert string to float: red"。标记部分因此是我得到错误的地方。集群

2D可视化是通过在散点图中绘制点,并与类群标签区分它很简单。

只是想知道是否有一种方法来做集群的三维可视化。

任何建议将不胜感激!

+0

我得到的错误 “ValueError异常:无法将字符串转换为float:红色”。标记部分是我得到错误的地方。它无法将字符串转换为浮点数。类型转换没有帮助。在二维阴谋,它的作品,但不知道为什么它不适用于3D绘图。 – user3447653

+0

那么,什么是'colormap'和什么是'kmeans.labels_'? – ImportanceOfBeingErnest

+0

@ ImportanceOfBeingErnest:kmeans.labels是像0和1那样的集群索引(因为我有2个集群)。色彩地图将标签转换为颜色。 – user3447653

回答

1

原则上,问题的代码应该工作。然而目前还不清楚marker=colormap[kmeans.labels_]会做什么以及为什么需要它。

三维散点图与2D版本完全相同。

标记参数会期望一个标记字符串,如"s""o"来确定标记形状。
可以使用参数c设置颜色。您可以提供单个颜色或阵列/颜色列表。在下面的示例中,我们只需提供c的群集索引并使用色彩映射。

import matplotlib.pyplot as plt 
from mpl_toolkits.mplot3d import Axes3D 
import pandas as pd 
import numpy as np 

v = np.random.rand(10,4) 
v[:,3] = np.random.randint(0,2,size=10) 
df = pd.DataFrame(v, columns=['Feature1', 'Feature2','Feature3',"Cluster"]) 
print (df) 

fig = plt.figure() 
ax = fig.add_subplot(111, projection='3d') 
x = np.array(df['Feature1']) 
y = np.array(df['Feature2']) 
z = np.array(df['Feature3']) 

ax.scatter(x,y,z, marker="s", c=df["Cluster"], s=40, cmap="RdBu") 

plt.show() 

enter image description here