问题描述
在以下代码产生的图中,
B->D
和D->B
我希望此“循环”用两条线表示(一条线可能需要弯曲),而不是用两端带有箭头的单线表示。请问我该如何实现?
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_edges_from(
[('A','B'),('A','C'),('D',('E','F'),('B','H'),'G'),'D'),('C','G')])
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G,pos,node_size = 500)
nx.draw_networkx_labels(G,pos)
nx.draw_networkx_edges(G,arrows=True)
plt.show()
解决方法
您可以使用PyGraphviz
>>> A = nx.nx_agraph.to_agraph(G)
>>> A.draw("G.ps",prog='circo')
,
您可以通过在nx.draw_edges
中指定连接样式直接进行操作,尽管边缘不会成一直线:
import networkx as nx
import matplotlib.pyplot as plt
plt.figure(1,figsize=(12,12))
G = nx.MultiDiGraph()
G.add_edges_from(
[('A','B'),('A','C'),('D',('E','F'),('B','H'),'G'),'D'),('C','G')])
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G,pos,node_size = 500)
nx.draw_networkx_labels(G,pos)
nx.draw_networkx_edges(G,connectionstyle='arc3,rad = 0.1',width = 2,arrows=True)
plt.show()
参考:
- https://stackoverflow.com/a/59917387/8160718
- https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.patches.ConnectionStyle.html
如果您不介意使用备用库,<script>
$(function () {
$('ul.pagination li.PagedList-skipToNext a').html("→");
$('ul.pagination li.PagedList-skipToPrevious a').html("←");
});
</script>
可以自动进行:
igraph
但是有些差异可能很重要:
-
只有从0开始的连续整数可以用作顶点索引,因此您需要手动添加映射:
import igraph as ig g = ig.Graph(directed=True) nodes = list('ABCDEFGH') edges = [('A','G')] g.add_vertices(g_nodes) g.add_edges(g_edges) ig.plot(g,bbox = (400,200),# bounding box of plot vertex_color='lightblue',vertex_label=nodes,vertex_frame_width=3)
-
它使用相当受限制的内表面而不是matplotlib。请注意,您需要自己定义图的大小。
-
它需要安装
idx = dict(zip(nodes,range(len(nodes)))) g_nodes = [idx[A] for A in nodes] g_edges = [(idx[A],idx[B]) for A,B in edges]
和igraph