Jupyter Notebook:输出前一行的图像 [英] Jupyter Notebook: Output image in previous line

查看:301
本文介绍了Jupyter Notebook:输出前一行的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的jupyter笔记本中并排绘制一些图像。因此它可以节省一些空间用于显示。例如

I want to plot some image side by side in my jupyter notebook. So it can save some space for display. For example

这是通过

fig = plt.figure(figsize=(14,3))
ax1 = fig.add_subplot(1,3,1,projection = '3d')
ax2 = fig.add_subplot(1,3,2)
ax3 = fig.add_subplot(1,3,3)

这使得它们在一个 .png 文件中。然而,在撰写论文后,我可能只想要部分图像。例如,上一个图中的第二个或第三个。这需要我手动裁剪图像

And this makes them in one .png file. However, later on in writing the paper, I may only want part of the image. For example, the 2nd or the 3rd in previous plot. And this requires me to crop the image manually.

我能想到的一种方法是分别制作每个子图,但是将它们显示在同一条线。在Python / Jupyter Notebook中,字符串输出可以通过在上一行末尾添加逗号来实现:

One way I can think of, is to make each subplot seperately, but display them in same line. In Python/Jupyter Notebook, the string output can achieve this by adding a comma at the end of previous line:

print 5, 
print 6
# returns 5, 6
# instead of 
# 5 
# 6

我想知道Jupyter Nobebook中是否有类似的东西可以做类似的事情

I'm wondering if there is anything similar in Jupyter Nobebook, that can do something like

plot fig1,
plot fig2
# Out put [fig1],[fig2]
# instead of 
# fig1 
# fig2

输出fig1,fig2在同一行,但是单独 .png file?

Output fig1, fig2 in the same line, but in seperate .png file?

推荐答案

使用以下 align_figures()

def align_figures():
    import matplotlib
    from matplotlib._pylab_helpers import Gcf
    from IPython.display import display_html
    import base64
    from ipykernel.pylab.backend_inline import show

    images = []
    for figure_manager in Gcf.get_all_fig_managers():
        fig = figure_manager.canvas.figure
        png = get_ipython().display_formatter.format(fig)[0]['image/png']
        src = base64.encodebytes(png).decode()
        images.append('<img style="margin:0" align="left" src="data:image/png;base64,{}"/>'.format(src))

    html = "<div>{}</div>".format("".join(images))
    show._draw_called = False
    matplotlib.pyplot.close('all')
    display_html(html, raw=True)

这是一个测试:

fig1, ax1 = pl.subplots(figsize=(4, 3))
fig2, ax2 = pl.subplots(figsize=(4, 3))
fig3, ax3 = pl.subplots(figsize=(4, 3))
align_figures()

代码假定输出格式为PNG图像。

The code assumes that the output format is PNG image.

这篇关于Jupyter Notebook:输出前一行的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆