在Gnuplot或matplotlib中绘制图形
我有一组关于聚类的数据,输出结果大概是这样的:
1 [1,2]
2 [1,6]
1 [2,4]
这里的1、2等是聚类的编号,而[1,2]等是对应的点的坐标。我想在图上绘制这些点的x坐标和y坐标,并在图中用点来表示聚类编号。不同的聚类编号用不同的颜色来区分。请问我该怎么做呢?
谢谢!
1 个回答
1
如果一个轴是聚类的ID,我不太明白怎么把x和y坐标都放到另一个轴上。所以我把x和y坐标分别画在x轴和y轴上,然后用聚类ID作为标签;我想你可以交换哪个值放到哪个轴上。
import matplotlib.pyplot as plt
from ast import literal_eval
data = """1 [1,2]
2 [1,6]
1 [2,4]"""
def cluster_color(clusternum):
'''Some kind of map of cluster ID to a color'''
if clusternum == 1:
return [(1, 0,0)]
if clusternum == 2:
return [(0, 0, 1)]
else:
return [(0, 1,0)]
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
def datalines(pt):
'''Pick the coordinates and label out of this text format'''
label, xy = pt.split(' ')
xy = literal_eval(xy)
assert(len(xy) == 2)
return xy[0], xy[1], label
for pt in data.splitlines():
if len(pt) > 0:
x, y, cluster = datalines(pt)
ax.scatter(x, y, c= cluster_color(float(cluster)))
ax.text(x + .01, y + .01, cluster)
fig.show()
注意:如果你的数据很多,不要对每个点单独调用scatter
;应该把x、y和聚类ID分别放到三个列表里,然后一次性用scatter
来画这些列表。