使用PyGraphviz在graph \ nodes上绘制更多信息

时间:2013-03-11 17:49:17

标签: python graphviz pygraphviz

我想创建一个图形并绘制它,到目前为止一直很好,但问题是我想在每个节点上绘制更多信息。 我看到我可以将属性保存到nodes \ edges,但是我如何绘制属性? 我正在使用PyGraphviz女巫使用Graphviz。

3 个答案:

答案 0 :(得分:3)

一个例子是

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')

答案 1 :(得分:2)

您只能将supported attributes添加到节点和边缘。这些属性对GrpahViz具有特定含义。

要显示有关边或节点的额外信息,请使用label属性。

答案 2 :(得分:-1)

如果你已经有一个带有你想要标记的属性的图表,你可以使用这个:

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()

结果:

enter image description here

特别注意,这两个巨大的并没有成为一个自循环,它们是两个不同的节点(例如,两个运动可以是巨大的,但它们不是同一个运动/实体)。

相关但与 nx 绘图:Plotting networkx graph with node labels defaulting to node name