matplotlib,将透明子图放置在另一个子图之上

matplotlib, place a transparent subplot on top of another subplot

我的目标是将透明背景的绘图恰好放在另一个绘图的顶部,但 y 轴在另一侧。但是,我不知道怎么调到合适的尺寸。

这个代码

plt.figure(1, figsize=(9, 3))
plt.subplot(1,1,1)  
plt.plot([1, 2], [3, 2], color='black')
ax2 = plt.axes([0, 0, 1, 1], facecolor='none')
ax2.yaxis.set_label_position("right")
ax2.yaxis.tick_right()
ax2.plot([1, 2], [3.1,2.1])

产生

显然,框的大小需要设置不同。

如果您想知道为什么,这里是背景。我的目标是绘制一个有 2 个 y 轴的图,一个在左边,一个在右边,其中左边的 y 轴被打断,右边的没有。打断我的意思是这样的:

该图是用 2 个子图创建的,如下所示:

top_ratio = 1
bot_ratio = 4
gsdict={'height_ratios':[top_ratio, bot_ratio]}
f, (ax1, ax2) = plt.subplots(2, 1, sharex=True, gridspec_kw=gsdict)

但是,如果我现在使用 twinx 获取另一个 y 轴,那么新的 y 轴仅适用于其中一个子图,但我希望它从上到下一直延伸。我的想法是创建一个具有透明背景的附加轴并将其添加到顶部。

您可能希望在与现有子图相同的位置创建一个新的子图。因为,默认情况下,所有子图都使用相同的子图规范,这很容易ax3 = fig.add_subplot(111)

import matplotlib.pyplot as plt

gsdict={'height_ratios':[1, 4]}
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, gridspec_kw=gsdict)

ax3 = fig.add_subplot(111, label="new subplot", facecolor="none")
ax3.yaxis.set_label_position("right")

ax3.tick_params(left=False, right=True, labelleft=False, labelright=True,
                bottom=False, labelbottom=False)
ax1.get_shared_x_axes().join(ax1,ax3)

# just to see the effect, make spines green
plt.setp(ax3.spines.values(), color="limegreen", linestyle=":")
plt.show()