使用plotly在Networkx跟踪中添加边着色的选项

2024-05-13 22:04:56 发布

您现在位置:Python中文网/ 问答频道 /正文

在plotly网站给出的示例中: https://plotly.com/python/network-graphs/

有没有办法为每个单独的边添加边着色(例如从十六进制值列表中)

就像为节点提供的一样


Tags: httpscom示例列表节点网站networkplotly
2条回答

以下是不同颜色边的示例:

import matplotlib.pyplot as plt
import networkx as nx

G = nx.cubical_graph()
pos = nx.spring_layout(G) 

nx.draw_networkx_nodes(G, pos, nodelist=[0, 1, 2, 3], node_color='y')
nx.draw_networkx_nodes(G, pos, nodelist=[4, 5, 6, 7], node_color='g')

nx.draw_networkx_edges(G, pos, edgelist=[(0, 1), (1, 2), (2, 3), (3, 0)], edge_color='y')
nx.draw_networkx_edges(G, pos, edgelist=[(4, 6), (6, 5), (5, 7), (7, 4)], edge_color='g')

nx.draw_networkx_labels(G, pos)

plt.show()

输出:

Image

有关更多信息,请参阅documentation

您可以分离将成为不同颜色的边并分别打印它们。当为每组边调用go.Scatter时,只需设置所需的颜色:

colors = ['#ff0000', '#0000ff']
edge_traces = []
for edge_set, c in zip(edge_sets, colors):
    edge_x = []
    edge_y = []
    for edge in edge_set:
        x0, y0 = G.nodes[edge[0]]['pos']
        x1, y1 = G.nodes[edge[1]]['pos']
        edge_x.append(x0)
        edge_x.append(x1)
        edge_x.append(None)
        edge_y.append(y0)
        edge_y.append(y1)
        edge_y.append(None)
    
    edge_traces.append(go.Scatter(
        x=edge_x, y=edge_y,
        line=dict(width=0.5, color=c),
        hoverinfo='none',
        mode='lines'))

只要确保在创建图形时添加新的散点图即可

fig = go.Figure(data=edge_traces + [node_trace],
    ...

enter image description here

相关问题 更多 >