1

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

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

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

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()

当我运行它时,我得到以下图: 上面脚本的输出

在这张图片中,上面的问题 2 意味着我希望将 y 轴标签“温度”、“速度”、“加速度”直接绘制在每个相应轴的下方。

提前感谢您的帮助。

问候,

L.

4

1 回答 1

0

对我有用的是 ImportanceOfBeingErnest 建议使用文本(用一行

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

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

于 2019-02-22T16:49:31.863 回答