自动为Graphviz中的节点分配颜色 [英] Automatically assign color to nodes in Graphviz
问题描述
我正在使用Python和Graphviz绘制一些由节点组成的簇图. 我想为每个节点分配不同的颜色,具体取决于属性,例如它的x坐标.
I'm using Python and Graphviz to draw some cluster graph consist of nodes. I want to assign different colors to each node, dependent on an attribute, e.g. its x-coordinate.
这是我生成图形的方式:
Here's how I produce graph:
def add_nodes(graph, nodes):
for n in nodes:
if isinstance(n, tuple):
graph.node(n[0], **n[1])
else:
graph.node(n)
return graph
A = [[517, 1, [409], 10, 6],
[534, 1, [584], 10, 12],
[614, 1, [247], 11, 5],
[679, 1, [228], 13, 7],
[778, 1, [13], 14, 14]]
nodesgv = []
for node in A:
nodesgv.append((str(node[0]),{'label': str(node[0]), 'color': ???, 'style': 'filled'}))
graph = functools.partial(gv.Graph, format='svg', engine='neato')
add_nodes(graph(), nodesgv).render(('img/test'))
现在我想按照每个节点的第一个值的顺序为每个节点分配颜色. 更具体地说,我想要的是:
And now I want to assign a color to each node with the ordering of the first value of each node. More specifically what I want is:
- 红色节点(517)
- 黄色节点(534)
- 绿色节点(614)
- 蓝色节点(679)
- 和一个紫色节点(778)
我知道如何为图形分配颜色,但是我要寻找的是与使用matplotlib时的c = x部分相似的东西.
I know how to assign colors to the graph, but what I'm looking for is something similar to the c=x part when using matplotlib.
问题是我无法事先知道节点(群集)的数量,因此例如,如果我有7个节点,我仍然希望有一个图,其中有7个节点从红色开始,并以紫色的.
Problem is I'm not able to know the number of nodes (clusters) beforehand, so for example if I've got 7 nodes, I still want a graph with 7 nodes that start from a red one, and end with a purple one.
plt.scatter(x, y, c=x, s=node_sizes)
那么Graphviz中有什么属性可以做到这一点?
So is there any attribute in Graphviz that can do this?
或者谁能告诉我matplotlib中的颜色图如何工作?
Or can anyone tell me how does the colormap in matplotlib work?
很抱歉,您所输入的内容不够清晰. T ^ T
Sorry for the lack of clarity. T^T
推荐答案
哦,我想出了一种获取我想要的东西的方法. 仅用于录制和其他人可能有相同的问题(?) 只需重新调整颜色图的比例并为节点分配相应的(颜色)索引即可.
Oh I figured out a way to get what I want. Just for recording and for someone else may have a same problem(?) Can just rescale a color map and assign the corresponding index (of color) to the nodes.
def add_nodes(graph, nodes):
for n in nodes:
if isinstance(n, tuple):
graph.node(n[0], **n[1])
else:
graph.node(n)
return graph
A = [[517, 1, [409], 10, 6],
[534, 1, [584], 10, 12],
[614, 1, [247], 11, 5],
[679, 1, [228], 13, 7],
[778, 1, [13], 14, 14]]
nodesgv = []
Arange = [ a[0] for a in A]
norm = mpl.colors.Normalize(vmin = min(Arange), vmax = max(Arange))
cmap = cm.jet
for index, i in enumerate(A):
x = i[0]
m = cm.ScalarMappable(norm = norm, cmap = cmap)
mm = m.to_rgba(x)
M = colorsys.rgb_to_hsv(mm[0], mm[1], mm[2])
nodesgv.append((str(i[0]),{'label': str((i[1])), 'color': "%f, %f, %f" % (M[0], M[1], M[2]), 'style': 'filled'}))
graph = functools.partial(gv.Graph, format='svg', engine='neato')
add_nodes(graph(), nodesgv).render(('img/test'))
这篇关于自动为Graphviz中的节点分配颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!