Skip to content Skip to sidebar Skip to footer

Runtimeerror: Underlying C/c++ Object Has Been Deleted When Saving And Afterwards Closing A Pyplot Figure

I ran into a python error that i have been trying to solve for several days now. My program creates figures, saves and closes them which works fine except for this error. Usually i

Solution 1:

How about change the backend to other options? For example:

import matplotlib as mpl
mpl.use( "agg" )

from matplotlib import pyplot as plt
import numpy as np

print plt.get_backend()

file_number = 100for num in np.arange(file_number):
    plt.figure('abc' + str(num),figsize=(22,12),dpi=100)
    #some plots are added to the figureprint1
    plt.savefig("%d.png" % num,dpi=100)
    print2
    plt.close()
    print3

Solution 2:

I can't replicate your problem (partially because your example is not self contained), but I think you could look at going about solving the problem slightly different.

Since your figure definition (size, dpi, etc.) stays the same throughout the loop (and even if it didn't) you could look at producing just one figure, and updating it inside the loop:

import matplotlib as mpl
mpl.use( "tkagg" )

from matplotlib import pyplot as plt
import numpy as np


file_number = 1000
fig = plt.figure('abc', figsize=(22,12), dpi=100)

plt.show(block=False)

for num in np.arange(file_number):
    fig.set_label('abc%s' % num)

    # add an axes to the figure
    ax = plt.axes()

    #some plots are added to the figure (I just plotted a line)
    plt.plot(range(num))

    plt.savefig("%d.png" % num, dpi=100)
    # draw the latest changes to the gui
    plt.draw()

    # remove the axes now that we have done what we want with it.
    fig.delaxes(ax)

# put in a blocking show to wait for user interaction / closure.
plt.show()

Typically this isn't how you would do things (I would normally update the axes rather than add/remove one each time) but perhaps you have a good reason for doing it this way.

That should improve the performance significantly.

Post a Comment for "Runtimeerror: Underlying C/c++ Object Has Been Deleted When Saving And Afterwards Closing A Pyplot Figure"