twinx 弄乱了 pcolormesh 图的颜色条

twinx messes up colorbar of pcolormesh plot

我在尝试在图像上绘制一些值时遇到问题。问题是我无法正确放置颜色条。正确地我的意思是我在其中叠加线图的图像。此线图的 yaxis 应该在右侧带有标签,然后再往右应该是图像的颜色条。

这是显示问题的简化代码:

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable

image = np.random.randint(10, size=100).reshape(10, 10)

fig, ax = plt.subplots()

# ax2 = ax.twinx()  # -> Calling this messes up the colorbar
# ax2.plot(image.sum(0), 'r')  # what I actually want to do but not needed for the error

im = ax.pcolormesh(image)

cax = make_axes_locatable(ax).append_axes('right', size="5%", pad=0.4)
cbar = fig.colorbar(im, cax=cax)

下面你可以看到 ax2 = ax.twinx() 在颜色栏上的效果(我对图像没有足够的声誉,所以 Whosebug 将其替换为链接)。

without ax2 = ax.twinx()

with ax2 = ax.twinx()

我尝试了 make_axes_locatable(ax).append_axes() 并且还尝试了与 make_axes_locatable(ax).new_horizontal() 的组合,灵感来自这个问题的答案:Positioning the colorbar.

查看 fig.colorbar() 的文档,我找到了参数 axcax 并使用它们。他们做了很多,但不是我想做的。

我不确定我做错了什么,无法在互联网上找到,非常感谢您的任何建议。

您是否尝试过 constrained_layout 的普通颜色条:

import matplotlib.pyplot as plt
import numpy as np

image = np.random.randint(10,  size=100).reshape(10, 10)

fig, ax = plt.subplots(constrained_layout=True)
ax2 = ax.twinx()  
ax2.plot(image.sum(0), 'r')  
im = ax.pcolormesh(image)

cbar = fig.colorbar(im, ax=ax)
plt.show()