在Gnuplot中或使用matplotlib绘制图形

2024-04-25 01:52:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个群集的数据集。输出结果如下:

1 [1,2]

2 [1,6]

1 [2,4]

其中1,2。。。是集群id,而[1,2]…等等是点。所以我想画出两个轴上的点x坐标和y坐标,并对应于图中的一个点,将簇id描述为标签,对于不同的id,点的颜色应该是不同的。我该怎么做?在

谢谢


Tags: 数据id颜色集群标签群集
1条回答
网友
1楼 · 发布于 2024-04-25 01:52:34

如果其中一个轴是簇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、cluster附加到三个单独的列表中,scatter这些列表。在

相关问题 更多 >