6

I use iPython notebook a lot together with matplotlib and whilst there are lots of cases when I am happy it automatically displays the images when I call imshow() there are moments when I would like to prevent that behavior.

Specifically I am looping over a very large array and generate a figure in matplotlib for each element which should be saved to disk. As part of that figure creation I have to call imshow() to draw an existing image (in my case the screenshot of a map) to the axis to later on draw additional material on top of that. Whenever I call imshow as part of the process the final figure is displayed inline in iPython notebook, how can I prevent that?

My code looks something like this:

import matplotlib as plt
fig = plt.pyplot.figure(figsize=(20,20))
im2 = plt.pyplot.imread('/some/dir/fancy-map.png')

# Magic to calculate points, x_min etc.

fig.clf()
ax = fig.gca(xlim=(x_min, x_max), ylim=(y_min, y_max))
ax.imshow(im2, extent=(4, 4.5746, 42.5448, 43.3791), aspect=1.5)
raster = ax.imshow(points, vmin = 0, vmax=maxval, extent=(x_min, x_max, y_min, y_max), aspect=1.5, origin='lower')
fig.colorbar(raster)
ax.set_title('coordinates plot')

fig.savefig("fancy-annotated-map.png", bbox_inches=0)
4

1 回答 1

4

尝试将其移动到一个函数中,并在函数的开头执行pylab.ioff()并在最后返回pylab.ion()

# Obvs add arguments so you can pass in your data and plot choices.
def make_img():
    pylab.ioff()

    import matplotlib as plt
    fig = plt.pyplot.figure(figsize=(20,20))
    im2 = plt.pyplot.imread('/some/dir/fancy-map.png')

    # Magic to calculate points, x_min etc.

    fig.clf()
    ax = fig.gca(xlim=(x_min, x_max), ylim=(y_min, y_max))
    ax.imshow(im2, extent=(4, 4.5746, 42.5448, 43.3791), aspect=1.5)
    raster = ax.imshow(points, 
                       vmin = 0, 
                       vmax=maxval, 
                       extent=(x_min, x_max, y_min, y_max), 
                       aspect=1.5, 
                       origin='lower')
    fig.colorbar(raster)
    ax.set_title('coordinates plot')
    fig.savefig("fancy-annotated-map.png", bbox_inches=0)

    pylab.ion()
  1. 这假设您仅在 IPython 中使用该函数,或者pylab始终导入该函数。最好用try...包裹except它,以便该功能可以在其他地方使用。

  2. 查看用于制作您自己的 IPython Magic 函数的模板%%%函数调用,如%cpaste)。一个很好的方法是创建你自己的魔法,比如%imnoshow或其他东西,它只包装调用的部分imshow,这样你就可以在imshow不必查看输出的情况下对输出进行内联处理。由于您的问题不涉及一般的绘图界面,而是这个特定的,所以我不会尝试在这里实现它,但希望上面的链接应该足以让您在需要时实现一些东西。

  3. 另一种方法是按照说明设置您自己的IPython 配置环境,包括拥有一些.py包含您自己的导入和辅助类定义等的特定文件。然后将您自己的特殊绘图函数放在那里,以便在启动时加载它们并在 IPython 的全局范围内可用。我强烈推荐这个有几个原因:(a)你实际上可以为你自己的辅助函数编写单元测试,如果你愿意的话,甚至可以在每次启动 IPython 时轻松地进行测试!(b) 这使您可以更轻松地进行版本控制并封装您经常需要的辅助函数的逻辑。(c) 您可以从“只是在那里”的功能中受益,而无需使其成为魔术功能或稍后将其导入。

于 2013-11-14T16:40:57.620 回答