How to check if colorbar exists on figure

前端 未结 4 1661
遥遥无期
遥遥无期 2020-12-18 03:33

Question: Is there a way to check if a color bar already exists?

I am making many plots with a loop. The issue is that the color bar is drawn every

4条回答
  •  生来不讨喜
    2020-12-18 03:39

    If you can access to axis and image information, colorbar can be retrieved as a property of the image (or the mappable to which associate colorbar).

    Following a previous answer (How to retrieve colorbar instance from figure in matplotlib), an example could be:

    ax=plt.gca()        #plt.gca() for current axis, otherwise set appropriately.
    im=ax.images        #this is a list of all images that have been plotted
    if im[-1].colorbar is None:   #in this case I assume to be interested to the last one plotted, otherwise use the appropriate index or loop over
        plt.colorbar() #plot a new colorbar
    

    Note that an image without colorbar returns None to im[-1].colorbar

提交回复
热议问题