【问题标题】:matplotlib, place a transparent subplot on top of another subplotmatplotlib,在另一个子图之上放置一个透明子图
【发布时间】:2019-08-26 15:23:18
【问题描述】:

我的目标是在另一个图的顶部有一个透明背景的图,但 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 轴仅适用于其中一个子图,但我希望它从上到下一直走。我的想法是创建一个具有透明背景的附加轴并将其添加到顶部。

【问题讨论】:

    标签: python matplotlib multiple-axes


    【解决方案1】:

    您可能希望在与现有子图相同的位置创建一个新子图。因为默认情况下,所有子图都使用相同的子图规范,这很简单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()
    

    【讨论】:

      猜你喜欢
      • 2016-03-12
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      • 2020-11-24
      • 1970-01-01
      • 2023-03-03
      相关资源
      最近更新 更多