我在 Python 中有以下数组:
numbers=[75, 100, 680, 123, 4, 4, 8, 15]
这些数字对应于与特定集群相关联的点的数量。
所以在绘制聚类点的同时,我想要一个图例,它提供以下信息:
"Cluster 1 has 75 points"
"Cluster 2 has 100 points"
等等。
我在编写循环代码时遇到困难,因此非常感谢您的帮助。
请您参考如下方法:
更新:
在提供更多信息后,我认为您需要这个:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# random data: 800 samples, 8 coordinates
X_scaled = np.random.rand(800,8)
# some labels e.g. output of clustering algorithm
labels = np.concatenate([np.ones(400),np.zeros(400)])
# unique classes/groups in the data
number_of_classes = np.unique(labels).shape[0]
# the desired legends
legends = ['cluster 1', 'cluster 2']
# colors for the groups
colors = ["r","b"]
fig1 = plt.figure()
ax = Axes3D(fig1)
for i in range(number_of_classes):
ax.scatter(X_scaled[:,0][labels==i], X_scaled[:,1][labels==i],X_scaled[:,7][labels==i], c = colors[i] ,s=50, label= legends[i] + " has {} points".format(X_scaled[:,0][labels==i].shape[0]))
plt.legend()
plt.savefig("test.png", dpi = 300)
plt.show()
编辑 1:如何使用 for 循环创建图例。
legends = []
for i in range(5):
legends.append('cluster{}'.format(i))
print(legends)
['cluster0', 'cluster1', 'cluster2', 'cluster3', 'cluster4']
