Matplotlib:使用与前一个轴相同的参数添加轴

时间:2017-10-25 13:31:37

标签: python matplotlib

我想在两个不同的子图中绘制数据。绘图后,我想回到第一个子图并在其中绘制一个额外的数据集。但是,当我这样做时,我收到了这个警告:

  

MatplotlibDeprecationWarning:使用与先前轴相同的参数添加轴当前重用前一个实例。在将来的版本中,将始终创建并返回新实例。同时,通过将唯一标签传递给每个轴实例,可以抑制此警告,并确保将来的行为。     warnings.warn(message,mplDeprecation,stacklevel = 1)

我可以用一段简单的代码重现它:

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)

有关如何避免此警告的任何想法?我使用matplotlib 2.1.0。看起来与here

相同

7 个答案:

答案 0 :(得分:18)

这是一个很好的例子,展示了使用 public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { } ' object oriented API的好处。

matplotlib

注意:让变量名称以小写字母开头更为pythonic,例如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() 而非data = ...PEP8

答案 1 :(得分:5)

使用plt.subplot(1,2,1) 在当前图中创建新轴。弃用警告告诉您,在将来的版本中,当您第二次调用它时,它不会抓取先前创建的轴,而是覆盖它。

您可以通过将其分配给变量来保存对第一个轴实例的引用。

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)

答案 2 :(得分:1)

您可以在绘制内容之前简单地调用plt.clf()。这将清除所有现有的情节。

答案 3 :(得分:1)

我有同样的问题。我曾经有以下引发警告的代码:

(请注意,变量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

我解决了它,像这样修改:

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

答案 4 :(得分:1)

请注意,在这种情况下,警告是误报。在您使用plt.subplot(..)重新激活先前创建的子图的情况下,最好不要触发它。

发生此警告的原因是plt.subplotfig.add_subplot()内部采用相同的代码路径。该警告仅针对后者,而非前者。

要详细了解此内容,请参见issues 12513。长话短说,人们正在为此而努力,但是要使这两个功能脱钩并不是那么容易。目前,如果警告是由plt.subplot()触发的,您可以轻松地忽略它。

答案 5 :(得分:0)

多次创建同一轴对象时出现错误。在您的示例中,您首先创建两个子图对象(使用plt.subplot方法)。

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

python自动将最后创建的轴设置为默认轴。轴仅表示图的框架,没有数据。这就是为什么您可以执行plt.plot(data)。方法plot(data)在轴对象中打印一些数据。 然后,当您尝试在同一图中打印新数据时,就不能再使用plt.subplot(2,1,2)了,因为python会默认创建一个新的axis对象。因此,您要做的是: 将每个子图分配给一个变量。

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

然后选择要在其中打印数据的“框架”:

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

如果您想在一个图形中绘制更多图形(例如5个),只需先创建一个图形即可。您的数据存储在Pandas DataFrame中,并为每个列在列表中创建一个新的axis元素。 然后遍历列表并在每个轴元素中绘制数据并选择属性

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]])

答案 6 :(得分:0)

我们可以为每个轴添加唯一的标签来绘制它。

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