Search code examples
pythonmatplotlibplotlynetworkxtrace

Option to add edge colouring in Networkx trace using plotly


In the example given in the plotly website: https://plotly.com/python/network-graphs/

Is there any way to add edge colouring (from a list of hex values for example) for each individual edge?

Just like it is given for the nodes


Solution

  • You can separate the edges that are going to be different colors and plot them separately. When you call go.Scatter for each set of edges, just set the color that you want:

    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'))
    

    Just make sure you add the new scatter plots when you create the figure

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

    enter image description here