在Python3中使用NetworkX创建弯曲的边缘 [英] Creating curved edges with NetworkX in Python3
本文介绍了在Python3中使用NetworkX创建弯曲的边缘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用networkx(如果您知道更好的框架,我也想采用其他框架)来创建一个 节点位于固定位置的抓图.同时,图形的边缘不应重叠.
I would like to use networkx (i would also like to take another framework if you know a better one) to create a graps whose nodes are at fixed positions. At the same time the edges of the graph should not overlap.
我以前的代码如下:
#!/usr/bin/env python3
import networkx as nx
import matplotlib.pyplot as plt
# Graph data
names = ['A', 'B', 'C', 'D', 'E']
positions = [(0, 0), (0, 1), (1, 0), (0.5, 0.5), (1, 1)]
edges = [('A', 'B'), ('A', 'C'), ('A', 'D'), ('A', 'E'), ('D', 'A')]
# Matplotlib figure
plt.figure('My graph problem')
# Create graph
G = nx.MultiDiGraph(format='png', directed=True)
for index, name in enumerate(names):
G.add_node(name, pos=positions[index])
labels = {}
for edge in edges:
G.add_edge(edge[0], edge[1])
labels[(edge[0], edge[1])] = '{} -> {}'.format(edge[0], edge[1])
layout = dict((n, G.node[n]["pos"]) for n in G.nodes())
nx.draw(G, pos=layout, with_labels=True, node_size=300)
nx.draw_networkx_edge_labels(G, layout, edge_labels=labels)
plt.show()
并给出以下结果
如何确保边缘是圆角的",以免边缘重叠?
How do I make sure that the edges are "rounded" so that they don't overlap?
推荐答案
我认为您不能直接使用networkx函数执行此操作.但是,您可以使用已计算的节点位置直接使用matplotlib.
I don't think you can do this directly with networkx functions. But you can use matplotlib directly using the node positions you have calculated.
修改您的代码:
import networkx as nx
import matplotlib.pyplot as plt
# Graph data
names = ['A', 'B', 'C', 'D', 'E']
positions = [(0, 0), (0, 1), (1, 0), (0.5, 0.5), (1, 1)]
edges = [('A', 'B'), ('A', 'C'), ('A', 'D'), ('A', 'E'), ('D', 'A')]
# Matplotlib figure
plt.figure('My graph problem')
# Create graph
G = nx.MultiDiGraph(format='png', directed=True)
for index, name in enumerate(names):
G.add_node(name, pos=positions[index])
labels = {}
layout = dict((n, G.node[n]["pos"]) for n in G.nodes())
nx.draw(G, pos=layout, with_labels=True, node_size=300)
ax = plt.gca()
for edge in edges:
ax.annotate("",
xy=layout[edge[0]], xycoords='data',
xytext=layout[edge[1]], textcoords='data',
arrowprops=dict(arrowstyle="->", color="0.5",
shrinkA=5, shrinkB=5,
patchA=None, patchB=None,
connectionstyle="arc3,rad=-0.3",
),
)
plt.show()
赠予:
另请参见此.
这篇关于在Python3中使用NetworkX创建弯曲的边缘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文