Python Matplotlib:使用与先前轴相同的参数添加轴
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46933824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Matplotlib: Adding an axes using the same arguments as a previous axes
提问by Nickj
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)
MatplotlibDeprecationWarning:使用与先前轴相同的参数添加轴当前会重用较早的实例。在未来的版本中,将始终创建并返回一个新实例。同时,通过将唯一标签传递给每个轴实例,可以抑制此警告并确保未来的行为。警告.警告(消息,mplDeprecation,堆栈级别= 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
关于如何避免此警告的任何想法?我使用 matplotlib 2.1.0。看起来和这里的问题一样
采纳答案by DavidG
This is a good example that shows the benefit of using matplotlib
's object oriented API.
这是一个很好的例子,示出了使用受益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 to have variable names start with a lower case letter e.g. data = ...
rather than Data = ...
see PEP8
回答by James
Using plt.subplot(1,2,1)
createsa 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.
使用在当前图形中plt.subplot(1,2,1)
创建一个新轴。弃用警告表明,在未来的版本中,当您第二次调用它时,它不会抓取先前创建的轴,而是会覆盖它。
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)
回答by ImportanceOfBeingErnest
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.
请注意,在这种情况下,警告是误报。理想情况下,它不应在您plt.subplot(..)
用来重新激活先前创建的子图的情况下触发。
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.
出现此警告的原因是plt.subplot
并且fig.add_subplot()
在内部采用相同的代码路径。警告是针对后者的,而不是针对前者的。
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()
.
要阅读有关此内容的更多信息,请参阅问题 12513。长话短说,人们正在研究它,但将这两个功能解耦并不像最初想象的那么容易。目前,如果警告是由plt.subplot()
.
回答by Tommaso Di Noto
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)
(请注意,变量Image
只是我保存为 numpy 数组的图像)
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
回答by Robert Schirmer
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).
当您多次创建相同的轴对象时会出现该错误。在您的示例中,您首先创建两个子图对象(使用 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.
python 自动将最后创建的轴设置为默认值。轴仅表示没有数据的绘图框架。这就是为什么你可以执行 plt.plot(data)。方法 plot(data) 在您的轴对象中打印一些数据。当您尝试在同一图中打印新数据时,您不能再次使用 plt.subplot(2, 1, 2) ,因为默认情况下 python 尝试创建一个新的轴对象。所以你要做的是:将每个子图分配给一个变量。
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
如果您有兴趣在一个图形中绘制更多图形(例如 5 个),只需先创建一个图形。您的数据存储在 Pandas DataFrame 中,您为列表中的每一列创建一个新的轴元素。然后遍历列表并在每个轴元素中绘制数据并选择属性
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]])