如何用Python写一个要求某些边缘颜色为红色的GraphViz点文件?

2024-10-01 15:28:34 发布

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

我正在使用python代码(使用python嵌套dicts)为GraphViz编写一个点文件来绘制我的有向边加权图,这要感谢DAWG的建议。。。在

nestedg={1: {2: 3, 3: 8, 5: -4}, 
     2: {4: 1, 5: 7}, 
     3: {2: 0.09}, 
     4: {1: 2, 3: -5}, 
     5: {4: 6}}

with open('/tmp/graph.dot','w') as out:
    for line in ('digraph G {','size="16,16";','splines=true;'):
        out.write('{}\n'.format(line))  
    for start,d in nestedg.items():
        for end,weight in d.items():
              out.write('{} -> {} [ label="{}" ];\n'.format(start,end,weight))
    out.write('}\n')

它生成了这个.DOT文件,GraphViz可以从中生成一个漂亮的图形图像:

^{pr2}$

问题: 如果一个边的权重小于一个特定的数字(例如0.5),比如从节点3到节点2的边(权重为0.09),我该如何更改python代码以请求GraphViz将其颜色设置为红色? 更一般地说,有没有一个好地方可以学习更多关于如何编写python代码来为GraphViz创建各种DOT文件,以及看到一些好的示例吗? 谢谢Tom99


Tags: 文件代码informatforlineitemsout
1条回答
网友
1楼 · 发布于 2024-10-01 15:28:34

Graphviz支持color attribute。在

因此,您可以修改您的代码以写出行

3 -> 2 [ label="0.09" color="red" ];

将边着色为红色。在

实现它的一个简单方法是修改行

^{pr2}$

进入

if weight < 0.5:
    out.write('{} -> {} [ label="{}" color="red" ];\n'.format(start,end,weight))
else:
    out.write('{} -> {} [ label="{}" ];\n'.format(start,end,weight))

相关问题 更多 >

    热门问题