如何正确绘制networkx图 [英] How to draw properly networkx graphs

查看:612
本文介绍了如何正确绘制networkx图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了这段代码,可以让我绘制如下图所示的图形

I got this code which allows me to draw a graph like the posted below

import networkx as nx
import pylab as plt
from networkx.drawing.nx_agraph import graphviz_layout


G = nx.DiGraph()
G.add_node(1,level=1)
G.add_node(2,level=2)
G.add_node(3,level=2)
G.add_node(4,level=3)

G.add_edge(1,2)
G.add_edge(1,3)
G.add_edge(2,4)

nx.draw(G, pos=graphviz_layout(G), node_size=1600, cmap=plt.cm.Blues,
        node_color=range(len(G)),
        prog='dot')
plt.show()

问题是,我该如何绘制带有以下节点的图形?

Question is, how could i draw the graph with nodes which:

  • 使用白色背景色
  • 内部带有标签
  • 已指示箭头
  • 可选地,箭头显示一定的重量
  • 自动或手动排列得很好

类似于下图的

正如您在该图中看到的那样,节点对齐得很好

As you can see in that image, nodes are aligned really nicely

推荐答案

由于拥有Graphviz,因此可以使用它来制作精美的图形并控制图形的元素. 点"布局引擎在像示例中那样定位图上做得很好. 例如

Since you have Graphviz you can use that to make nice drawings and control the elements of the drawing. The 'dot' layout engine does a great job of positioning digraphs like the one in your example. For example

import networkx as nx
import pylab as plt
from networkx.drawing.nx_agraph import graphviz_layout, to_agraph
import pygraphviz as pgv

G = nx.DiGraph()
G.add_node("A",rank=0)
G.add_nodes_from(['B','C','D'],style='filled',fillcolor='red')
G.add_nodes_from(['D','F','G'])
G.add_nodes_from(['H'],label='target')
G.add_edge('A','B',arrowsize=2.0)
G.add_edge('A','C',penwidth=2.0)
G.add_edge('A','D')
G.add_edges_from([('B','E'),('B','F')],color='blue')
G.add_edges_from([('C','E'),('C','G')])
G.add_edges_from([('D','F'),('D','G')])
G.add_edges_from([('E','H'),('F','H'),('G','H')])

# set defaults
G.graph['graph']={'rankdir':'TD'}
G.graph['node']={'shape':'circle'}
G.graph['edges']={'arrowsize':'4.0'}

A = to_agraph(G)
print(A)
A.layout('dot')
A.draw('abcd.png')

产生输出

strict digraph {
    graph [rankdir=TD];
    node [label="\N",
        shape=circle
    ];
    A    [rank=0];
    C    [fillcolor=red,
        style=filled];
    A -> C   [penwidth=2.0];
    B    [fillcolor=red,
        style=filled];
    A -> B   [arrowsize=2.0];
    D    [fillcolor=red,
        style=filled];
    A -> D;
    C -> E;
    C -> G;
    B -> E   [color=blue];
    B -> F   [color=blue];
    D -> G;
    D -> F;
    H    [label=target];
    E -> H;
    G -> H;
    F -> H;
}

以点表示为

您可以在 http://www.graphviz.org上了解有关可调图形参数的信息. /doc/info/attrs.html

这篇关于如何正确绘制networkx图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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