Yaxis标签跨越了两个轴,并具有子图中一个轴的Yaxis标签

问题描述 投票:0回答:0
I有一个带有3个子图的图:顶部图大于随后的两个图。他们都共享相同的X和Y轴。但是,Ylabel相当长,因此两个底部图的Ylabels重叠(请参见下面的IMG)。这是代码:

import numpy as np import matplotlib.pyplot as plt from matplotlib.transforms import blended_transform_factory imgs = [ np.random.randn(200, 200), np.random.randn(50, 70), np.random.randn(100, 100), ] figsize = [4, 6] ylabel = "Long label for radius (cm)" fig = plt.figure(figsize=figsize, layout="constrained") gs = fig.add_gridspec(3, 1, height_ratios=[2, 1, 1]) axes = [fig.add_subplot(gs[i]) for i in range(3)] for i in range(len(axes)): ax = axes[i] ax.imshow(imgs[i], aspect="auto") ax.set_xlabel("time (min)") # from here on come different trials for ax in axes: ax.set_ylabel(ylabel) fig.align_ylabels(axes) # needed because of different y-ticks (100 vs 50)

enter image description here 我想拥有一个横跨两个图的Ylabel。 我尝试了几件事,所有这些都无法正常工作。 我的第一次尝试是

axes[0].set_ylabel(ylabel) axes[1].set_ylabel(ylabel, loc="bottom") fig.align_ylabels(axes)

给出正确的x对准但错误的位置:

,然后我尝试了 axes[0].set_ylabel(ylabel) axes[1].set_ylabel(ylabel, loc="bottom", va="center") fig.align_ylabels(axes) enter image description here 为x和y对齐的结果失败。


到目前为止最好的尝试是

axes[0].set_ylabel(ylabel) axes[1].set_ylabel(ylabel) ax = axes[1] new_trafo = blended_transform_factory( x_transform=ax.yaxis.label.get_transform(), y_transform=ax.transAxes, ) axes[1].set_ylabel(ylabel, y=0.0, va="center") fig.align_ylabels(axes)

在此结果(可以解决的好的对齐方式,但错误的x对齐)。 enter image description here

这些方法中的任何方法都没有正常工作。但是,必须有一种方法来告诉matplotlib,即使在重新计算ylabel位置
layout="constrained"

fig.align_ylabels(axes)

后,底部的ylabel也应与顶部完全相同的x位置(在图像素中)完全相同。我该如何解决这个“对齐问题”?

enter image description here数字:将底部两个图的Ylabels分成两行对我来说不是解决方案,因为它在顶部Ylabel和其左轴邻居之间创造了空间。为简单起见,我已经忽略了原始问题的左轴邻居,如下图所述。

axes[0].set_ylabel(ylabel) for ax in axes[1:]: ax.set_ylabel("Long label\nfor radius (cm)") fig.align_ylabels(axes)

plt.subplots可用于创建多个轴并设置共享的Y轴,以便可以在子图中的两个轴上对齐y轴标签。您可以使用ax.set_ylabel()将标签定位在一个轴上,并且可以使用ax.yaxis.set_label_position()调整其位置。为了保持对齐的一致性,请确保两个子图具有相同的y轴。


python matplotlib subplot axis-labels matplotlib-gridspec
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.