简体   繁体   中英

Vary thickness of edges based on weight in NetworkX

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())

In order to set the widths for each edge, ie 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()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM