繁体   English   中英

使用 Networkx 的图中边缘上的箭头

[英]Arrows on edges in a graph using Networkx

我有一个带有节点和边的图。 代码使用数组Weights为数组Edges着色,如当前输出所示。 是否可以在Edges中的数组元素上放置箭头,如预期输出中所示? 我想要根据Edges在特定边缘上的箭头,而不是全部。

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable

N = 1

def pos():
    x, y = 1, N + 3 - 1
    for _ in range(2 * N * (N + 1)):
        yield (x, y)
        y -= (x + 2) // (N + 3)
        x = (x + 2) % (N + 3)

G = nx.Graph()
it_pos = pos()
for u in range(2 * N * (N + 1)):
    G.add_node(u + 1, pos=next(it_pos))
    if u % (2 * N + 1) < N:
        for v in (u - 2 * N - 1, u - N - 1, u - N):
            if G.has_node(v + 1):
                G.add_edge(u + 1, v + 1)
    elif u % (2 * N + 1) == N:
        G.add_edge(u + 1, u - N + 1)
    elif u % (2 * N + 1) < 2 * N:
        for v in (u - 1, u - N - 1, u - N):
            G.add_edge(u + 1, v + 1)
    else:
        for v in (u - 1, u - N - 1):
            G.add_edge(u + 1, v + 1)


nx.draw(G, nx.get_node_attributes(G, 'pos'), with_labels=True, font_weight='bold')
Edges=np.array([[1,2],[1,3],[1,4]])
Weights=np.array([[1.7],[2.9],[8.6]])
flat_weights = Weights.flatten()
weights_normalized = [x / max(flat_weights) for x in flat_weights]
edge_weight_map = dict(zip([tuple(e) for e in Edges.tolist()],weights_normalized))
my_cmap = plt.cm.get_cmap('Oranges')
colors = my_cmap([edge_weight_map.get(tuple(e), 0) for e in Edges.tolist()])
pos = nx.get_node_attributes(G, 'pos')
sm = ScalarMappable(cmap=my_cmap, norm=plt.Normalize(0,max(flat_weights)))
nx.draw_networkx_edges(G, pos, edge_color=colors, 
                       edgelist=[tuple(e) for e in Edges.tolist()],
                       width=5);

plt.colorbar(sm)

当前输出为

在此处输入图像描述

预期的输出是

在此处输入图像描述

你快到了。

首先,您需要创建有向图而不是无向图:

G = nx.DiGraph()

其次,有向图对象默认使用箭头绘制,因此您需要在调用DiGraph nx.draw(...)时指定arrows=False

nx.draw(G, nx.get_node_attributes(G, 'pos'), with_labels=True, font_weight='bold', arrows=False)

如果您现在单独绘制所选边缘,它们会带有箭头(默认情况下)。

在此处输入图像描述

所以你想要一个有向图:

G = nx.DiGraph()

https://networkx.org/documentation/stable/reference/classes/digraph.html

暂无
暂无

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

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