使用add_artist后Pyplot不会清除图形

时间:2019-12-21 18:34:42

标签: matplotlib

在这个玩具示例中,我使用add_artistMario添加到情节中。当我这样做时,我似乎无法清除数字。尝试将马里奥(mario)添加到第二个绘图(02.png)时,Python抛出RuntimeError: Can not put single artist in more than one figure。为什么会这样呢?如何避免此错误?我尝试发送ab following this approach的副本,但是没有用。

import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox

vortexRF = plt.imread('./mario.png')
imagebox = OffsetImage(vortexRF, zoom=0.03)

for ii in range(3):

   fig, ax = plt.subplots(2, 2)
   plt.subplots_adjust(wspace=0.6, hspace=0.5)

   for jj in range(2):
      for kk in range(2):
         ax[jj, kk].plot([0, 1], [0, 1], label='1')
         ax[jj, kk].plot([0, 1], [0, 1], label='2', ls='--')

   ax[1, 0].legend(loc='upper center', bbox_to_anchor=(.08, 2.85))

   if True: # Switch to control if we add mario
      ab = AnnotationBbox(imagebox, (0, 0), frameon=False)
      cbar_ax = fig.add_axes([0.7, .92, 0.1, 0.1])
      cbar_ax.add_artist(ab)
      cbar_ax.axis('off')

   plt.savefig('./%02d' % ii)

   # attempt to clear figure
   plt.clf()
   plt.cla()
   plt.close('all')
   ab.remove()

1 个答案:

答案 0 :(得分:2)

如果您试图使Mario匆忙运行:),如下图所示,我认为每次添加到坐标轴时都需要创建一个新的“图像框”。

enter image description here

import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox

vortexRF = plt.imread('mario.png')
for ii in range(9):
   fig, ax = plt.subplots(2, 2)
   plt.subplots_adjust(wspace=0.6, hspace=0.5)
   for jj in range(2):
      for kk in range(2):
         ax[jj, kk].plot([0, 1], [0, 1], label='1')
         ax[jj, kk].plot([0, 1], [0, 1], label='2', ls='--')
   ax[1, 0].legend(loc='upper center', bbox_to_anchor=(.08, 2.85))

   if True: # Switch to control if we add mario
      imagebox = OffsetImage(vortexRF, zoom=0.03)
      ab = AnnotationBbox(imagebox, (0, 0), frameon=False)
      cbar_ax = fig.add_axes([0.1+0.1*ii, .92, 0.1, 0.1])
      cbar_ax.add_artist(ab)
      cbar_ax.axis('off')

   plt.savefig(str(ii)+'.png')
plt.show()