【发布时间】:2017-04-21 00:22:45
【问题描述】:
anumberofquestions 关于使用 matplotlib 创建“缩略图”图(即较大图的较小版本,缩略图图覆盖在原始图上)。
但是,我找不到使用 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'
有没有办法解决这个问题?
【问题讨论】:
-
你能举出一些“问题的数量......”吗?我想这会帮助其他人理解你想要达到的目标。您能否详细说明您对使用
GridSpec的要求?从代码看来,它似乎很容易被figure.subplots替换。 -
另外......如果你用
axis而不是grid_cell调用add_inset_to_axis(fig, axis, (0.675, 0.82, 0.3, 0.15))会发生什么?至少从函数的编写方式来看,这似乎是调用它的预期方式。 -
好吧,事实证明,您使用
axis而不是grid_cell是正确的,这确实有效,非常感谢。在代码中,这是基于相关函数无法访问实际轴的,我想这就是我之前没有发现这一点的原因。如果你把它写出来作为答案而不是评论,我可以给你功劳。
标签: python matplotlib plot thumbnails