cqcn1991 cqcn1991 - 2 months ago 31
Python Question

Jupyter Notebook: Output image in previous line

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

enter image description here

This is done through

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)


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.

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


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


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

Answer

use the following 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)

Here is a test:

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

The code assumes that the output format is PNG image.