How to add labels to nodes in a graph in networkx?
integer, networkx, partitioning, python
Solution
Since your `node_list` was composed of integers, your nodes got the string representation of those integers as labels. But your nodes can be any hashable object, not just integers. So the simplest thing to do would be to make your `node_list` the string representation of the items in `parlist`. (The items in `parlist` are lists, which are mutable and therefore not hashable. That's why we can't just use `parlist` as our `node_list`.)
There is also the function nx.relabel_nodes, which we could use instead, but I think just giving the nodes the right label in the first place is simpler.
import networkx as nx
import matplotlib.pyplot as plt
def partitions(num):
final = [[num]]
for i in range(1, num):
a = num - i
res = partitions(i)
for ele in res:
if ele[0] <= a:
final.append([a] + ele)
return final
def drawgraph(parlist):
G = nx.Graph()
length = len(parlist)
print "length is %s\n" % length
node_list = [str(item) for item in parlist]
G.add_cycle(node_list)
pos = nx.circular_layout(G)
draw_lifted(G, pos)
def draw_lifted(G, pos=None, offset=0.07, fontsize=16):
"""Draw with lifted labels
http://networkx.lanl.gov/examples/advanced/heavy_metal_umlaut.html
"""
pos = nx.spring_layout(G) if pos is None else pos
nx.draw(G, pos, font_size=fontsize, with_labels=False)
for p in pos: # raise text positions
pos[p][1] += offset
nx.draw_networkx_labels(G, pos)
plt.show()
drawgraph(partitions(4))
yields
Problem
I am writing a code for integer partition and constructing a graph where each node is a partition. I would like to label the nodes in the graph with partition elements like {2,1,1}, {1,1,1,1},{2,2} etc. So I want to know, how to label a node in networkx. I have already seen the code for labeling node but I didn't get it. The code is given below: ``` nx.draw_networkx_nodes(G,pos, nodelist=[0,1,2,3], node_color='r', node_size=500, alpha=0.8) ``` But what I want is to label individual nodes of already constructed graph! I am providing my code here, so that you can have better understanding of it. ``` import networkx as nx from matplotlib import pylab as pl def partitions(num): final=[[num]] for i in range(1,num): a=num-i res=partitions(i) for ele in res: if ele[0]<=a: final.append([a]+ele) return final def drawgraph(parlist): #This is to draw the graph G=nx.Graph() length=len(parlist) print "length is %s\n" % length node_list=[] for i in range(1,length+1): node_list.append(i) G.add_cycle(node_list) nx.draw_circular(G) pl.show() ``` Please help me. Thank you very much