Delete a subplot

PythonMatplotlib

Python Problem Overview


I'm trying to figure out a way of deleting (dynamically) subplots in matplotlib. I see they have a remove method, but I get the error

NotImplementedError: cannot remove artist

I'm surprised that I can't find this anywhere. Does anyone know how to do this?

from matplotlib import pyplot as plt

fig, axs = plt.subplots(1,3)

axs[0].plot([1,2],[3,4])
axs[2].plot([0,1],[2,3])

plt.draw()
plt.tight_layout()

enter image description here

Python Solutions


Solution 1 - Python

Use fig.delaxes or plt.delaxes to remove unwanted subplots

fig, axs = plt.subplots(1,3)
axs[0].plot([1,2],[3,4])
axs[2].plot([0,1],[2,3])

fig.delaxes(axs[1])

plt.draw()
plt.tight_layout()

enter image description here

Solution 2 - Python

ax.set_visible(False)

will suffice in most cases.

Solution 3 - Python

Remove the axis from the figure doc:

axs[1].remove()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeffView Question on Stackoverflow
Solution 1 - PythonJeffView Answer on Stackoverflow
Solution 2 - Pythonnaught101View Answer on Stackoverflow
Solution 3 - PythonstansyView Answer on Stackoverflow