Axes disappear after drawing Networkx Graph on another subplot

Viewed 155

I try to have a graph visualization on one subplot and a line plot of some values on another subplot. However, after I draw the graph on the first subplot, axes on the other subplot disappear (although I did not allow any shared axes). And I cannot bring them back.

import networkx as nx
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
G = nx.graph_atlas(1)
nx.draw(G, ax=ax1)
plt.show()

Results in: enter image description here While without nx.draw() it is: enter image description here

I've tried calling ax2.get_yaxis().set_visible(True) after nx.draw(G, ax=ax1) but it has no effect.

Q1: How to restore the axes on ax2?
Q2: How is it possible that nx.draw(G,ax=ax1) affects ax2?

1 Answers

The problem is a bug in networkx. Instead of setting the ticklabels for the axes ax off, it calls plt.tick_params(...). This will affect the currently active pyplot axes, which in your case is ax2.

So one option is to replace plt.tick_params( by ax.tick_params( in the source in lines 417 and 692 and 806 and 959 of networkx/networkx/drawing/nx_pylab.py.

I've just created a PR for that in https://github.com/networkx/networkx/pull/3476


The other option is to make sure the current pyplot axes is the one where your graph is in, e.g. via plt.sca(ax1),

import networkx as nx
print(nx.__version__)
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
G = nx.graph_atlas(1)
plt.sca(ax1)
nx.draw(G, ax=ax1)
plt.show()
Related