簡體   English   中英

Matplotlib 獲取子圖(軸)大小?

[英]Matplotlib get subplot (axes) size?

只是徘徊 - 如何獲得 Matplotlib 中的子圖(軸?)的大小?

如果我在https://matplotlib.org/3.1.1/api/axes_api.html中執行 Ctrl-F“大小” - 在上下文中只有一個匹配:“......具有不同的標記大小和/或.. .",所以它並沒有真正告訴我如何找到軸的大小。

說,我有與交互式調整圖形相同的代碼,並在 Matplotlib 中切換 plot 可見性?

#!/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 軸表示的子圖的大小?

有關bbox如何工作的完整說明,請參閱此處 您的每個軸 object 都適合邊界框。 您需要做的就是獲取軸邊界框的高度和寬度。 ax_h, ax_w = ax.bbox.height, ax.bbox.width

您可以使用bbox.transformed方法轉換為圖形坐標。 例如: ax_h = ax.bbox.transformed(fig.gca().transAxes).height

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM