在 matplotlib 中使用 onclick/事件删除颜色条

问题描述 投票:0回答:0

我正在用 2 个子图创建无花果,如下所示:

fig, ax = plt.subplots(1, 2, figsize=(6, 18), dpi=200)
axes = ax.ravel()
axes[0].imshow(plateLabeled)
pcm = axes[0].pcolormesh(plateLabeled)#, cmap='msml2')
fig.colorbar(pcm, ax=axes[0], shrink=0.4, pad=0.1)
axes[0].set_aspect('auto', adjustable='box')

最初第一个子图显示了一个图像,然后我单击内部,然后第二个子图更新。然后我试图根据第二个子图中的某个事件(鼠标单击)更改/更新第一个子图。它工作得很好,除了颜色条没有随着第一个子图中先前内容的更新或删除而更新。

def onclick(event):
    global pcm
    if event.button == 1 and event.inaxes == axes[0]:  # 'MouseButton.LEFT':
        xdata_, ydata_ = round(event.xdata), round(event.ydata)
        sIdx = gCoord2Idcs[(ydata_, xdata_, 1)]
        mz_, int_ = xvector, yvector
        spec, = axes[1].plot(mz_, int_, lw=0.5, alpha=0.5)
        axes[0].scatter(xdata_, ydata_, marker='.', c=spec.get_color(), edgecolors=spec.get_color(), s=1)
 
    if event.button == 3 and event.dblclick and event.inaxes == axes[1]:
        axes[1].clear()
        for scatter in axes[0].collections:
            scatter.remove()
    if event.button == 1 and event.dblclick and event.inaxes == axes[1]:
        # just creating an new image for axes[0]
        # .... 
        axes[0].clear()
        fig.colorbar(pcm, ax=axes[0]).remove()
        fig.colorbar(pcm, ax=axes[0]).set_ticks([])
        # fig.clear()
        axes[0].imshow(im, cmap='msml2')
        axes[0].set_title("m/z: {:.4f}, tol: {}".format(mz_v, tol))
        pcm = axes[0].pcolormesh(im, cmap='msml2')
        fig.colorbar(pcm, ax=axes[0], shrink=0.4, pad=0.1)
    plt.pause(0.1)
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()

我得到这些(截图):

您可以在

viridis
cmap 中看到以前的颜色条。即使删除了
axes[0]
内容。

如何在条件点击/事件后更新/删除/清除

axes[0]
suplot colorbar?

python matplotlib colorbar
© www.soinside.com 2019 - 2024. All rights reserved.