Home > Software design >  How to select a list of edges to draw in networkx.draw
How to select a list of edges to draw in networkx.draw

Time:01-17

I have a networkx graph with many edges and for this reason I want to select a subset that I want to draw. But there is strange behaviour.

import networkx as nx
G = nx.Graph()
G.add_edge(0,1,color=.1,weight=2)
G.add_edge(1,2,color=.4,weight=4)
G.add_edge(2,3,color=1.4,weight=6)
G.add_edge(3,4,color=2.4,weight=3)
G.add_edge(4,0,color=5.7,weight=1)

colors = nx.get_edge_attributes(G,'color').values()
weights = nx.get_edge_attributes(G,'weight').values()

pos = nx.circular_layout(G)

# This works:
nx.draw(G, pos, 
        edge_color=colors, 
        width=list(weights),
        with_labels=True,
        node_color='lightgreen',
       )
# This works too:
nx.draw(G, pos, 
        edge_color=colors, 
        width=list(weights),
        with_labels=True,
        node_color='lightgreen',
        edgelist=[(0,1),(1,2),(2,3),(3,4),(4,0)],
       )

This is the result. (I will add a colorbar later, so the colors can be interpreted).

Image that is drawn

# This however gives an error:
# ValueError: Invalid RGBA argument: 0.1
nx.draw(G, pos, 
        edge_color=colors, 
        width=list(weights),
        with_labels=True,
        node_color='lightgreen',
        edgelist=[(0,1),(1,2),(2,3),],
       )

Is there a way to prevent this error? It seems to me that this is bug. But maybe there is something that I miss.

CodePudding user response:

I found the error: You also have to edit the color-key-word-argument:

edgelist=[(0,1),(1,2),(2,3),]
nx.draw(G, pos, 
        edge_color=[G.edges[e]['color'] for e in edgelist], 
        width=list(weights),
        with_labels=True,
        node_color='lightgreen',
        edgelist=edgelist,
       )

But I still think that the error that I got was not helpful...

CodePudding user response:

You set colors = nx.get_edge_attributes(G,'color').values()

This gives dict_values([0.1, 5.7, 0.4, 1.4, 2.4])

draw is trying to match 5 values to only 3 edges

So like you said, you have to resize the colors dict

  •  Tags:  
  • Related