【问题标题】:Axes Subplot y size轴子图 y 大小
【发布时间】:2016-08-12 00:33:35
【问题描述】:

我有两个共享 x 轴的子图。第一个有数据和拟合函数,第二个是数据和拟合函数之间的差异。在图中,两个子图都具有相同的 y 轴大小(以像素为单位)。现在我希望数据的 y 轴和拟合大于误差轴。我的代码如下:

import matplotlib.pyplot as plt
f, axarr = plt.subplots(2, sharex=True,figsize=(15, 12))
axarr[0].scatter(x, data , facecolors='none', edgecolors='crimson')
axarr[0].plot(x, fit, color='g',linewidth=1.5)
axarr[0].set_ylim([18,10])
axarr[1].plot(x,data-fit,color='k',linewidth=width)
axarr[1].set_ylim([-0.4,0.4])
yticks[-1].label1.set_visible(False)
plt.subplots_adjust(hspace=0.)

是否有任何代码可以设置第二个图的大小?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    看看this example, using gridspec。我相信这正是你想要的。以下是您的案例采用的示例。 编辑后也共享 x 轴

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import gridspec
    
    # generate some data
    x = np.arange(0, 10, 0.2)
    y = np.sin(x)
    
    # plot it
    fig = plt.figure(figsize=(8, 6))
    gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1])
    ax0 = plt.subplot(gs[0])
    ax1 = plt.subplot(gs[1], sharex=ax0)  # <---- sharex=ax0 will share ax1 with ax2
    ax0.plot(x, y)
    ax1.plot(y, x)
    
    plt.show()
    

    或者在第一个链接中关注Hagnes answer 甚至更简单:

    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.arange(0, 10, 0.2)
    y = np.sin(x)
    
    f, (a0, a1) = plt.subplots(2,1, gridspec_kw = {'height_ratios':[1, 3]}, sharex=True)  # <---- sharex=True will share the xaxis between the two axes
    a0.plot(x, y)
    a1.plot(y, x)
    plt.show()
    

    【讨论】:

    • 首先感谢您的回答!是的,我知道这一点,但是这两个图不再共享 x 轴。我想知道是否有任何方法可以获得“sharex”选项并设置绘图的大小。
    • 不客气!请参阅我更新的答案,其中我还共享 x 轴。我还添加了一个不需要GridSpec 的更简单的代码sn-p。
    • 完美!这正是我想要的。
    • 我会,但我只是收到错误 TypeError: __init__() got an unexpected keyword argument 'gridspec_kw'
    • 你有什么matplotlib版本?
    猜你喜欢
    • 1970-01-01
    • 2013-10-05
    • 2019-06-02
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    相关资源
    最近更新 更多