如何使用PyGraphviz在无向图的边缘添加和显示权重? [英] How to add and show weights on edges of a undirected graph using PyGraphviz?

查看:347
本文介绍了如何使用PyGraphviz在无向图的边缘添加和显示权重?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import pygraphviz as pgv
A = pgv.AGraph()
A.add_node('Alice')
A.add_node('Emma')
A.add_node('John')
A.add_edge('Alice', 'Emma')
A.add_edge('Alice', 'John')
A.add_edge('Emma', 'John')
print A.string()
print "Wrote simple.dot"
A.write('simple.dot')  # write to simple.dot
B = pgv.AGraph('simple.dot')  # create a new graph from file
B.layout()  # layout with default (neato)
B.draw('simple.png')  # draw png
print 'Wrote simple.png'

我想在边缘上添加权重,该权重也应该出现在图中.

I want to add weights to the edges which should also show up on the figure.

推荐答案

您可以在创建边缘时将属性添加到边缘:

You can add attributes to the edges when you create them:

A.add_edge('Alice', 'Emma', weight=5)

或者您可以稍后通过以下方式设置它们:

or you can set them later with:

edge = A.get_edge('Alice', 'Emma')
edge.attr['weight'] = 5

要将文本信息添加到边缘,请给它们一个label属性:

To add textual information to edges, give them a label attribute instead:

edge = A.get_edge('Alice', 'Emma')
edge.attr['label'] = '5'

所有属性都在内部存储为字符串,但是GraphViz会将它们解释为特定类型.请参阅属性文档.

All attributes are internally stored as strings but GraphViz interprets these as specific types; see the attribute documentation.

这篇关于如何使用PyGraphviz在无向图的边缘添加和显示权重?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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