gpt4 book ai didi

python - 如何在python中使用networkx绘制有向图?

转载 作者:IT老高 更新时间:2023-10-28 21:12:05 26 4
gpt4 key购买 nike

我有一些来 self 想要映射到图表的脚本的节点。在下面,我想使用箭头从 A 到 D,并且边缘可能也被着色(红色或其他东西)。

这基本上就像所有其他节点都存在时从 A 到 D 的路径。您可以将每个节点想象成城市,从 A 到 D 的旅行需要方向(带有箭头)。

下面的这段代码构建了图表

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

G = nx.Graph()
G.add_edges_from(
[('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])

val_map = {'A': 1.0,
'D': 0.5714285714285714,
'H': 0.0}

values = [val_map.get(node, 0.25) for node in G.nodes()]

nx.draw(G, cmap = plt.get_cmap('jet'), node_color = values)
plt.show()

但我想要图片中显示的内容。 enter image description here enter image description here

第一张图片的箭头和第二张图片上的红色边缘。

最佳答案

只有红色边缘的箭头的完整示例:

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
G.add_edges_from(
[('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])

val_map = {'A': 1.0,
'D': 0.5714285714285714,
'H': 0.0}

values = [val_map.get(node, 0.25) for node in G.nodes()]

# Specify the edges you want here
red_edges = [('A', 'C'), ('E', 'C')]
edge_colours = ['black' if not edge in red_edges else 'red'
for edge in G.edges()]
black_edges = [edge for edge in G.edges() if edge not in red_edges]

# Need to create a layout when doing
# separate calls to draw nodes and edges
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'),
node_color = values, node_size = 500)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)
nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)
plt.show()

Red edges

关于python - 如何在python中使用networkx绘制有向图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20133479/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com