Matplotlib: Adding an axes using the same arguments as a previous axes

This is a good example that shows the benefit of using matplotlib's object oriented API.

import numpy as np
import matplotlib.pyplot as plt

# Generate random data
data = np.random.rand(100)

# Plot in different subplots
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(data)

ax2.plot(data)

ax1.plot(data+1)

plt.show()

Note: it is more pythonic to have variable names start with a lower case letter e.g. data = ... rather than Data = ... see PEP8


I had the same problem. I used to have the following code that raised the warning:

(note that the variable Image is simply my image saved as numpy array)

import numpy as np
import matplotlib.pyplot as plt

plt.figure(1)  # create new image
plt.title("My image")  # set title
# initialize empty subplot
AX = plt.subplot()  # THIS LINE RAISED THE WARNING
plt.imshow(Image, cmap='gist_gray')  # print image in grayscale
...  # then some other operations

and I solved it, modifying like this:

import numpy as np
import matplotlib.pyplot as plt

fig_1 = plt.figure(1)  # create new image and assign the variable "fig_1" to it
AX = fig_1.add_subplot(111)  # add subplot to "fig_1" and assign another name to it
AX.set_title("My image")  # set title
AX.imshow(Image, cmap='gist_gray')  # print image in grayscale
...  # then some other operations

Note that in this case, the warning is a false positive. It should ideally not be triggered in the case you use plt.subplot(..) to reactivate a subplot which has previously been created.

The reason this warning occurs is that plt.subplot and fig.add_subplot() take the same code path internally. The warning is meant for the latter, but not the former.

To read more about this, see issues 12513. Long story short, people are working on it, but it is not as easy as initially thought to decouple the two functions. For the moment you can just savely ignore the warning if it is triggered by plt.subplot().


Using plt.subplot(1,2,1) creates a new axis in the current figure. The deprecation warning is telling that in a future release, when you call it a second time, it will not grab the previously created axis, instead it will overwrite it.

You can save a reference to the first instance of the axis by assigning it to a variable.

plt.figure()
# keep a reference to the first axis
ax1 = plt.subplot(1,2,1)
ax1.plot(Data)

# and a reference to the second axis
ax2 = plt.subplot(1,2,2)
ax2.plot(Data)

# reuse the first axis
ax1.plot(Data+1)