在Jupyter笔记本中并排绘制两个matplotlib.image.AxesImage对象

时间:2017-05-26 23:16:26

标签: matplotlib jupyter-notebook

我有一个返回matplotlib.image.AxesImage对象的函数,我想在同一个图中并排绘制其中两个对象。我试过这样的事情:

fig, (ax1, ax2) = plt.subplots(ncols=2)
ax1 = function_that_returns_AxesImage(some_arguments)  # tried to reassign ax1
ax2 = function_that_returns_AxesImage(other_arguments) # tried to reassign ax2

然而,这仅产生一个带有两个空子图的图形,我想要的两个图被绘制在一列中,而不是并排(see current plots output here)。 我的问题是我必须使用function_that_returns_axes,我不知道如何将返回的图放入子图中。或者,如果我可以在Jupyter中并排显示两个数字,那也可以。

2 个答案:

答案 0 :(得分:0)

如果您无法将ax1, ax2传递给function_that_returns_axes,则可以使用以下代码:

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)

详细信息: Jupyter Notebook: Output image in previous line

答案 1 :(得分:0)

解决方案当然取决于function_that_returns_axes对图的确切含义。但是看起来,它考虑了现有的数字并返回它绘制的轴。

然后可以使用此轴并更改其位置,使其位于用户定义的网格上。网格将通过matplotlib.gridspec创建。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure()

def function_that_returns_axes(l="A"):
    ax = fig.add_subplot(111, label=l)
    ax.plot(np.random.rand(5))
    return ax

ax1 = function_that_returns_axes("A")
ax2 = function_that_returns_axes("B")

gs = gridspec.GridSpec(1,2)
ax1.set_position(gs[0].get_position(fig))
ax1.set_subplotspec(gs[0]) 

ax2.set_position(gs[1].get_position(fig))
ax2.set_subplotspec(gs[1])   

plt.show()

enter image description here

可以看出,两个轴彼此相邻,尽管它们最初是由function_that_returns_axes在彼此之上创建的。

如果函数没有返回轴,而是图像,则解决方案如下:

def function_that_returns_image(l="A"):
    ax = fig.add_subplot(111, label=l)
    im = ax.imshow(np.random.rand(5,5))
    return im

im1 = function_that_returns_image("A")  
im2 = function_that_returns_image("B")

ax1 = im1.axes
ax2 = im2.axes

# the rest being the same as above...

enter image description here