2

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: enter image description here

I would like to plot a graph with the weights given in a new color next to the nodes, such as: enter image description here

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

1 Answer 1

3

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:

enter image description here

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Hi, thanks for your reply! However, I don't want to change the colors, and only add the weights next to the original node index. Your last line labels = {n: str(n) + '; ' + str(G.nodes[n]['weight']) for n in G.nodes} does not work in my code. Is there any method to generate what I want?
You should set weight attribute for each node for this code to work.
At least it works, but I hope there is an even more precise way :)
Updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.