How to remove lines in a Matplotlib plot

前端 未结 5 1947
忘掉有多难
忘掉有多难 2020-11-27 12:51

How can I remove a line (or lines) of a matplotlib axes in such a way as it actually gets garbage collected and releases the memory back? The below code appears to delete t

5条回答
  •  感动是毒
    2020-11-27 13:31

    I'm showing that a combination of lines.pop(0) l.remove() and del l does the trick.

    from matplotlib import pyplot
    import numpy, weakref
    a = numpy.arange(int(1e3))
    fig = pyplot.Figure()
    ax  = fig.add_subplot(1, 1, 1)
    lines = ax.plot(a)
    
    l = lines.pop(0)
    wl = weakref.ref(l)  # create a weak reference to see if references still exist
    #                      to this object
    print wl  # not dead
    l.remove()
    print wl  # not dead
    del l
    print wl  # dead  (remove either of the steps above and this is still live)
    

    I checked your large dataset and the release of the memory is confirmed on the system monitor as well.

    Of course the simpler way (when not trouble-shooting) would be to pop it from the list and call remove on the line object without creating a hard reference to it:

    lines.pop(0).remove()
    

提交回复
热议问题