如何在python中制作力导向图? [英] How do I make a force-directed graph in python?
问题描述
我想要一个图形,该图形显示几个节点,节点之间的方向箭头表示一种关系,其厚度相对于它们的连接强度.
在R中,这非常简单
library("qgraph")test_edges<-data.frame(从= c('a','a','a','b','b'),到= c('a','b','c','a','c'),厚度= c(1,5,2,2,1))qgraph(test_edges,esize = 10,gray = TRUE)
哪个生产:
但是在Python中,我找不到一个清晰的例子.NetworkX和igraph似乎暗示这是可能的,但我一直无法弄清楚.
我首先尝试使用NetworkX的标准绘图功能(使用matplotlib)进行此操作,但效果不是很好.
但是,NetworkX还
描述的图形的输出I want a graph that shows a few nodes, directional arrows between nodes representing a relationship, with thickness relative to the strength of their connection.
In R this is very simple
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)
Which produces:
But in Python I haven't been able to find a clear example. NetworkX and igraph seem to hint that it's possible, but I haven't been able to figure it out.
I first tried doing this with NetworkX's standard drawing functions, which use matplotlib, but I was not very successful.
However, NetworkX also supports drawing to the dot
format, which supports edge weight, as the penwidth
attribute.
So here is a solution:
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')
Then, to show the graph, run in a terminal:
dot -Tpng /tmp/graph.dot > /tmp/graph.png
xdg-open /tmp/graph.png
(or the equivalent on your OS)
Which shows:
这篇关于如何在python中制作力导向图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!