2017-07-07 35 views

回答

2

該圖內的軸線相對於該圖中positionned。默認情況下你有例如數字寬度的0.125的一部分作爲左側的空間。這意味着調整圖形的大小,也會縮放軸。

您可以計算間距需要改變的程度,如果圖形重新縮放,軸的大小保持不變。新的間距需要使用fig.subplots_adjust進行設置。

import matplotlib.pyplot as plt 

def set_figsize(figw,figh, fig=None): 
    if not fig: fig=plt.gcf() 
    w, h = fig.get_size_inches() 
    l = fig.subplotpars.left 
    r = fig.subplotpars.right 
    t = fig.subplotpars.top 
    b = fig.subplotpars.bottom 
    hor = 1.-w/float(figw)*(r-l) 
    ver = 1.-h/float(figh)*(t-b) 
    fig.subplots_adjust(left=hor/2., right=1.-hor/2., top=1.-ver/2., bottom=ver/2.) 

fig, ax=plt.subplots() 

ax.plot([1,3,2]) 

set_figsize(9,7) 

plt.show() 

然後,您也可以使用此函數更改數字窗口調整大小時的子圖區參數。

import matplotlib.pyplot as plt 

class Resizer(): 
    def __init__(self,fig=None): 
     if not fig: fig=plt.gcf() 
     self.fig=fig 
     self.w, self.h = self.fig.get_size_inches() 
     self.l = self.fig.subplotpars.left 
     self.r = self.fig.subplotpars.right 
     self.t = self.fig.subplotpars.top 
     self.b = self.fig.subplotpars.bottom 

    def set_figsize(self, figw,figh): 
     hor = 1.-self.w/float(figw)*(self.r-self.l) 
     ver = 1.-self.h/float(figh)*(self.t-self.b) 
     self.fig.subplots_adjust(left=hor/2., right=1.-hor/2., top=1.-ver/2., bottom=ver/2.) 

    def resize(self, event): 
     figw = event.width/self.fig.dpi 
     figh = event.height/self.fig.dpi 
     self.set_figsize(figw,figh) 

fig, ax=plt.subplots() 

ax.plot([1,3,2]) 

r = Resizer() 
cid = fig.canvas.mpl_connect("resize_event", r.resize) 

plt.show() 

enter image description here

0

在matplotlib圖的窗口中,有一個名爲'Configure subplots'的按鈕(參見下圖,在Windows 10上使用matplotlib 1.5.2版截圖)。嘗試改變參數'左'和'右'。您也可以使用plt.subplots_adjust(left=..., bottom=..., right=..., top=..., wspace=..., hspace=...)更改這些參數。

enter image description here

+0

我不認爲有任何理由downvote這個答案。這是正確和有用的,即使它沒有提供精確的算法來設置所討論參數的值。 – ImportanceOfBeingErnest

相關問題