python如何为GraphViz写一个点文件,要求一些边被着色为红色? [英] How can python write a dot file for GraphViz asking for some edges to be colored red?

查看:413
本文介绍了python如何为GraphViz写一个点文件,要求一些边被着色为红色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用python代码(使用python嵌套的代码)为GraphViz写出一个DOT文件来绘制我的有向边加权图,感谢DAWG的建议...

I am using python code (with python nested dicts) to write out a DOT file for GraphViz to draw my directed edge-weighted graph, thanks to DAWG's suggestions...

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可以从中生成一个漂亮的图形图像:

Which produces this .DOT file, from which GraphViz can produce a nice graph image:

digraph G {
size="16,16";
splines=true;
1 -> 2 [ label="3" ];
1 -> 3 [ label="8" ];
1 -> 5 [ label="-4" ];
2 -> 4 [ label="1" ];
2 -> 5 [ label="7" ];
3 -> 2 [ label="0.09" ];
4 -> 1 [ label="2" ];
4 -> 3 [ label="-5" ];
5 -> 4 [ label="6" ];
}

QUESTION:
我如何更改这个python代码来询问GraphViz如果其重量小于特定数字(例如0.5),例如从节点3到2的边缘(重量为0.09),则对边缘RED进行着色?
更一般地说,有一个更好的地方可以学习更多关于如何编写python代码来创建GraphViz的各种DOT文件,并查看好的例子?
感谢Tom99

QUESTION: How can I change this python code to ask GraphViz to color an edge RED if its weight is less than a specific number (e.g., 0.5), such as the edge from node 3 to 2 (with a weight of 0.09)? And more generally is there a good place to learn much more about how to write python code to create all kinds of DOT files for GraphViz, and to see good examples? Thanks Tom99

推荐答案

Graphviz支持颜色属性

Graphviz supports color attribute.

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

Thus, you could modify your code to write out the line

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

将边缘标为红色。

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

A simple way to achieve it is to modify the line

out.write('{} -> {} [ label="{}" ];\n'.format(start,end,weight))

进入

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

这篇关于python如何为GraphViz写一个点文件,要求一些边被着色为红色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆