matplotlib GridSpec

时间:2016-12-06 11:18:20

标签: python matplotlib plot thumbnails

有关于使用matplotlib创建“缩略图”的a number of questions(即较大版本的较小版本,其中缩略图重叠)到原来的)。

但是,我找不到使用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'

有解决方法吗?

1 个答案:

答案 0 :(得分: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))