Reputation: 83
I'm trying to draw a network diagram using Python Networkx package. I would like to vary the thickness of the edges based on the weights given to the edges.
I am using the following code which draws the diagram, but I cannot get the edge to vary its thickness based on the weight. Can someone help me with this problem? Thanks in advance.
df = pd.DataFrame({ 'from':['D', 'A', 'B', 'C','A'], 'to':['A', 'D', 'A', 'E','C'], 'weight':['1', '5', '8', '3','20']})
G=nx.from_pandas_edgelist(df, 'from', 'to', edge_attr='weight', create_using=nx.DiGraph() )
nx.draw_shell(G, with_labels=True, node_size=1500, node_color='skyblue', alpha=0.3, arrows=True,
weight=nx.get_edge_attributes(G,'weight').values())
Upvotes: 8
Views: 8051
Reputation: 88305
In order to set the widths for each edge, i.e with an array-like of edges, you'll have to use nx.draw_networkx_edges
through the width parameter, since nx.draw
only accepts a single float. And the weights can be obtaind with nx.get_edge_attributes
.
Also you can draw with a shell layout using nx.shell_layout
and using it to position the nodes instead of nx.draw_shell
:
import networkx as nx
from matplotlib import pyplot as plt
widths = nx.get_edge_attributes(G, 'weight')
nodelist = G.nodes()
plt.figure(figsize=(12,8))
pos = nx.shell_layout(G)
nx.draw_networkx_nodes(G,pos,
nodelist=nodelist,
node_size=1500,
node_color='black',
alpha=0.7)
nx.draw_networkx_edges(G,pos,
edgelist = widths.keys(),
width=list(widths.values()),
edge_color='lightblue',
alpha=0.6)
nx.draw_networkx_labels(G, pos=pos,
labels=dict(zip(nodelist,nodelist)),
font_color='white')
plt.box(False)
plt.show()
Upvotes: 15