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

问题描述 投票:0回答:1

我写了一个基于matplotlib的Python脚本,它根据公共时间线生成曲线。在我的绘图中共享相同x轴的曲线数量可以在1到6之间变化,具体取决于用户选项。绘制的每个数据使用不同的y刻度,并且需要不同的轴进行绘制。因此,我可能需要在我的绘图右侧绘制最多5个不同的Y轴。当我添加新的时,我在其他帖子中找到了偏移轴位置的方法,但我还有两个问题:

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

我无法分享我的整个代码,因为它太大了,但我从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轴标签“温度”,“速度”,“加速度”直接绘制在每个相应的轴下方。

在此先感谢您的帮助。

问候,

L.

python-3.x matplotlib axis-labels multiple-axes twinx
1个回答
0
投票

对我有用的是对欧内斯特使用文本的建议的重要性(如同一行一样)

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

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

© www.soinside.com 2019 - 2024. All rights reserved.