在 Python3 中使用 NetworkX 创建曲线边缘 [英] Creating curved edges with NetworkX in Python3

查看:36
本文介绍了在 Python3 中使用 NetworkX 创建曲线边缘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用networkx(如果你知道更好的框架,我也想采用另一个框架)来创建一个节点位于固定位置的graps.同时图的边不应该重叠.

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.

我之前的代码是这样的:

My previous code looks like this:

#!/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 新闻中,您现在可以为 nx.draw_networkx_edges 指定一个 connectionstyle 参数.例如,如果我想要一个边缘弯曲的网络,我可以这样写:

In other NetworkX news, YOU CAN NOW specify a connectionstyle parameter to nx.draw_networkx_edges. For example, if I want a network with curved edges I can write:

# 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.

The make the edges more curvy, simply increase the x of "rad=x".

注意:代码不会生成带有所有颜色和箭头的图形,为此需要多一些代码.

这篇关于在 Python3 中使用 NetworkX 创建曲线边缘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆