python - How to add labels to nodes in a graph in networkx? -


i writing code integer partition , constructing graph each node partition. label nodes in graph partition elements {2,1,1}, {1,1,1,1},{2,2} etc.

so want know, how label node in networkx.

i have seen code labeling node didn't it. code given below:

nx.draw_networkx_nodes(g,pos,                        nodelist=[0,1,2,3],                        node_color='r',                        node_size=500,                     alpha=0.8) 

but want label individual nodes of constructed graph!

i providing code here, can have better understanding of it.

import networkx nx matplotlib import pylab pl  def partitions(num):     final=[[num]]      in range(1,num):         a=num-i         res=partitions(i)         ele in res:             if ele[0]<=a:                 final.append([a]+ele)      return final  def drawgraph(parlist):     #this draw graph     g=nx.graph()     length=len(parlist)     print "length %s\n" % length      node_list=[]      in range(1,length+1):         node_list.append(i)      g.add_cycle(node_list)      nx.draw_circular(g)     pl.show() 

please me.

thank much

since node_list composed of integers, nodes got string representation of integers labels. nodes can hashable object, not integers. simplest thing make node_list string representation of items in parlist. (the items in parlist lists, mutable , therefore not hashable. that's why can't use parlist our node_list.)

there function nx.relabel_nodes, use instead, think giving nodes right label in first place simpler.

import networkx nx import matplotlib.pyplot plt   def partitions(num):     final = [[num]]      in range(1, num):         = num -         res = partitions(i)         ele in res:             if ele[0] <= a:                 final.append([a] + ele)      return final   def drawgraph(parlist):     g = nx.graph()     length = len(parlist)     print "length %s\n" % length     node_list = [str(item) 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 lifted labels     http://networkx.lanl.gov/examples/advanced/heavy_metal_umlaut.html     """     pos = nx.spring_layout(g) if pos none else pos     nx.draw(g, pos, font_size=fontsize, with_labels=false)     p in pos:  # raise text positions         pos[p][1] += offset     nx.draw_networkx_labels(g, pos)     plt.show()  drawgraph(partitions(4)) 

yields

enter image description here


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -