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

Question:

I want to plot data, in two different subplots. After plotting, I want to go back to the first subplot and plot an additional dataset in it. However, when I do so I get this warning:

MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.
warnings.warn(message, mplDeprecation, stacklevel=1)

I can reproduce that with a simple piece of code:

import matplotlib.pyplot as plt
import numpy as np

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

# Plot in different subplots
plt.figure()
plt.subplot(1, 2, 1)
plt.plot(data)

plt.subplot(1, 2, 2)
plt.plot(data)

plt.subplot(1, 2, 1) # Warning occurs here
plt.plot(data + 1)

Any ideas on how to avoid this warning? I use matplotlib 2.1.0. Looks like the same problem as here

Asked By: Nickj

||

Answers:

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

Answered By: DavidG

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)
Answered By: James

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
Answered By: Tommaso Di Noto

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().

The error appears when you create same axis object more then one time. In your example you first create two subplot objects (with method plt.subplot).

type(plt.subplot(2, 1, 2)) Out: matplotlib.axes._subplots.AxesSubplot

python automatically sets the last created axis as default. Axis means just the frame for the plot without data. That’s why you can perform plt.plot(data). The method plot(data) print some data in your axis object.
When you then try to print new data in the same plot you can’t just use plt.subplot(2, 1, 2) again, because python try to create a new axis object by default. So what you have to do is:
Assign each subplot to an variable.

ax1 = plt.subplot(2,1,1)
ax2 = plt.subplot(2,1,2)

then choose your “frame” where you want to print data in:

ax1.plot(data)
ax2.plot(data+1)
ax1.plot(data+2)

If you are interested to plot more graphs (e.g. 5) in one figure, just create first a figure. Your data is stored in a Pandas DataFrame and you create for each column a new axis element in a list.
then you loop over the list and plot in each axis element the data and choose the attributes

import pandas as pd 
import matplotlib.pyplot as plt 

#want to print all columns
data = pd.DataFrame('some Datalist')
plt.figure(1)
axis_list = []

#create all subplots in a list 
for i in range(data.shape[1]):
axis_list.append(plt.subplot(data.shape[1],1,i+1)

for i,ax in enumerate(axis_list):

    # add some options to each subplot  
    ax.grid(True)
    #print into subplots
    ax.plot(data.iloc[:,[i]])
Answered By: Robert Schirmer

We can add unique label to each axis to plot it.

ax = plt.subplot(label='testlabel')

Answered By: Pritam
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.