2017-04-18 48 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