首页 > 解决方案 > twinx 弄乱了 pcolormesh 情节的颜色条

问题描述

尝试在图像顶部绘制一些值时遇到问题。问题是我无法真正正确放置彩条。正确地说,我的意思是我覆盖线图的图像。此线图的 y 轴应在其标签的右侧,然后再向右应为图像的颜色条。

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

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()上的效果(我对图像没有足够的声誉,所以 stackoverflow 用链接替换了它)。

没有ax2 = ax.twinx()

ax2 = ax.twinx()

我已经尝试过make_axes_locatable(ax).append_axes()并且还结合了make_axes_locatable(ax).new_horizontal()这个问题的答案:Positioning the colorbar

查看文档,fig.colorbar()我发现了这些论点axcax并与他们一起玩。他们做了很多,但不是我想要的。

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

标签: pythonmatplotlibcolorbartwinx

解决方案


您是否尝试过使用 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()

在此处输入图像描述


推荐阅读