matplotlib将节点号添加到图例键

时间:2016-01-29 07:46:59

标签: python matplotlib legend networkx

我用networkx和matplotlib创建了一个网络图,它有20个不同颜色的节点。相同颜色的节点属于同一类别,但每个节点都有不同的标签。我已经对分组进行了排序(尽管我将其从下面的示例中删除以简化操作),但我似乎无法将节点编号显示在图例键中。

这是我的代码:

import networkx as nx
import matplotlib.pyplot as 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 the graph
    g = nx.Graph()
    for t in nodes:
        g.add_node(t)
    pos=nx.spring_layout(g)

    fig, ax = plt.subplots(1, figsize=(10,10))

    for 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()

这就是它给我的东西:

enter image description here

我想在图例中也有节点的数字,就像节点本身一样。有谁知道怎么做?我已经被困在这几个小时了!

1 个答案:

答案 0 :(得分:0)

根据documentation,您可以简单地将字典放入nx.draw_networkx_labels中的标签位置,即

nx.draw_networkx_labels(g, pos, labels=nodelabeldict, font_size=10,
              font_color='#FFFFFF', font_family='sans-serif')