我已经计算了文档距离,并在 sklearn 中使用 MDS 来使用 matplotlib 绘制它们。我想用 seaborn (pairplot) 绘制它们,但不知道如何转换 MDS 数据以便 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()
最佳答案
如 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')
关于python - 如何格式化数据以供 seaborn 使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45960625/