Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

python - How to retrieve colorbar instance from figure in matplotlib

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.colorbar(ax)
newimg = img+10*np.randn(512,512)

def update_colorbar(fig,ax,newimg):
    cbar = fig.axes[1]
    ax.set_data(newimg)
    cbar.update_normal(ax)
    plt.draw()

but it seems that returned results from fig.axes() does not have the colorbar instance like I expected. I can probably just pass the colorbar instance as an argument to the update function, but I thought just passing one fig parameter may be good enough. Can anyone explain a little bit on how to retrieve the colorbar from the figure? Or why 'fig.axes()' doesn't return the AxesImage or Colobar instance but just the Axes or AxesSubplot? I think I just need more understanding of the Axes/Figure stuff.Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...