我正在尝试绘制一些数组数据,并在轴的右侧添加一个颜色条,以匹配高度并设置宽度。
从生成一些数据开始。
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.random.rand(700, 400)
我具有以下功能。
def plot_data(data, aspect, pad):
fig, ax = plt.subplots()
img = ax.imshow(data, aspect=aspect)
last_axes = plt.gca()
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=pad)
cbar = fig.colorbar(im, cax=cax)
plt.sca(last_axes)
运行plot_data(data, None, 0.05)
给出了我所期望的-an image with colorbar taking up 5% of the width, matched to the same height and padded correctly.
但是运行plot_data(data, 2.5, 0)
会导致a figure with an image that has the correct aspect ratio, but a colorbar that's padded way too much.,我可以通过将padding设置为负,通过反复试验找到一个好的值来纠正此问题。但是,我需要使它通用,并且无需用户监视即可工作。
我找到了this thread,但答案似乎无法解决这种特殊情况。
任何建议都非常感谢!
我一直在玩这个游戏,看起来颜色条总是基于数据图边缘的原始位置。这意味着,对于正的宽高比,图形的高度保持固定,图形的宽度减小。然后将图像居中,因此需要使用填充来分别通过宽度-高度/长宽比(向内)调整颜色栏。
width=last_axes.get_position().width height=last_axes.get_position().height cax = divider.append_axes('right', size='5%', pad=-((width/0.7)-(height/(0.7*aspect)) + pad))
我遇到的奇怪的事情是,它并没有精确地居中,而是数据和轴标签的中心,因此我们必须相应地缩小调整比例,因此公式中的比例为1 / 0.7。我意识到这并不完美,因为刻度线没有按纵横比减小,因此线性移位会更合适,但我现在已经做到了!
请注意,这不适用于小于1的纵横比,因为在那一点上,宽度是固定的,而在应用纵横比时,高度会改变。我要继续弄乱它,看看我是否可以泛化景观
编辑:
好,我有。附加轴功能出于某种原因将垂直颜色条强制为绘图的原始高度。对于人像图来说很好,但对于风景如画的情况来说是坏的,因为数据在垂直方向上会缩小,但是情节不是,所以我不得不在这里输入完整的代码:
长的细图,可能需要进行调整。def plot_data(data, aspect, pad): fig, ax = plt.subplots() img = ax.imshow(data, aspect=aspect) last_axes = plt.gca() divider = make_axes_locatable(ax) if(aspect<1): hscale=aspect cbar = fig.colorbar(img,shrink=hscale,pad=(-0.43+pad)) else: hscale=1 width=last_axes.get_position().width height=last_axes.get_position().height padfix = -((width/0.7)-(height/(0.7*aspect))) cax = divider.append_axes('right',size='5%', pad=padfix+ pad) cbar = fig.colorbar(img,cax=cax)
再次有一个固定的偏移量(这次是\ 0.43左右),这很奇怪,这是通过反复试验发现的,如果绘制really