How to retrieve colorbar instance from figure in matplotlib

前端 未结 2 1095
执笔经年
执笔经年 2020-12-05 23:54

all. I want to update the colorbar of a figure when the imagedata is changed. So something like:

img = misc.lena()
fig = plt.figure()
ax = plt.imshow(im)
plt         


        
2条回答
  •  既然无缘
    2020-12-06 00:48

    Sometimes it can be useful to retrieve a colorbar even if it was not held in a variable.

    In this case, it is possible to retrieve the colorbar from the plot with:

    # Create an example image and colourbar
    img = np.arange(20).reshape(5,4)
    plt.imshow(img)
    plt.colorbar()
    
    # Get the current axis 
    ax = plt.gca()        
    
    # Get the images on an axis
    im = ax.images        
    
    # Assume colorbar was plotted last one plotted last
    cb = im[-1].colorbar   
    
    # Do any actions on the colorbar object (e.g. remove it)
    cb.remove()
    

    EDIT:

    or, equivalently, the one liner:

    plt.gca().images[-1].colorbar.remove()
    

    N.B.: see also comments for the use of ax.collections[-1] instead of ax.images[-1]. For me it always worked only the first way, I don't know what depends on, maybe the type of data or plot.


    Now you can operate on cb as if it were stored using commands described in the colorbar API. For instance you could change xlim or call update as explained in other comments. You could remove it with cb.remove() and recreate it with plt.colorbar().

    plt.draw() or show should be called after to update plot.

    As the image is the mappable associated to the colorbar and can be obtained with cb.mappable.

提交回复
热议问题