我想使用networkx (如果你知道更好的框架,我也想采用另一个框架)来创建一个节点位于固定位置的graps。同时,图形的边不应该重叠。
我之前的代码如下所示:
#!/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()
并给出了以下结果
我如何确保边缘是“圆角”的,这样它们就不会重叠?
发布于 2020-12-09 16:32:21
在其他NetworkX新闻中,您现在可以将connectionstyle
参数指定为nx.draw_networkx_edges
。例如,如果我想要一个具有弯曲边缘的网络,我可以这样写:
# Compute position of nodes
pos = nx.kamada_kawai_layout(G)
# Draw nodes and edges
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_edges(
G, pos,
connectionstyle="arc3,rad=0.1" # <-- THIS IS IT
)
这使得边缘更加弯曲,只需增加"rad=x“的x。
注意:代码不会生成包含所有颜色和箭头的图形,需要更多代码。
发布于 2020-03-11 21:18:48
我不认为你可以用networkx函数直接做到这一点。但是您可以使用计算出的节点位置直接使用matplotlib。
调整你的代码:
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()
提供:
另请参见this。
发布于 2019-04-10 09:11:41
正如Paul提到的,现在可以选择在draw_networkx_edges
中使用FancyArrowPatch
,尽管它只适用于有向图,而且速度也非常慢。
无论如何,我打包了一些旧代码,这些代码使用bezier
包从NetworkX图(或者实际上是任何边列表)中生成漂亮的曲线边,并绘制它们。它可能很有用:https://github.com/beyondbeneath/bezier-curved-edges-networkx
使用SNAP Facebook数据集和ForceAtlas2布局的示例图像:
https://stackoverflow.com/questions/52588453
复制相似问题