Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating curved edges with NetworkX in Python3

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()

and gives the following result

enter image description here

How do I make sure that the edges are "rounded" so that they don't overlap?

like image 508
g3n35i5 Avatar asked Oct 01 '18 09:10

g3n35i5


1 Answers

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
)

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

Note: the code won't produce this figure with all the colors and arrows, a little more code is necessary for that.

like image 54
Ulf Aslak Avatar answered Sep 28 '22 07:09

Ulf Aslak