简体   繁体   中英

Networkx Graph plot node weights

I would like to assign node weights to each node in an undirected graph. I use the following MWE:

import sys
import matplotlib.pyplot as plt
import networkx as nx
G = nx.Graph()
G.add_node(0)
G.add_node(1, weight=2)
G.add_node(2, weight=3)
nx.draw(G, with_labels=True)
plt.show()

Then I have a figure of the following form: 在此处输入图片说明

I would like to plot a graph with the weights given in a new color next to the nodes, such as: 在此处输入图片说明

What is the easiest way to implement this? On SO the materials are mostly for edge weights, or changing node sizes wrt the node weights.

You can use labels attribute with corresponding dict and node_color attribute with corresponding list. For this code:

G = nx.Graph()
G.add_node(0, weight=8)
G.add_node(1, weight=5)
G.add_node(2, weight=3)
labels = {n: G.nodes[n]['weight'] for n in G.nodes}
colors = [G.nodes[n]['weight'] for n in G.nodes]
nx.draw(G, with_labels=True, labels=labels, node_color=colors)

Networkx will draw:

在此处输入图片说明

If you want to draw both node ID and its weight, you can write something like this:

labels = {n: str(n) + '; ' + str(G.nodes[n]['weight']) for n in G.nodes}


If you have missing weight attributes in nodes and want to draw them, you can use this code:

labels = {
    n: str(n) + '\nweight=' + str(G.nodes[n]['weight']) if 'weight' in G.nodes[n] else str(n)
    for n in G.nodes
}

I think it is nearly impossible to draw weights near nodes with different color. It is the best I can suggest to you.

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