remove colorbar from figure in matplotlib

后端 未结 9 549
终归单人心
终归单人心 2020-12-08 14:14

This should be easy but I\'m having a hard time with it. Basically, I have a subplot in matplotlib that I\'m drawing a hexbin plot in every time a function is called, but ev

9条回答
  •  时光取名叫无心
    2020-12-08 15:02

    I had a similar problem and played around a little bit. I came up with two solutions which might be slightly more elegant:

    1. Clear the whole figure and add the subplot (+colorbar if wanted) again.

    2. If there's always a colorbar, you can simply update the axes with autoscale which also updates the colorbar.

    I've tried this with imshow, but I guess it works similar for other plotting methods.

    from pylab import *
    close('all') #close all figures in memory
    
    #1. Figures for fig.clf method
    fig1 = figure()
    fig2 = figure()
    cbar1=None
    cbar2=None
    data = rand(250, 250)
    
    def makefig(fig,cbar):
      fig.clf()
      ax = fig.add_subplot(111)
      im = ax.imshow(data)
      if cbar:
        cbar=None
      else:
        cbar = fig.colorbar(im)
      return cbar
    
    
    #2. Update method
    fig_update = figure()
    cbar3=None
    data_update = rand(250, 250)
    img=None
    
    def makefig_update(fig,im,cbar,data):
      if im:
        data*=2 #change data, so there is change in output (look at colorbar)
        #im.set_data(data) #use this if you use new array
        im.autoscale()
        #cbar.update_normal(im) #cbar is updated automatically
      else:
        ax = fig.add_subplot(111)
        im = ax.imshow(data)
        cbar=fig.colorbar(im)
      return im,cbar,data
    
    #Execute functions a few times
    for i in range(3):
      print i
      cbar1=makefig(fig1,cbar1)
      cbar2=makefig(fig2,cbar2)
      img,cbar3,data_update=makefig_update(fig_update,img,cbar3,data_update)
    cbar2=makefig(fig2,cbar2)
    
    fig1.show()
    fig2.show()
    fig_update.show()
    

提交回复
热议问题