networkx节点node样式style定制化,Python

x33g5p2x  于2021-12-08 转载在 Python  
字(0.9k)|赞(0)|评价(0)|浏览(305)

networkx节点node样式style定制化,Python

import networkx as nx
from matplotlib import pyplot as plt

KEY = 'key'

def app():
    G = nx.DiGraph()
    plt.figure(figsize=(12, 10), dpi=100)

    G.add_node(G.number_of_nodes())
    G.add_node(G.number_of_nodes())
    G.add_node(G.number_of_nodes())

    G.nodes[0][KEY] = [(90, 1), (80, 2), (70, 3)]
    G.nodes[1][KEY] = [(91, 1), (81, 2), (71, 3)]
    G.nodes[2][KEY] = [(92, 1), (82, 2), (72, 3)]

    print(G.nodes(data=True))

    pos = nx.spring_layout(G)

    labels = {}
    for i in range(G.number_of_nodes()):
        ls = G.nodes[i][KEY]
        s = str(i) + '\n' + tuplelist2str(ls)
        labels.__setitem__(i, s)

    nx.draw_networkx_nodes(G, pos=pos,
                           node_color='red',
                           node_size=2000,
                           node_shape='s')

    label_options = {"ec": "black", "fc": "white", "alpha": 0.7}
    nx.draw_networkx_labels(G, pos=pos,
                            labels=labels,
                            font_size=8,
                            font_color='blue',
                            bbox=label_options)

    plt.margins(0.1)
    plt.axis('off')
    plt.show()

def tuplelist2str(tl):
    s = ''
    for t in tl:
        s = s + '(' + str(t[0]) + ',' + str(t[1]) + ')'
    return s

if __name__ == '__main__':
    app()

输出:

相关文章