简体   繁体   中英

Wrong colors for weighted edges in NetworkX

after dealing with the following issue for far too long, I decided to put a post in here.

I am trying to set up a networkx graph and color the edges according to some weight. Thing is, there seems to be a false assignment between edges and colors.

Here is a simple code snippet.

#! /usr/bin/python
# -*- coding: latin-1 -*-
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.colors as colors

# Set Up Data
G=nx.Graph()
G.add_node(0,pos=(0,0),label='0')
G.add_node(1,pos=(0,1),label='1')
G.add_node(2,pos=(1,0),label='2')
G.add_node(3,pos=(1,1),label='3')

G.add_edge(1,2, weight=3)
G.add_edge(0,2, weight=5)
G.add_edge(1,3, weight=2)
G.add_edge(2,3, weight=1)
G.add_edge(0,1, weight=4)

# Attributes
pos = nx.get_node_attributes(G,'pos')
weights = nx.get_edge_attributes(G,'weight')
labels = nx.get_node_attributes(G,'label')

# Plot Figure
fig = plt.figure()

# Nodes
nx.draw_networkx_nodes(G,pos)
nx.draw_networkx_labels(G,pos,labels)

# Edges
out = nx.draw_networkx_edges(G,pos,edge_color = weights.values(), edge_cmap = plt.cm.jet, vmin = 0.0, vmax = max(weights.values()))
nx.draw_networkx_edge_labels(G,pos,edge_labels=weights)
plt.axis('off')

# Set Up Colorbar
cbar = plt.colorbar(out)

# Show
plt.show()

From this I get quite a strange assignment from edges to colors. Can anybody explain that? Did I do something wrong?

Eventually, I found a workaround by sorting the colors.

# Store edges
sorted_edge = []
sorted_edge.append((1,2))
sorted_edge.append((0,2))
sorted_edge.append((1,3))
sorted_edge.append((2,3))
sorted_edge.append((0,1))

# Sort edges
sorted_edge = sorted(sorted_edge)

# Sort colors
new_colors = []
sorted_indices = [sorted_edge.index(edge) for edge in weights.keys()]
for index in sorted_indices:
    while len(new_colors) < index+1:
        new_colors.append(0)
    new_colors[index] = weights.values()[sorted_indices.index(index)]

Firstly, I would believe that this is not the intended solution to the issue?! Secondly, I am having a larger application of this small example where the assignment entirely fails, even with this sorting. Hence, I thought I'd better get a step back and try to understand what the issue is.

Appreciate your answers.

Best, Jonas

I tried your snippet and I can reproduce the issue. This works as it should:

edges, colors = zip(*nx.get_edge_attributes(G,'weight').items())
nx.draw(G, pos, edgelist=edges, edge_color=colors, width=10, edge_cmap = plt.cm.jet, vmin = 0.0, vmax = max(weights.values()))

My guess is that draw_edges does not keep the order of edges as defined by get_edge_attributes, but I am not sure ...

Before:

之前

After:

后

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM