2017-05-26 265 views
0

我有一個函數返回一個matplotlib.image.AxesImage對象,我想在同一個圖中並排繪製兩個這些對象。我想是這樣的:在Jupyter筆記本中並排繪製兩個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,我不知道如何把返回的情節放入subplots。或者,如果我可以在Jupyter中並排顯示兩個數字,那也可以起作用。

+0

我認爲我們需要對'function_that_returns_axes'的更多信息。它似乎確實考慮了代碼的某些部分,否則它不會繪製到相同的現有數字。這個功能從哪裏來?你自己寫了嗎?你能給它一個鏈接嗎? – ImportanceOfBeingErnest

+0

@ImportanceOfBeingErnest當然,我正在使用galpy庫[https://github.com/jobovy/galpy.git](https://github.com/jobovy/galpy.git)。具體功能是在galpy/galpy/potential_src/Potential.py中找到的繪圖函數。謝謝你的幫助! –

+0

我的答案是否適合你?如果是這樣的話,我不需要深入研究激情代碼。 – ImportanceOfBeingErnest

回答

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

0

如果不能通過ax1, ax2function_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