2017-08-30 15 views
1

我已經計算了文檔距離,並且在sklearn中使用MDS以使用matplotlib繪製它們。我想用seaborn(pairplot)繪製它們,但不知道如何翻譯MDS數據以便它可以被seaborn讀取。如何格式化數據以供seaborn使用

from sklearn.manifold import MDS 

mds = MDS(n_components=2, dissimilarity="precomputed", random_state=1) 
pos = mds.fit_transform(dist) 
xs, ys = pos[:, 0], pos[:, 1] 

names = [name for name in labels] 

# Define the plot 
for x, y, name in zip(xs, ys, names): 
    plt.scatter(x, y, color=color) 
    plt.text(x, y, name) 


plt.show() 

回答

1

the documentation for pairplot()說明,本函數需要一個長格式數據幀,其中每列是一個變量,並且每個行是一個觀察。 最簡單的就是使用Pandas構造這個數據框(儘管我相信一個numpy數組可以工作)。

長形式的數據框的行數與觀察值一樣多,每列都是一個變量。 seaborn的功能是使用分類列來拆分數據幀是不同的組。

在你的情況下,數據幀可能會是這樣的:

X   Y   label 
0 0.094060 0.484758 Label_00 
1 0.375537 0.150206 Label_00 
2 0.215755 0.796629 Label_02 
3 0.204077 0.921016 Label_01 
4 0.673787 0.884718 Label_01 
5 0.854112 0.044506 Label_00 
6 0.225218 0.552961 Label_00 
7 0.668262 0.482514 Label_00 
8 0.935415 0.100438 Label_00 
9 0.697016 0.633550 Label_01 
(...) 

你將它傳遞給pairplot像這樣:

sns.pairplot(data=df, hue='label') 

enter image description here

相關問題