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

匿名 (未验证) 提交于 2019-12-03 08:36:05

问题:

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

回答1:

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



回答2:

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) 


回答3:

You can simply call plt.clf() before you plot things. This will clear all existing plots.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!