How do I change the color of the edges in a graph in networkx based on the weights of those edges?
The following code just gives all black edges,even though the colormap is jet!
nx.draw_networkx(g,pos=pos,with_labels=True,edge_colors=[g[a][b]['weight'] for a,b in g.edges()], width=4,edge_cmap = plt.cm.jet)
Scaling the edge weights to be between 0 and 1 doesn't change anything.
I'm not sure how the above code differs from that in a related question except that I don't use a loop for draw_networkx
because I'm not animating the graph.
Add all the edges in ebunch as weighted edges with specified weights. Each edge given in the list or container will be added to the graph. The edges must be given as 3-tuples (u,v,w) where w is a number. The attribute name for the edge weights to be added.
As you probably know, NetworkX is not primarily a graph drawing package, so it doesn't offer much to create visually pleasing and interactive graphs. Also, NetworkX cannot handle visualizations of large graphs, so you need to reach out for another drawing library and learn how to use it.
Can this construct a heterogeneous graph directly? A NetworkX graph inherently does not have node and edge types. Instead, the nodes can have different feature dimensions. So there is currently no one-liner to copy node features from a NetworkX graph to a DGL HeteroGraph.
#!/usr/bin/env python
"""
Draw a graph with matplotlib.
You must have matplotlib for this to work.
"""
try:
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import numpy as np
except:
raise
import networkx as nx
G=nx.path_graph(8)
#Number of edges is 7
values = range(7)
# These values could be seen as dummy edge weights
jet = cm = plt.get_cmap('jet')
cNorm = colors.Normalize(vmin=0, vmax=values[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
colorList = []
for i in range(7):
colorVal = scalarMap.to_rgba(values[i])
colorList.append(colorVal)
nx.draw(G,edge_color=colorList)
plt.savefig("simple_path.png") # save as png
plt.show() # display
Just modified an example code from networkx that plots a simple graph.
A simpler use in networkx 2.2
as seen in this example.
And using the code used by the answer above by Vikram:
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import numpy as np
import networkx as nx
G=nx.path_graph(8)
#Number of edges is 7
values = range(7)
nx.draw(G, edge_color=values, cmap=plt.cm.jet)
plt.show() # display
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With