Search code examples
pythonpython-3.xnetworkx

Networkx graph with different nodes from three lists


i want to describe you my problem...

I tried to optimize routes with gurobipy and I got active arcs like this:

active_arcs=[(0, 2),(0, 4),(0, 11),(1, 24),(2, 7),(3, 1),(4, 5),(5, 3),(6, 0),(7, 6),
(8, 14),(9,6),(10, 0),(11, 13),(12, 9),(13, 12),(14, 15),(15, 16),(16, 17),(17, 18),
(18, 0),(19, 23),(20, 19),(21, 20),(22, 10),(23, 22),(24, 8),(26, 21)]

and two lists with indices of addresses:

locations= [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]

gas_stations = [24,25,26,27]

now I want to plot a networkx graph...

For every index in active_arcs and in locations I want a blue node with the index.

For every index in active_arcs and in gas stations I want a green node with the index "C" for Charge instead of the index.

In this Example the indices 24 and 26 should be green and "C"

enter image description here

I tried it like that but I have no idea how to solve it...

import networkx
G = networkx.Graph(active_arcs)
labels = dict(zip(G.nodes(), G.nodes()))
networkx.draw_networkx(G,labels=labels, width=1,
                                   node_size=200, font_size=13,
                                   pos=networkx.spring_layout(G))

Solution

  • Change the values of you labels dict in order to adapt the labels and create a list of color in the order of the nodes of you graph:

    import networkx
    
    active_arcs=[(0, 2),(0, 4),(0, 11),(1, 24),(2, 7),(3, 1),(4, 5),(5, 3),(6, 0),(7, 6),
    (8, 14),(9,6),(10, 0),(11, 13),(12, 9),(13, 12),(14, 15),(15, 16),(16, 17),(17, 18),
    (18, 0),(19, 23),(20, 19),(21, 20),(22, 10),(23, 22),(24, 8),(26, 21)]
    
    locations= [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]
    
    gas_stations = [24,25,26,27]
    
    
    G = networkx.Graph(active_arcs)
    
    labels = dict(zip(G.nodes(), G.nodes()))
    for l in labels.keys():
        if l in gas_stations:
            labels[l] = 'C'
            
    colors = []
    for n in G.nodes:
        if n in gas_stations:
            colors.append('green')
        else:
            colors.append('blue')
            
    
    
    networkx.draw_networkx(G,labels=labels, node_color = colors, width=1,
                                       node_size=200, font_size=13,
                                       pos=networkx.spring_layout(G))