如何在Jupyter Notebook中保存ImageGrid且不显示图像?
解决Jupyter Notebook中保存ImageGrid不显示图形的问题
有两种简单方法可以实现保存ImageGrid但不在Notebook中显示图形:
方法1:保存后关闭当前图形
在调用plt.savefig()之后添加plt.close(fig)语句,关闭创建的图形对象,这样Notebook就不会渲染显示该图形。修改后的函数代码如下:
from mpl_toolkits.axes_grid1 import ImageGrid def save_img(hists,path): fig = plt.figure(figsize=(8, 8)) grid = ImageGrid(fig, 111, # similar to subplot(111) nrows_ncols=(16, 4), # creates 16x4 grid of axes axes_pad=0.1, # pad between axes in inch. ) for ax, im in zip(grid, hists): # Iterating over the grid returns the Axes. ax.set_xticks([]),ax.set_yticks([]) ax.margins(x=0,y=0) ax.imshow(im) plt.savefig(f'{path}.jpg',bbox_inches='tight') plt.close(fig) # 关闭图形,避免在Notebook中显示
这种方法仅针对当前图形生效,不会影响Notebook中其他需要显示的绘图操作,灵活性更高。
方法2:全局设置非交互式后端
如果你的Notebook会话中所有绘图都只需要保存、不需要显示,可以在导入matplotlib.pyplot之前设置使用非交互式后端Agg:
import matplotlib matplotlib.use('Agg') # 设置非交互式后端,仅用于保存图形 import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import ImageGrid def save_img(hists,path): fig = plt.figure(figsize=(8, 8)) grid = ImageGrid(fig, 111, # similar to subplot(111) nrows_ncols=(16, 4), # creates 16x4 grid of axes axes_pad=0.1, # pad between axes in inch. ) for ax, im in zip(grid, hists): # Iterating over the grid returns the Axes. ax.set_xticks([]),ax.set_yticks([]) ax.margins(x=0,y=0) ax.imshow(im) plt.savefig(f'{path}.jpg',bbox_inches='tight')
这种方式会全局禁用图形显示,适合全程批量保存图片、不需要查看绘图效果的场景。
内容的提问来源于stack exchange,提问作者Talha Anwar
相关产品推荐
相关产品推荐

