注意
前往結尾以下載完整的範例程式碼。
以程式方式控制子圖調整#
注意
此範例主要旨在展示 Matplotlib 中的一些進階概念。
如果您只是希望為標籤留下足夠的空間,則幾乎總是更簡單且足夠好地使用 Figure.subplots_adjust
手動設定子圖參數,或使用其中一種自動版面配置機制(受限版面配置指南 或 緊湊版面配置指南)。
此範例描述使用者定義的方法,讀取 Artist 大小並據此設定子圖參數。其主要目的是說明一些進階概念,例如讀取文字位置、使用邊界框和轉換,以及使用 事件。但是,如果您想要自動化版面配置並且需要比緊湊版面配置和受限版面配置更大的彈性,它也可以作為起點。
在下面,我們收集所有 y 標籤的邊界框,並將子圖的左邊框向右移動,使其為所有邊界框的聯集留下足夠的空間。
計算文字邊界框有一個問題:查詢文字邊界框 (Text.get_window_extent
) 需要一個渲染器 (RendererBase
實例) 來計算文字大小。此渲染器只有在圖形繪製後 (Figure.draw
) 才可用。
解決方案是將調整邏輯放入繪製回呼中。此函數會在圖形繪製後執行。它現在可以檢查子圖是否為文字留下足夠的空間。如果沒有,則會更新子圖參數並觸發第二次繪製。
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
fig, ax = plt.subplots()
ax.plot(range(10))
ax.set_yticks([2, 5, 7], labels=['really, really, really', 'long', 'labels'])
def on_draw(event):
bboxes = []
for label in ax.get_yticklabels():
# Bounding box in pixels
bbox_px = label.get_window_extent()
# Transform to relative figure coordinates. This is the inverse of
# transFigure.
bbox_fig = bbox_px.transformed(fig.transFigure.inverted())
bboxes.append(bbox_fig)
# the bbox that bounds all the bboxes, again in relative figure coords
bbox = mtransforms.Bbox.union(bboxes)
if fig.subplotpars.left < bbox.width:
# Move the subplot left edge more to the right
fig.subplots_adjust(left=1.1*bbox.width) # pad a little
fig.canvas.draw()
fig.canvas.mpl_connect('draw_event', on_draw)
plt.show()

參考
此範例中顯示了以下函數、方法、類別和模組的使用