Search code examples
pythonmatplotlibcounter

How to remove contour's clabel


As we know that we can remove the collections of contour/contourf. But how can I remove the contour's clabel?

fig = plt.figure()
ax = fig.add_subplots(111)
for ivalue in range(10):
    values = alldata [ivalue,:,:]
    cs = plt.contour(x,y,vakues)
    cb = plt.clabel(cs, cs.levels)
     # now remove cs
    for c in cs.collections:
        c.remove()
    # but how can I remove cb?
    plt.savefig('%s.png'%ivalue)

The clabel of first png still exists in second png. So i want to remove clabel meanwhile.


Solution

  • You can do the exact same as you are already doing for the contour lines. Minimal example:

    import numpy as np
    import matplotlib.pylab as pl
    
    pl.figure()
    for i in range(2):
        c  = pl.contour(np.random.random(100).reshape(10,10))
        cl = pl.clabel(c)
    
        if i == 1:
            pl.savefig('fig.png'.format(i))
    

    Results in double contours, labels:

    enter image description here

    By changing it to:

        # Same code as above left out
    
        if i == 1:
            pl.savefig('fig.png'.format(i))
    
        for contour in c.collections:
            contour.remove()
    
        for label in cl:
            label.remove()
    

    enter image description here