如何在python中生成一个forcedirected图?

2024-10-01 04:52:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要一个显示几个节点的图,节点之间的方向箭头表示一个关系,其厚度与它们的连接强度有关。在

在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似乎暗示这是可能的,但我还没能搞清楚。在


Tags: tofromtestdata节点关系libraryframe
1条回答
网友
1楼 · 发布于 2024-10-01 04:52:29

我第一次尝试使用NetworkX的标准绘图函数来实现这一点,它使用matplotlib,但是我并不是很成功。在

但是,NetworkX也supports drawing to the ^{} format,即supports edge weight, as the ^{} 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')

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

^{pr2}$

(或操作系统上的等效项)

这表明:

output of the graph described by OP

相关问题 更多 >