使用PyGraphviz在图形节点上绘制更多信息
我想创建一个图形并把它画出来,到现在为止一切都很好,但问题是我想在每个节点上绘制更多的信息。我看到可以把属性保存到节点和边上,但我该怎么把这些属性画出来呢?我正在使用PyGraphviz,它是基于Graphviz的。
3 个回答
0
如果你已经有一个图形,并且想给某些属性加上标签,你可以使用下面的代码:
def draw_nx_with_pygraphviz_attribtes_as_labels(g, attribute_name, path2file=None):
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# https://stackoverflow.com/questions/15345192/draw-more-information-on-graph-nodes-using-pygraphviz
if path2file is None:
path2file = './example.png'
path2file = Path(path2file).expanduser()
g = nx.nx_agraph.to_agraph(g)
# to label in pygrapviz make sure to have the AGraph obj have the label attribute set on the nodes
g = str(g)
g = g.replace(attribute_name, 'label') # it only
print(g)
g = pgv.AGraph(g)
g.layout()
g.draw(path2file)
# https://stackoverflow.com/questions/20597088/display-a-png-image-from-python-on-mint-15-linux
img = mpimg.imread(path2file)
plt.imshow(img)
plt.show()
# remove file https://stackoverflow.com/questions/6996603/how-to-delete-a-file-or-folder
path2file.unlink()
# -- tests
def test_draw():
# import pylab
import networkx as nx
g = nx.Graph()
g.add_node('Golf', size='small')
g.add_node('Hummer', size='huge')
g.add_node('Soccer', size='huge')
g.add_edge('Golf', 'Hummer')
draw_nx_with_pygraphviz_attribtes_as_labels(g, attribute_name='size')
if __name__ == '__main__':
test_draw()
结果:
特别要注意的是,这两个“巨大”的节点并没有变成自环,它们是两个不同的节点(比如说,两个运动项目都可以被称为“巨大”,但它们并不是同一个运动或实体)。
相关内容,但使用nx绘图:使用节点标签默认显示节点名称绘制networkx图形
4
你只能给节点和边添加一些支持的属性。这些属性在GraphViz中有特定的含义。
如果你想在边或节点上显示额外的信息,可以使用label
这个属性。
4
一个例子是
import pygraphviz as pgv
from pygraphviz import *
G=pgv.AGraph()
ndlist = [1,2,3]
for node in ndlist:
label = "Label #" + str(node)
G.add_node(node, label=label)
G.layout()
G.draw('example.png', format='png')
但要确保你明确添加属性 label
,这样可以显示额外的信息,就像马丁提到的那样 https://stackoverflow.com/a/15456323/1601580。