Matplotlib: add axes using the same arguments as previous axes

I want to build data in two different subheadings. After plotting, I want to return to the first subplot and build an additional data set in it. However, when I do this, I get this warning:

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

I can reproduce this 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 am using matplotlib 2.1.0. Looks like the same problem here

+27
python matplotlib
source share
7 answers

This is a good example that demonstrates the benefits of using the object-oriented matplotlib 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 when variable names begin with a lowercase letter, for example, data =... rather than Data =... see PEP8

+18
source share

Using plt.subplot(1,2,1) creates a new axis in the current drawing. An obsolescence warning informs that in a future version, when you call it a second time, it will not capture the previously created axis, instead, it will overwrite it.

You can save a link 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) 
+6
source share

Please note that in this case the warning is a false positive. Ideally, you should not run it if you use plt.subplot(..) to reactivate the subplot that was previously created.

The reason plt.subplot this warning is that plt.subplot and fig.add_subplot() use the same code path inside. The warning is intended for the latter, but not for the former.

To learn more about this, see Issues 12513 . In short, people are working on it, but it’s not as easy as it was originally thought to separate the two functions. For now, you can simply ignore the warning if it is called plt.subplot() .

+2
source share

You can simply call plt.clf() before building plt.clf() . This will clear all existing sites.

+1
source share

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

(note that the Image variable is just my image saved as an 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 by changing 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 
+1
source share

In order to add something else besides the previous answers, especially regarding the answer of @Tommaso Di Noto. In my case, I had to set the title for the graph, and not for the axis, in any case, both helped me, but, for your information, I had to pass the label to add_subplot:

  fig = plt.figure() # Set Title plt.title('title') # Define the first axis ax1 = fig.add_subplot(111, label='title') 

If you're wondering why 111 is the position in the grid, check add_subplot: In Matplotlib, what does the argument in fig.add_subplot (111) mean?

Hope this helps

0
source share

An error appears when you create the same axis object more than once. In your example, you first create two subplot objects (using the plt.subplot method).

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

Python automatically sets the last axis created by default. An axis simply means a frame for a graph without data. That is why you can execute plt.plot (data). The plot (data) method prints some data in your axis object. When you then try to print new data on the same graph, you cannot just use plt.subplot (2, 1, 2) again, because python is trying to create a new axis object by default. So what you have to do: assign each subplot to a variable.

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

then select your "frame" into which you want to print the data:

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

If you are interested in building more charts (e.g. 5) on one shape, just create a shape first. Your data is stored in a DataFrame Pandas, and you create for each column a new axis element in the list. Then you iterate over the list and apply data to each element of the axis and select 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]]) 
0
source share

All Articles