2016-12-06 42 views
1

縮圖曲線有上SO是anumberofquestions有關創建與matplotlib「縮略圖」曲線(即較小版本的較大小區,其中所述縮略圖情節被疊加到原始的)。與matplotlib GridSpec

但是,我找不到一個方法來與GridSpec地塊做到這一點。我知道這是因爲來自GridSpec的軸無法轉換(即調整大小和轉換)。

這裏是重現該問題的完整的腳本:

import matplotlib 
from matplotlib import gridspec, pyplot 
from matplotlib.backends.backend_pdf import PdfPages 

def add_inset_to_axis(figure, axis, rect): 
    left, bottom, width, height = rect 
    def transform(coord): 
     return figure.transFigure.inverted().transform(
      axis.transAxes.transform(coord)) 
    fig_left, fig_bottom = transform((left, bottom)) 
    fig_width, fig_height = transform([width, height]) - transform([0, 0]) 
    return figure.add_axes([fig_left, fig_bottom, fig_width, fig_height]) 

def main(): 
    pdf = PdfPages('example.pdf') 
    fig = pyplot.figure() 
    n_rows, n_cols = 2, 2 
    x_range = (-100, 100) 
    outer_grid = gridspec.GridSpec(n_rows, n_cols) 
    index, row, col = 0, 0, 0 
    while index < n_rows * n_cols: 
     data = [x for x in xrange(*x_range)] 
     grid_cell = outer_grid[row, col] 
     axis = pyplot.subplot(grid_cell) 
     axis.plot(range(*x_range), data) 
     inset = add_inset_to_axis(fig, grid_cell, (0.675, 0.82, 0.3, 0.15)) 
     inset.plot(range(0, 10), data[0:10]) 
     col += 1 
     if col == 2: 
      col = 0 
      row += 1 
     index = row * 2 + col 
    pdf.savefig(fig) 
    pdf.close() 

if __name__ == '__main__': 
    print('Using matplotlib version %s' % matplotlib.__version__) 
    main() 

輸出:

Using matplotlib version 1.5.1 
Traceback (most recent call last): 
    File "stackoverflow_inset.py", line 38, in <module> 
    main() 
    File "stackoverflow_inset.py", line 26, in main 
    inset = add_inset_to_axis(fig, grid_cell, (0.675, 0.82, 0.3, 0.15)) 
    File "stackoverflow_inset.py", line 10, in add_inset_to_axis 
    fig_left, fig_bottom = transform((left, bottom)) 
    File "stackoverflow_inset.py", line 9, in transform 
    axis.transAxes.transform(coord)) 
AttributeError: 'SubplotSpec' object has no attribute 'transAxes' 

有沒有解決的辦法?

+0

你能舉一些「問題的數量......」?我想這會幫助別人理解你想要達到的目標。你還可以詳細瞭解你使用'GridSpec'的要求嗎?從代碼看來,它可以很容易地被'figure.subplots'取代。 – ImportanceOfBeingErnest

+0

另外..如果你用'axis'而不是'grid_cell'調用'add_inset_to_axis(fig,axis,(0.675,0.82,0.3,0.15))'會發生什麼?至少從函數的編寫方式來看,這似乎是調用它的預期方式。 – ImportanceOfBeingErnest

+0

嗯,事實證明你是正確的使用'axis'而不是'grid_cell',這是行得通的,非常感謝。在代碼中,這是基於相關函數無法訪問實際軸的,我想這就是爲什麼我之前沒有發現這一點。如果你把它寫成答案而不是評論,我可以給你信任。 – snim2

回答

1

從函數定義add_inset_to_axis(figure, axis, rect)看來,第二個參數實際上應該是matplotlib.axes實例。的

所以不是給grid_cell作爲一個參數,一個應該使用axis

inset = add_inset_to_axis(fig, axis, (0.675, 0.82, 0.3, 0.15))