簡體   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