简体   繁体   中英

NetworkX: draw_networkx not drawing labels:, draw results in'_AxesStack' object is not callable

Trying to draw two nodes graph with latest version of networkx-3.0 and latest version of matplotlib-3.6.3 . Drawing does not show labels on the plot:

import networkx as nx
import matplotlib.pyplot as plt

G=nx.Graph()
G.add_node(1, text='foo')
G.add_node(2, text='bar')
G.add_edge(1,2)
print("Node labels: ", nx.get_node_attributes(G, 'text'))
nx.draw_networkx(G, with_labels=True)
>> Node labels:  {1: 'foo', 2: 'bar'}

在此处输入图像描述

Shows graph without labels. Why?

And this results in error:

nx.draw(G)
plt.show()

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_16652\3657615245.py in <module>
----> 1 nx.draw(G)
      2 plt.show()

~\Anaconda3\lib\site-packages\networkx\drawing\nx_pylab.py in draw(G, pos, ax, **kwds)
    111     cf.set_facecolor("w")
    112     if ax is None:
--> 113         if cf._axstack() is None:
    114             ax = cf.add_axes((0, 0, 1, 1))
    115         else:

TypeError: '_AxesStack' object is not callable

<Figure size 640x480 with 0 Axes>

To answer the first question: the nx graph doesn't "know" that you want to look at its text attribute for the label, so it just goes with the initial node name.

Instead, you could pass a relabeled graph into the draw function

import networkx as nx
import matplotlib.pyplot as plt

G=nx.Graph()
G.add_node(1, text='foo')
G.add_node(2, text='bar')
G.add_edge(1,2)
print("Node labels: ", nx.get_node_attributes(G, 'text'))

nx.draw_networkx(nx.relabel_nodes(G, nx.get_node_attributes(G, 'text')), 
                 with_labels=True, node_color = 'orange')
plt.show()

The result:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM