如何在python中制作强制导向图?

时间:2016-08-12 23:23:38

标签: python data-visualization igraph networkx r-qgraph

我想要一个图表,显示几个节点,表示关系的节点之间的方向箭头,厚度相对于其连接的强度。

在R中这很简单

library("qgraph")
test_edges <- data.frame(
   from = c('a', 'a', 'a', 'b', 'b'),
   to = c('a', 'b', 'c', 'a', 'c'),
   thickness = c(1,5,2,2,1))
qgraph(test_edges, esize=10, gray=TRUE)

哪个产生: force directed graph via R

但在Python中,我找不到一个明确的例子。 NetworkX和igraph似乎暗示它是可能的,但我无法弄明白。

1 个答案:

答案 0 :(得分:4)

我首先尝试使用使用matplotlib的NetworkX标准绘图函数,但我不是很成功。

但是,NetworkX也是supports drawing to the dot formatsupports edge weight, as the penwidth attribute

所以这是一个解决方案:

import networkx as nx

G = nx.DiGraph()
edges = [
    ('a', 'a', 1),
    ('a', 'b', 5),
    ('a', 'c', 2),
    ('b', 'a', 2),
    ('b', 'c', 1),
    ]
for (u, v, w) in edges:
    G.add_edge(u, v, penwidth=w)

nx.nx_pydot.write_dot(G, '/tmp/graph.dot')

然后,要显示图表,请在终端中运行:

dot -Tpng /tmp/graph.dot > /tmp/graph.png
xdg-open /tmp/graph.png

(或您的操作系统上的等效文件)

显示:

output of the graph described by OP