Matplotlib如何获取子图(轴)的大小?

3
只是想知道 - 如何在Matplotlib中获取子图(轴)的大小?
如果我在https://matplotlib.org/3.1.1/api/axes_api.html中使用Ctrl-F搜索“size” - 只有一个匹配项,上下文为:“... with varying marker size and/or ...”,所以它并没有真正告诉我如何找到轴的大小。
比如,我有与Interactively resize figure and toggle plot visibility in Matplotlib?中相同的代码。
#!/usr/bin/env python3

import matplotlib
print("matplotlib.__version__ {}".format(matplotlib.__version__))
import matplotlib.pyplot as plt
import numpy as np

default_size_inch = (9, 6)
showThird = False

def onpress(event):
  global fig, ax1, ax2, ax3, showThird
  if event.key == 'x':
    showThird = not showThird
    if showThird:
      fig.set_size_inches(default_size_inch[0]+3, default_size_inch[1], forward=True)
      plt.subplots_adjust(right=0.85) # leave a bit of space on the right
      ax3.set_visible(True)
      ax3.set_axis_on()
    else:
      fig.set_size_inches(default_size_inch[0], default_size_inch[1], forward=True)
      plt.subplots_adjust(right=0.9) # default
      ax3.set_visible(False)
      ax3.set_axis_off()
    fig.canvas.draw()


def main():
  global fig, ax1, ax2, ax3
  xdata = np.arange(0, 101, 1) # 0 to 100, both included
  ydata1 = np.sin(0.01*xdata*np.pi/2)
  ydata2 = 10*np.sin(0.01*xdata*np.pi/4)

  fig = plt.figure(figsize=default_size_inch, dpi=120)
  ax1 = plt.subplot2grid((3,3), (0,0), colspan=2, rowspan=2)
  ax2 = plt.subplot2grid((3,3), (2,0), colspan=2, sharex=ax1)
  ax3 = plt.subplot2grid((3,3), (0,2), rowspan=3)

  ax3.set_visible(False)
  ax3.set_axis_off()

  ax1.plot(xdata, ydata1, color="Red")
  ax2.plot(xdata, ydata2, color="Khaki")

  fig.canvas.mpl_connect('key_press_event', lambda event: onpress(event))
  plt.show()


# ENTRY POINT
if __name__ == '__main__':
  main()

如何找到由ax1和ax2轴表示的子图的大小?

1
Matplotlib图形有许多坐标系。您想知道哪个坐标系的轴尺寸? - undefined
感谢@PaulBrodersen - 我猜,我希望在图形方面既有"相对"(即"figure"),也有"绝对"(即"figure-inches")的信息,因为我想要这些信息来进行子图的进一步缩放/调整尺寸。 - undefined
4
ax.get_position() 返回相对于图形坐标系的位置。将这些数字除以英寸单位的图形大小(fig.get_size_inches())即可得到位置的英寸表示。 - undefined
这个链接可以帮到你吗?它解释了如何确定Matplotlib图表的轴尺寸(以像素为单位)。 - undefined
1个回答

4
完整解释的工作原理,请参考此处。每个轴对象都适合于一个边界框中。您需要做的就是获取轴边界框的高度和宽度。 ax_h,ax_w = ax.bbox.height,ax.bbox.width 您可以使用方法转换为图形坐标。例如: ax_h = ax.bbox.transformed(fig.gca().transAxes).height

4
请解释你的答案是如何工作的,你具体做了什么。这会鼓励提问者复制并粘贴答案,而不理解解决方案的含义。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接