python - python 如何为 GraphViz 编写一个点文件,要求将某些边染成红色?

标签 python dictionary graphviz dot directed-acyclic-graphs

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

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

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" ];
}

如果边的权重小于特定数字(例如 0.5),例如从节点 3 到 2 的边(权重为 0.09),如何更改此 Python 代码以要求 GraphViz 将边着色为红色? 更一般地说,是否有一个好地方可以详细了解如何编写 python 代码来为 GraphViz 创建各种 DOT 文件,并查看好的示例?

最佳答案

Graphviz 支持color attribute .

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

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

将边缘着色为红色。

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

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 - python 如何为 GraphViz 编写一个点文件,要求将某些边染成红色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23734030/

相关文章:

python - Python校准相机

python : How do I make my program produce a file with a random file name

c# - 路径平滑/点减少算法

python - 如何可视化单词模式?

graphviz 垂直绘制图形

python - 如何通过匹配python中的特定字符从字符串中删除某些字符

python - 如何在Windows下使用所有外部编译Python?

c++ - 2个unique_ptr的 map

c# - 如何使用 LINQ 填充字典?

graphviz - 使用graphviz,HTML换行