i've made network graph networkx , matplotlib has 20 nodes in different shades of colour. nodes of same colour belong same category, each have different label. i've got grouping sorted (although took out of example below simplify things), can't seem node numbers show in legend keys.
here's code:
import networkx nx import matplotlib.pyplot plt def make_network_graph(): nodes = ['21', '91', '60', '85', '67', '59', '29', '88', '28', '30', '76', '53', '97', '81', '64', '57', '74', '69', '35', '95'] nodelabels = [r'label 1', r'label 2', r'label 3', r'label 4', r'label 5', r'label 6', r'label 7', r'label 8', r'label 9', r'label 10', r'label 11', r'label 12', r'label 13', r'label 14', r'label 15', r'label 16', r'label 17', r'label 18', r'label 19', r'label 20'] nodecolours = ['#000000', '#000000', '#000000', '#000000', '#000000', '#3b3b3b', '#3b3b3b', '#3b3b3b', '#4f4f4f', '#636363', '#777777', '#8b8b8b', '#8b8b8b', '#8b8b8b', '#8b8b8b', '#8b8b8b', '#9f9f9f', '#bdbdbd', '#bdbdbd', '#bdbdbd'] nodelabeldict = {r'label 11': ['76'], r'label 1': ['21'], r'label 2': ['91'], r'label 3': ['60'], r'label 4': ['85'], r'label 5': ['67'], r'label 17': ['74'], r'label 18': ['69'], r'label 19': ['35'], r'label 20': ['95'], r'label 6': ['59'], r'label 7': ['29'], r'label 8': ['88'], r'label 12': ['53'], r'label 13': ['97'], r'label 14': ['81'], r'label 15': ['64'], r'label 16': ['57'], r'label 9': ['28'], r'label 10': ['30']} nodecolourdict = dict(zip(nodelabels, nodecolours)) # generate graph g = nx.graph() t in nodes: g.add_node(t) pos=nx.spring_layout(g) fig, ax = plt.subplots(1, figsize=(10,10)) l in nodelabels: llist = nodelabeldict[l] lcolour = nodecolourdict[l] nx.draw_networkx_nodes(g,pos,nodelist=llist, ax=ax,node_color=lcolour,label=l) nx.draw_networkx_labels(g, pos, labels=none, font_size=10, font_color='#ffffff', font_family='sans-serif') plt.axis('off') ax.legend(scatterpoints=1, loc=(-0.15, 0.2), shadow=true) plt.savefig('/tmp/network.png') plt.show()
this gives me:
i have nodes' numbers in legend too, inside circles, nodes themselves. have idea how that? i've been stuck on hours!
according documentation, can put dictionary labels position in nx.draw_networkx_labels, i.e.
nx.draw_networkx_labels(g, pos, labels=nodelabeldict, font_size=10, font_color='#ffffff', font_family='sans-serif')
Comments
Post a Comment