【问题标题】:Setting the same axis limits for all subplots in matplotlib为 matplotlib 中的所有子图设置相同的轴限制
【发布时间】:2015-06-23 15:24:19
【问题描述】:

这个问题看起来很简单,但是我找不到pythonic的方法来解决它。我有几个(四个)子图应该具有相同的xlimylim。遍历所有子图 à la

f, axarr = plt.subplots(4)
for x in range(n):
    axarr[x].set_xlim(xval1, xval2)
    axarr[x].set_ylim(yval1, yval2)

不是最好的做事方式,尤其是对于 2x2 子图 - 这是我实际处理的。我正在寻找类似plt.all_set_xlim(xval1, xval2) 的东西。

请注意,我不希望更改任何其他内容(应分别控制刻度和标签)。

编辑:我正在使用 plt.subplots(2, 2) 包装器。按照 dienzs 的回答,我尝试了 plt.subplots(2, 2,sharex=True, sharey=True) - 几乎是正确的,但现在除了左边和底行之外,蜱虫已经消失了。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    通过matplotlib.pyplot.setp()https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.setp.html在Artist对象上设置xlimylim属性

    # Importing matplotlib.pyplot package.
    import matplotlib.pyplot as plt
    
    # Assigning 'fig', 'ax' variables.
    fig, ax = plt.subplots(2, 2)
    
    # Defining custom 'xlim' and 'ylim' values.
    custom_xlim = (0, 100)
    custom_ylim = (-100, 100)
    
    # Setting the values for all axes.
    plt.setp(ax, xlim=custom_xlim, ylim=custom_ylim)
    

    【讨论】:

    • 这里需要更多解释。这没有帮助
    【解决方案2】:

    你可以试试这个。

    #set same x,y limits for all subplots
    fig, ax = plt.subplots(2,3)
    for (m,n), subplot in numpy.ndenumerate(ax):
        subplot.set_xlim(xval1,xval2)
        subplot.set_ylim(yval1,yval2)
    

    【讨论】:

      【解决方案3】:

      如果您有多个子图,即

      fig, ax = plt.subplots(4, 2)
      

      你可以使用它。它从第一个图中得到 y 轴的限制。如果您想要其他子图,只需更改 ax[0,0] 的索引。

      plt.setp(ax, ylim=ax[0,0].get_ylim())
      

      【讨论】:

      • 这正是最佳答案所说的。
      • 不是。在此示例中,我从多个绘图中获取限制,而不是自定义范围。
      • 哦,我明白了。您将第一个情节的 ylim 扩展到其他情节。
      【解决方案4】:

      您可以使用shared axes,它将共享 x 和/或 y 限制,但允许以任何其他方式自定义轴。

      【讨论】:

      • 好吧,这仍然涉及分别为每个子图提供 sharexsharey 选项。我应该提到我正在使用plt.subplots() 包装器。现在包装器确实将sharex=True 作为可选参数,但这摆脱了轴刻度,我在文档中看不到可以轻松恢复它们的选项。当然,这个问题都是关于简单而简洁的代码。我试图避免重复的部分——想想一个 8x2 的子图或其他东西。
      【解决方案5】:

      这一点都不优雅,但它对我有用......

      fig, axes = plt.subplots(6, 3, sharex=True)
      axes[0, 0].set_xlim(right=10000) # sharex=True propagates it to all plots
      for i in range(6):
          for j in range(3):
              axes[i, j].plot('Seconds', df.columns[2+3*i+j], data=df)  # your plot instructions
      plt.subplots_adjust(wspace=.5, hspace=0.2)
      

      【讨论】:

        猜你喜欢
        • 2016-07-24
        • 2022-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-09
        • 2011-04-16
        相关资源
        最近更新 更多