Networkx:如何更改相同边缘的颜色和大小?

时间:2019-04-04 11:24:04

标签: python networkx

我使用networkx

生成了一个图形
import networkx as nx
G = nx.grid_graph(dim=[5,5])
nx.draw(G);

enter image description here

然后我使用astar算法计算两个节点之间的最小路径

def dist(a, b):
    (x1, y1) = a
    (x2, y2) = b
    return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
nodes = list(G.nodes)
tmp = nx.astar_path(G,nodes[3],nodes[14],dist)

现在,我想修改节点之间路径的边缘的颜色和大小,其中节点由tmp定义

tmp
[(0, 3), (1, 3), (2, 3), (2, 4)]

1 个答案:

答案 0 :(得分:0)

您需要使用其自己的命令绘制网络的每个组件。这是一个工作代码,演示了如何实现这种绘图。

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

# only relevant part is treated here
G = nx.grid_graph(dim=[5,5])

node_list = [(0, 3), (1, 3), (2, 3), (2, 4)]
edge_list = [[(0, 3), (1, 3)], [(1, 3), (2, 3)], [(2, 3), (2, 4)]]

pos = nx.spring_layout(G)
nx.draw(G, pos=pos, with_labels=True)
# draw selected nodes in green with triangle shape
nx.draw_networkx_nodes(G, pos=pos, nodelist=node_list, node_size=300, node_color='g', node_shape='^')
# draw selected edges in blue with solid line
nx.draw_networkx_edges(G, pos=pos, edgelist=edge_list, width=3.0, edge_color='blue', style='solid')

输出图:

enter image description here