[英]Changing matplotlib subplot size/position after axes creation
是否可以在創建軸后設置matplotlib子圖的大小/位置? 我知道我能做到:
import matplotlib.pyplot as plt
ax = plt.subplot(111)
ax.change_geometry(3,1,1)
把軸放在三排的頂行。 但是我想讓軸跨越前兩排。 我試過這個:
import matplotlib.gridspec as gridspec
ax = plt.subplot(111)
gs = gridspec.GridSpec(3,1)
ax.set_subplotspec(gs[0:2])
但軸仍然填滿了整個窗口。
為清晰起見,我想更改現有軸實例的位置,而不是在創建它時設置它。 這是因為每次添加數據時都會修改軸的范圍(使用cartopy在地圖上繪制數據)。 地圖可能變得高而窄,或短而寬(或介於兩者之間)。 因此,在繪圖功能之后將決定網格布局。
感謝Molly指出我正確的方向,我有一個解決方案:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure()
ax = fig.add_subplot(111)
gs = gridspec.GridSpec(3,1)
ax.set_position(gs[0:2].get_position(fig))
ax.set_subplotspec(gs[0:2]) # only necessary if using tight_layout()
fig.add_subplot(gs[2])
fig.tight_layout() # not strictly part of the question
plt.show()
您可以使用subplot2grid的rowspan
參數創建一個帶有一個子圖的圖形,該子圖跨越兩行和一個跨越一行的子圖:
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = plt.subplot2grid((3,1), (0,0), rowspan=2)
ax2 = plt.subplot2grid((3,1), (2,0))
plt.show()
如果要在創建后更改子圖大小和位置,可以使用set_position方法。
ax1.set_position([0.1,0.1, 0.5, 0.5])
你不需要這個來創建你描述的數字。
您可以通過使用fig.tight_layout()
來避免ax.set_position()
,而不是重新計算新的gridspec:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# create the first axes without knowing of further subplot creation
fig, ax = plt.subplots()
ax.plot(range(5), 'o-')
# now update the existing gridspec ...
gs = gridspec.GridSpec(3, 1)
ax.set_subplotspec(gs[0:2])
# ... and recalculate the positions
fig.tight_layout()
# add a new subplot
fig.add_subplot(gs[2])
fig.tight_layout()
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.