繁体   English   中英

NetworkX中加权边缘的颜色错误

[英]Wrong colors for weighted edges in NetworkX

在处理以下问题的时间过长之后,我决定在此处发布一个帖子。

我正在尝试设置networkx图并根据一些权重为边缘着色。 事实是,边缘和颜色之间似乎存在错误的分配。

这是一个简单的代码片段。

#! /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()

由此我得到了从边缘到颜色的相当奇怪的分配。 有人可以解释吗? 我做错什么了吗?

最终,我通过对颜色进行排序找到了一种解决方法。

# 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)]

首先,我认为这不是该问题的预期解决方案吗? 其次,我在这个小例子中有一个更大的应用,即使进行这种排序,分配也会完全失败。 因此,我认为我最好退后一步,尝试了解问题所在。

感谢您的回答。

最好,乔纳斯

我尝试了您的代码段,并且可以重现该问题。 这可以正常工作:

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

我的猜测是draw_edges不能保持get_edge_attributes定义的边缘顺序,但是我不确定...

之前:

之前

后:

后

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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