matplotlib:使用多个 twinx 子图控制 y 轴标签的位置

matplotlib: controlling position of y axis label with multiple twinx subplots

我写了一个基于 matplotlib 的 Python 脚本,它根据一个共同的时间轴生成曲线。根据用户选项,我的绘图中共享相同 x 轴的曲线数量可以从 1 到 6 不等。 绘制的每个数据都使用不同的 y 刻度,并且需要不同的轴来绘制。因此,我可能需要在绘图的右侧绘制最多 5 个不同的 Y 轴。我在其他一些 post 中找到了在添加新轴时偏移轴位置的方法,但我仍然有两个问题:

  1. 如何控制多个轴的位置使刻度标签不重叠?
  2. 如何控制每个轴标签的位置,使其垂直放置在每个轴的底部?以及如何在显示 window 调整大小、放大等时保持这种对齐方式... 我可能需要编写一些代码,首先查询轴的位置,然后是将标签相对于该位置放置的指令,但我真的不知道该怎么做。

我无法分享我的全部代码,因为它太大了,但我是从 this example 中的代码派生出来的。我通过添加一个额外的绘图和一个额外的轴来修改该示例,以更接近地匹配我的脚本中打算执行的操作。

import matplotlib.pyplot as plt


def make_patch_spines_invisible(ax):
    ax.set_frame_on(True)
    ax.patch.set_visible(False)
    for sp in ax.spines.values():
        sp.set_visible(False)


fig, host = plt.subplots()
fig.subplots_adjust(right=0.75)

par1 = host.twinx()
par2 = host.twinx()
par3 = host.twinx()

# Offset the right spine of par2.  The ticks and label have already been
# placed on the right by twinx above.
par2.spines["right"].set_position(("axes", 1.2))
# Having been created by twinx, par2 has its frame off, so the line of its
# detached spine is invisible.  First, activate the frame but make the patch
# and spines invisible.
make_patch_spines_invisible(par2)
# Second, show the right spine.
par2.spines["right"].set_visible(True)

par3.spines["right"].set_position(("axes", 1.4))
make_patch_spines_invisible(par3)
par3.spines["right"].set_visible(True)

p1, = host.plot([0, 1, 2], [0, 1, 2], "b-", label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], "r-", label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], "g-", label="Velocity")
p4, = par3.plot([0,0.5,1,1.44,2],[100, 102, 104, 108, 110], "m-", label="Acceleration")

host.set_xlim(0, 2)
host.set_ylim(0, 2)
par1.set_ylim(0, 4)
par2.set_ylim(1, 65)

host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")
par3.set_ylabel("Acceleration")

host.yaxis.label.set_color(p1.get_color())
par1.yaxis.label.set_color(p2.get_color())
par2.yaxis.label.set_color(p3.get_color())
par3.yaxis.label.set_color(p4.get_color())

tkw = dict(size=4, width=1.5)
host.tick_params(axis='y', colors=p1.get_color(), **tkw)
par1.tick_params(axis='y', colors=p2.get_color(), **tkw)
par2.tick_params(axis='y', colors=p3.get_color(), **tkw)
par3.tick_params(axis='y', colors=p4.get_color(), **tkw)
host.tick_params(axis='x', **tkw)

lines = [p1, p2, p3, p4]

host.legend(lines, [l.get_label() for l in lines])

# fourth y axis is not shown unless I add this line
plt.tight_layout()
plt.show()

当我运行这个的时候,我得到了下面的情节: output from above script

在此图中,上面的问题 2 意味着我希望将 y 轴标签 'Temperature'、'Velocity'、'Acceleration' 绘制在每个相应轴的正下方。

在此先感谢您的帮助。

此致,

L.

对我有用的是 ImportanceOfBeingErnest 关于使用文本的建议(像

host.text(1.2, 0, "Velocity" , ha="left", va="top", rotation=90, transform=host.transAxes))

而不是试图控制标签位置。