Search code examples
pythongraphnetworkxedges

networkx edge color is always black, color attribute is ignored


I have some analysis rules i want to represent, and i want the edges that come in and out of certain nodes to have the same colour. I approached it with different ways but none of them worked. For example:

G = nx.DiGraph()
color_map = []
color_iter = 0
edge_colors_iter = ["#4e79a9", "#59a14f", "#9c755f", "#f28e2b", "#edc948", "#bab0ac", "#e15759", "#b07aa1",
                    "#76b7b2", "#ff9da7"]

for index, row in rules.iterrows():

    edges_to_add = []
    color_of_rule = edge_colors_iter[color_iter]


    #left_side_items and right_side_items are essentially lists for in and out edges 
    #of the certain node i need with the same color
    # ...

    for item in left_side_items:
        edges_to_add.append((str(item), "R"+str(rule_id)))

    for item in right_side_items:
        edges_to_add.append(("R"+str(rule_id), str(item)))

    G.add_edges_from(edges_to_add, color=color_of_rule)

    color_iter += 1

for node in G:

    if str(node).startswith("R"):
        color_map.append('#f9dc4c')

    else:
        color_map.append('#339e34')

nx.draw_circular(G, node_color=color_map, with_labels=True)
plt.show()

I get the correct graph but the colors are always black, for example enter image description here


Solution

  • Apparently nx.draw_circular does not consider the colors attribute and must be explicitly given.

    for item in left_side_items:
        G.add_edge(str(item), "R"+str(rule_id), color=color_of_rule)
    
    for item in right_side_items:
        G.add_edge("R"+str(rule_id), str(item), color=color_of_rule)
    
    color_iter += 1
    

    After adding the colors to each edge you can get them in a list that will be passed to the draw_circular.

    edges = G.edges()
    colors = [G[u][v]['color'] for u, v in edges]
    
    nx.draw_circular(G, edge_color=colors, node_size=final_node_sizes, node_color=color_map, with_labels=True)
    plt.show()