Question

I've built a graph using the following code:

G = networkx.Graph()
G.add_edges_from([list(e) for e in P + Q + R])    
colors = "bgrcmyk"
color_map = [colors[i] for i in range(n/2)]

# add colors
for i in range(len(P)):
    edge = list(P[i])
    G[edge[0]][edge[1]]['edge_color'] = color_map[i]

for i in range(len(P)):
    edge = list(Q[perms[0][i]])
    G[edge[0]][edge[1]]["color"] = color_map[perms[0][i]]

for i in range(len(P)):
    edge = list(R[perms[1][i]])
    G[edge[0]][edge[1]]["color"] = color_map[perms[1][i]]

which I then display using:

networkx.draw(G)
matplotlib.pyplot.show()

It displays fine, except that all edges are coloured in black instead of the colours I tried to assign in the above snippet. Any ideas?

Was it helpful?

Solution 2

Hm, finally found what I needed to do. Colours apparently needed to be separated, and network needs to be drawn with draw_networkx. So the above three for loops are to be replaced with:

pos=networkx.spring_layout(G)
for i in range(len(P)):
    networkx.draw_networkx_edges(G,pos,
                edgelist=[list(P[i]), list(Q[perms[0][i]]), list(R[perms[1][i]])],edge_color=color_map[i], width="8")

OTHER TIPS

You can do it without drawing edges in a loop. It will be faster for larger graphs.

import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph()
# example graph 
for color in "bgrcmyk":
    G.add_edge('s'+color,'t'+color, color=color)

# edge_color_attr = nx.get_edge_attributes(G,'color')
# edges = edge_color_attr.keys()
# colors = edge_color_attr.values()
edges,colors = zip(*nx.get_edge_attributes(G,'color').items())
nx.draw(G,edgelist=edges,edge_color=colors,width=10)
plt.show()

The docstring shows:

edge_color : color string, or array of floats Edge color. Can be a single color format string (default='r'), or a sequence of colors with the same length as edgelist. If numeric values are specified they will be mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top