【问题标题】:Draw more information on graph\nodes using PyGraphviz使用 PyGraphviz 绘制有关图形\节点的更多信息
【发布时间】:2023-04-05 20:22:01
【问题描述】:

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

【问题讨论】:

    标签: python graphviz pygraphviz


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      一个例子是

      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 以获得额外信息,以显示 Martin 提到的 https://stackoverflow.com/a/15456323/1601580

      【讨论】:

      • 请注意,对于尝试重复使用此答案的任何人,您必须将要显示的属性命名为“标签”。
      【解决方案3】:

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

      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 绘图:Plotting networkx graph with node labels defaulting to node name

      【讨论】:

        猜你喜欢
        • 2019-04-13
        • 2019-07-17
        • 1970-01-01
        • 2020-04-23
        • 2021-02-28
        • 2020-02-24
        • 2015-03-08
        • 1970-01-01
        • 2019-01-29
        相关资源
        最近更新 更多