Plotting networkx graph with node labels defaulting to node name

前端 未结 1 857
南旧
南旧 2020-11-27 19:36

NetworkX is powerful but I was trying to plot a graph which shows node labels by default and I was surprised how tedious this seemingly simple task could be for someone new

相关标签:
1条回答
  • 2020-11-27 19:50

    tl/dr: just add with_labels=True to the nx.draw call.

    The page you were looking at is somewhat complex because it shows how to set lots of different things as the labels, how to give different nodes different colors, and how to provide carefully control node positions. So there's a lot going on.

    However, it appears you just want each node to use its own name, and you're happy with the default color and default position. So

    import networkx as nx
    import pylab as plt
    
    G=nx.Graph()
    # Add nodes and edges
    G.add_edge("Node1", "Node2")
    nx.draw(G, with_labels = True)
    plt.savefig('labels.png')
    

    If you wanted to do something so that the node labels were different you could send a dict as an argument. So for example,

    labeldict = {}
    labeldict["Node1"] = "shopkeeper"
    labeldict["Node2"] = "angry man with parrot"
    
    nx.draw(G, labels=labeldict, with_labels = True)
    

    0 讨论(0)
提交回复
热议问题