Networkx: plot quality issue - python

Below are two plotted network graph using two methods. The lines and circles in the first graph looks better and smoother than the second one. But I cannot really tell the reason why the second one does not look the same as the first one in terms of the image quality.
locations = {
0:(4,4),
1:(2,0),
2:(8,0),
3:(0,1),
4:(1,1),
5:(5,2),
6:(7,2),
7:(3,3),
8:(6,3),
}
edges = [
(0, 8, {'vehicle': '0'}),
(8, 6, {'vehicle': '0'}),
(6, 2, {'vehicle': '0'}),
(2, 5, {'vehicle': '0'}),
(5, 0, {'vehicle': '0'}),
(0, 7, {'vehicle': '1'}),
(7, 1, {'vehicle': '1'}),
(1, 4, {'vehicle': '1'}),
(4, 3, {'vehicle': '1'}),
(3, 0, {'vehicle': '1'}),
]
G=nx.DiGraph()
G.add_edges_from(edges)
plt.figure(figsize=(15,10))
plt.show()
#vehicle 0
temp = [e for e in edges if e[2]['vehicle'] == '0'] #temporary list that filters the path of vehicle 0
nx.draw_networkx_nodes(G, locations, nodelist=[x[0] for x in temp], node_color='b')
nx.draw_networkx_edges(G, locations, edgelist=temp,
width=2, edge_color='b', style='dashed')
#vehicle 1
temp = [e for e in edges if e[2]['vehicle'] == '1']
nx.draw_networkx_nodes(G, locations, nodelist=[x[0] for x in temp], node_color='r')
nx.draw_networkx_edges(G, locations, edgelist=temp,
width=2, edge_color='r', style='dashed')
#let's color the node 0 in black
nx.draw_networkx_nodes(G, locations, nodelist=[0], node_color='k')
# labels
nx.draw_networkx_labels(G, locations, font_color='w', font_size=12, font_family='sans-serif')
#print out the graph
plt.axis('on')
plt.show()
The second graph and codes:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
locations = \
[(4, 4), # depot
(2, 0), (8, 0), # row 0
(0, 1), (1, 1),
(5, 2), (7, 2),
(3, 3), (6, 3),
(5, 5), (8, 5),
(1, 6), (2, 6),
(3, 7), (6, 7),
(0, 8), (7, 8)]
v0 = [0, 1, 4, 3, 15, 0]
v1 = [0, 14, 16, 10, 2, 0]
vehicles = [v0, v1]
cl = ["r", "b","green","yellow"]
x=0
for v in vehicles:
n=0
e=[]
node=[]
for i in v:
G.add_node(i, pos=(locations[i][0], locations[i][1]))
# a= [locations[i][0], locations[i][1]]
# print(a)
if n > 0:
# print(n)
# print(v[n])
# print (v[n-1])
u= (v[n-1], v[n])
e.append(u)
node.append(i)
print(e)
print(node)
G.add_edge(v[n-1], v[n])
nx.draw(G, nx.get_node_attributes(G, 'pos'), nodelist=node, edgelist=e, with_labels=True, node_color=cl[x], width=2, edge_color=cl[x], \
style='dashed', font_color='w', font_size=12, font_family='sans-serif')
# print(x)
n += 1
x+=1
#let's color the node 0 in black
nx.draw_networkx_nodes(G, locations, nodelist=[0], node_color='k')
plt.axis('on')
plt.show()
when zoomed out (might be not very clear to see here), the lines and circles in the second graph are not as smooth as the first graph. what's the reason of this problem?

You are drawing the same nodes and edges more than once. Call the draw function outside of the node loop:
for v in vehicles:
n=0
e=[]
node=[]
for i in v:
G.add_node(i, pos=(locations[i][0], locations[i][1]))
# a= [locations[i][0], locations[i][1]]
# print(a)
if n > 0:
# print(n)
# print(v[n])
# print (v[n-1])
u= (v[n-1], v[n])
e.append(u)
node.append(i)
print(e)
print(node)
G.add_edge(v[n-1], v[n])
# print(x)
n += 1
nx.draw(G, nx.get_node_attributes(G, 'pos'), nodelist=node, edgelist=e, with_labels=True, node_color=cl[x], width=2, edge_color=cl[x], \
style='dashed', font_color='w', font_size=12, font_family='sans-serif')
x+=1
Which results in this image:

Your code doesn't show how plt is initialized in the first code snipped. These differences tend to come from the backend used by matplotlib. You may want to take a look at this documentation: https://matplotlib.org/faq/usage_faq.html#what-is-a-backend

Related

Fill color in single cells in a networkx graph

I've build a graph with networkx, that looks like this: Graph
I want to fill every singel cell with a specified color. The Graph was drawn by nx.draw_networkx_edges() (returns a LineCollection). I found a similar question here (Fill area between lines), but the solution in the comments, doesn't worked for me.
I've also used plt.fill_between with a simpler graph and manually set the values:
plt.fill_between([1, 2], [2, 2], color='yellow')
plt.fill_between([1.75, 2, 3], [1.25, 2, 2], color='purple')
plt.fill_between([0, 1, 1.25], [2, 2, 1.25], color='red')
plt.fill_between([0.75, 1.25, 1.75, 2.25], [0.75, 1.25, 1.25, 0.75], color='blue')
plt.fill_between([2, 2.25, 3], [0, 0.75, 1], color='pink')
plt.fill_between([0, 0.75, 1], [1, 0.75, 0], color='green')
And it turns out pretty good (result), but the problem with that is, that the filling depends on the order when the cells get filled and that would make the algorithm for it way to complicated, I guess.
Does anyone knows a better and simpler solution?
Edit:
I tried to convert the Graph into a Voronoi-Diagram to try the solution of #JohanC, but the runtime is pretty long and the solution for larger graphs isn't exact. For the calculation of the centroids I used this Center of Polygon
def find_Centroid(v):
sum_A = 0
sum_x = 0
sum_y = 0
for i in range(len(v)):
next = i+1 if i != len(v)-1 else 0
sum_A += v[i][0]*v[next][1] - v[next][0]*v[i][1]
sum_x += (v[i][0] + v[next][0]) * (v[i][0]*v[next][1] - v[next][0]*v[i][1])
sum_y += (v[i][1] + v[next][1]) * (v[i][0]*v[next][1] - v[next][0]*v[i][1])
A = 1/2 * sum_A
Cx = 1/(6*A) * sum_x
Cy = 1/(6*A) * sum_y
return Cx, Cy
# Get all cells of Graph (I think that takes most of the time)
cycle = nx.minimum_cycle_basis(SVG)
centroids = list()
# calculate all centroids of the cells
for c in cycle:
subG = SVG.subgraph(c)
sortedCycle = sortGraphNodes(subG)
centroid = find_Centroid(sortedCycle)
SVG.add_node((centroid[0], centroid[1]))
centroids.append(centroid)
vor = Voronoi(centroids)
voronoi_plot_2d(vor)
plt.show()
Result small graph
Result large graph
Using the first code block from the question that shows filling the simpler graph, I constructed an example network.
The edges are listed below:
edges = [((1, 2), (2, 2)),
((1, 2), (0, 2)),
((1, 2), (1.25, 1.25)),
((2, 2), (1.75, 1.25)),
((2, 2), (3, 2)),
((1.75, 1.25), (1.25, 1.25)),
((1.75, 1.25), (2.25, 0.75)),
((3, 2), (3, 1)),
((0, 2), (0, 1)),
((1.25, 1.25), (0.75, 0.75)),
((0.75, 0.75), (0, 1)),
((0.75, 0.75), (1, 0)),
((2.25, 0.75), (2, 0)),
((2.25, 0.75), (3, 1)),
((2, 0), (1, 0)),
((2, 0), (3, 0)),
((3, 1), (3, 0)),
((0, 1), (0, 0)),
((1, 0), (0, 0))]
With this network, we do not need to use any Voronoi
diagram (although very pleasing to they eye) to fill
the cells of the network.
The basis for the solution is to use the minimum cycle
basis iterator for the network, and then correct each
cycle for following actual edges in the network (see
documentation for minimum cycle basis
"nodes are not necessarily returned in a order by
which they appear in the cycle").
The solution becomes the following, assuming edges
from above:
import matplotlib.pyplot as plt
import networkx as nx
G = nx.Graph()
for edge in edges:
G.add_edge(edge[0], edge[1])
pos = {x: x for x in G.nodes}
options = {
"node_size": 10,
"node_color": "lime",
"edgecolors": "black",
"linewidths": 1,
"width": 1,
"with_labels": False,
}
nx.draw_networkx(G, pos, **options)
# Fill all cells of graph
for cycle in nx.minimum_cycle_basis(G):
full_cycle = cycle.copy()
cycle_path = [full_cycle.pop(0)]
while len(cycle_path) < len(cycle):
for nb in G.neighbors(cycle_path[-1]):
if nb in full_cycle:
idx = full_cycle.index(nb)
cycle_path.append(full_cycle.pop(idx))
break
plt.fill(*zip(*cycle_path))
plt.show()
The resulting graph looks like this:
This algorithm scales better than the Voronoi / centroid
approach listed in the edit to the question, but suffers
from the same inefficiencies for large networks (O(m^2n),
according to the reference in the
documentation for minimum cycle basis).

How to get position of edge weights in a networkx graph?

Currently there is a function in networkx library for getting positions of all nodes: spring_layout. Quoting from the docs, it returns:
dict :
A dictionary of positions keyed by node
And can be used as:
G=nx.path_graph(4)
pos = nx.spring_layout(G)
I would like something similar to access the position of an edge-weight for a weighted graph. It should return the position of where the number for edge-weight would be placed, preferably at the center of the edge and just above the edge. (By above, I mean "outside" the graph, so for a horizontally-placed square graph's bottom-most edge, it would be just below the edge).
So the question is, is there anything in-built similar to spring_layout for achieving this? And if not, how to go about it yourself?
You can use nx.draw_edge_labels which returns a dictionary with edges as keys and (x, y, label) as values
import matplotlib.pyplot as plt
import networkx as nx
# Create a graph
G = nx.path_graph(10)
# Add 2 egdes with labels
G.add_edge(0, 8, name='n1')
G.add_edge(2, 7, name='n2')
# Get the layout
pos = nx.spring_layout(G)
# Draw the graph
nx.draw(G, pos=pos)
# Draw the edge labels
edge_labels = nx.draw_networkx_edge_labels(G, pos)
.
Now you can see the variables edge_labels
print(edge_labels)
# {(0, 1): Text(0.436919941201627, -0.2110471432994752, '{}'),
# (0, 8): Text(0.56941037628304, 0.08059107891826373, "{'name': 'n1'}"),
# (1, 2): Text(0.12712625526483384, -0.2901338796021985, '{}'),
# (2, 3): Text(-0.28017240645783603, -0.2947104829441387, '{}'),
# (2, 7): Text(0.007024254096114596, -0.029867791669433513, "{'name': 'n2'}"),
# (3, 4): Text(-0.6680363649371021, -0.26708812849092933, '{}'),
# (4, 5): Text(-0.8016944207643129, -0.0029986274715349814, '{}'),
# (5, 6): Text(-0.5673817462107436, 0.23808073918504968, '{}'),
# (6, 7): Text(-0.1465270298295821, 0.23883392944036055, '{}'),
# (7, 8): Text(0.33035539545007536, 0.2070939421162053, '{}'),
# (8, 9): Text(0.7914739158501038, 0.2699223242747882, '{}')}
Now to get the position of say, edge (2,7), you just need to do
print(edge_labels[(2,7)].get_position())
# Output: (0.007024254096114596, -0.029867791669433513)
You can read more about the documentation here.
If you want to extract the x,y coordinates of all the edges, you can try this:
edge_label_pos = { k: v.get_position()
for k, v in edge_labels.items()}
#{(0, 1): (0.436919941201627, -0.2110471432994752),
# (0, 8): (0.56941037628304, 0.08059107891826373),
# (1, 2): (0.12712625526483384, -0.2901338796021985),
# (2, 3): (-0.28017240645783603, -0.2947104829441387),
# (2, 7): (0.007024254096114596, -0.029867791669433513),
# (3, 4): (-0.6680363649371021, -0.26708812849092933),
# (4, 5): (-0.8016944207643129, -0.0029986274715349814),
# (5, 6): (-0.5673817462107436, 0.23808073918504968),
# (6, 7): (-0.1465270298295821, 0.23883392944036055),
# (7, 8): (0.33035539545007536, 0.2070939421162053),
# (8, 9): (0.7914739158501038, 0.2699223242747882)}

Generate Complete DFS Paths using networkx

I am trying to generate complete path list instead of the optimized one. Better explained using the below example.
import networkx as nx
G = nx.Graph()
G.add_edges_from([(0, 1), (1, 2), (2, 3)])
G.add_edges_from([(0, 1), (1, 2), (2, 4)])
G.add_edges_from([(0, 5), (5, 6)])
The above code create a Graph with edges 0=>1=>2=>3 and 0=>1=>2=>4 and 0=>5=>6
All I want is to extract all paths from 0.
I tried:
>> list(nx.dfs_edges(G, 0))
[(0, 1), (1, 2), (2, 3), (2, 4), (0, 5), (5, 6)]
All I want is:
[(0, 1, 2, 3), (0, 1, 2, 4), (0, 5, 6)]
Is there any pre-existing method from networkx which can be used? If not, any way to write an optimal method that can do the job?
Note: My problem is limited to the given example. No more corner cases possible.
Note2: For simplification the data is generated. In my case, the edges list is coming from data set. Assumption is given a graph and a node (Say 0), Can we generate all paths?
Give this a try:
import networkx as nx
G = nx.Graph()
G.add_edges_from([(0, 1), (1, 2), (2, 3)])
G.add_edges_from([(0, 1), (1, 2), (2, 4)])
G.add_edges_from([(0, 5), (5, 6)])
pathes = []
path = [0]
for edge in nx.dfs_edges(G, 0):
if edge[0] == path[-1]:
# node of path
path.append(edge[1])
else:
# new path
pathes.append(path)
search_index = 2
while search_index <= len(path):
if edge[0] == path[-search_index]:
path = path[:-search_index + 1] + [edge[1]]
break
search_index += 1
else:
raise Exception("Wrong path structure?", path, edge)
# append last path
pathes.append(path)
print(pathes)
# [[0, 1, 2, 3], [0, 1, 2, 4], [0, 5, 6]]

Counting edges between nodes in networkx

I have a graph where my nodes can have multiple edges between them in both directions and I want to set the width between the nodes based on the sum of all edges between them.
import networkx as nx
nodes = [0,1]
edges = [(0,1),(1,0)]
G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
weights = [2,3]
nx.draw(G, width = weights)
I would like to have the width between 0 and 1 set to 5 as that is the summed weight.
First you need to create a MultiDiGraph and add all possible edges to it. This is because it supports multiple directed egdes between the same set of nodes including self-loops.
import networkx as nx
nodes = [0, 1, 2, 3, 4, 5]
edges = [(0,1), (1,0), (1, 0),(0, 1), (2, 3), (2, 3), (2, 3), (2, 3),
(4, 1), (4, 1), (4, 1), (4, 1), (4, 1), (4, 1), (4, 5), (5, 0)]
G = nx.MultiDiGraph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
Next, create a dictionary containing counts of each edges
from collections import Counter
width_dict = Counter(G.edges())
edge_width = [ (u, v, {'width': value})
for ((u, v), value) in width_dict.items()]
Now create a new DiGraph from the edge_width dictionary created above
G_new = nx.DiGraph()
G_new.add_edges_from(edge_width)
Plotting using thickened edges
This is an extension of answer mentioned here.
edges = G_new.edges()
weights = [G_new[u][v]['width'] for u,v in edges]
nx.draw(G_new, edges=edges, width=weights)
Add Edge labels
See this answer for more info.
pos = nx.spring_layout(G_new)
nx.draw(G_new, pos)
edge_labels=dict([((u,v,),d['width'])
for u,v,d in G_new.edges(data=True)])
nx.draw_networkx_edges(G_new, pos=pos)
nx.draw_networkx_edge_labels(G_new, pos, edge_labels=edge_labels,
label_pos=0.25, font_size=10)
You can also view this Google Colab Notebook with working code.
References
https://stackoverflow.com/a/25651827/8160718
https://stackoverflow.com/a/22862610/8160718
Drawing networkX edges
MultiDiGraph in NetworkX
Count occurrences of List items

How to stop Networkx from changing the order of head and tail nodes(u,v) to (v,u) in an edge?

I've got a simple graph created using networkx.
import networkx as nx
import matplotlib.pyplot as plt
from pprint import pprint
G = nx.Graph()
head_nodes = range(0, 9)
tail_nodes = range(1, 10)
edge_ls = list(zip(head_nodes, tail_nodes))
G.add_nodes_from(range(0, 10))
G.add_edges_from(edge_ls)
pprint(G.nodes())
nx.draw(G)
plt.show()
I want to remove the edge between node 0 and 1 and add three new nodes (say node 10,11,12). Then, edges have
to be created between node 0 and 10, 10 and 11, 11 and 2.
I'm using G.remove_edge(0,1) to remove the edge between node 0 and 1.
Could someone suggest which function can be used to add n new nodes?
Also, if n new nodes are added, will these nodes be numbered automatically?
I intend to do this in a loop, delete an edge that already exists between two nodes and add n new nodes and edges connecting these nodes.
EDIT:
I tried the following to add n new edges
G = nx.Graph()
head_nodes = range(0, 9)
tail_nodes = range(1, 10)
edge_ls = list(zip(head_nodes, tail_nodes))
G.add_nodes_from(range(0, 10))
G.add_edges_from(edge_ls)
head = 0
tail = 1
G.remove_edge(head, tail)
Nnodes = G.number_of_nodes()
newnodes = [head, Nnodes+1, Nnodes+2, Nnodes+3, tail] # head and tail already exists
newedges = [(x, y) for x, y in zip(newnodes[0:len(newnodes)-1], newnodes[1:len(newnodes)])]
G.add_edges_from(newedges)
pprint(G.edges())
Output:
EdgeView([(0, 11), (1, 2), (1, 13), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (11, 12), (12, 13)])
Expected Output:
EdgeView([(0, 11), (1, 2), (13, 1), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (11, 12), (12, 13)])
I'm not sure why the edge that was added in the order (13,1)(head, tail) is stored as (1,13). Any suggestion on how to preserve the order of head and tail node while adding a new edge?
EDIT2:
replacing nx.Graph() with nx.OrderedGraph() also doesn't help.
A Graph is an undirected graph, where (1, 13) and (13, 1) mean the same thing, the edges have no 'arrows'.
What you want is a DiGraph, meaning a directed graph. See https://networkx.github.io/documentation/stable/reference/classes/index.html
An OrderedGraph is something else - it just means that when you iterate over nodes and edges, they come out in a particular order (similar to lists vs sets).

Categories

Resources