簡體   English   中英

使用圖形句柄指定在 jupyter 中呈現輸出 matplotlib 圖形的位置

[英]Specify where in output matplotlib figures are rendered in jupyter using figure handles

在使用 matplotlib 時,對我來說一個常見的模式是在一個函數中計算,返回它,然后讓調用者決定用它做什么(渲染到屏幕,保存到文件等等)。

在 jupyter notebook 中,我想循環調用這樣的函數,並確保圖形輸出是有序的。 在這個答案https://stackoverflow.com/a/53450873/4050510 中,我們了解到plt.show()可以幫助我們處理圖像。 該答案的重寫是:

# cell 1
%matplotlib inline
import matplotlib.pyplot as plt
def make_figure(i):
    f = plt.figure(i)
    plt.plot([1,i,3])
    return f
#cell 2
for i in range(3):
    f = make_figure(i)
    print(i)
    plt.show()

上面的代碼確實有效。 問題是如果我想先創建所有圖形,然后按選定的順序渲染它們,解決方案就會崩潰。 plt.show()將同時渲染所有打開的圖形。

#cell 3
fs = [(i,make_figure(i)) for i in range(3)]
for i,f in fs:
    print(i)
    plt.show()

要進行的自然修改是將plt.show()更改為f.show() 在 jupyter notebook 之外,這將很好地解決問題。

# cell 4
fs = [(i,make_figure(i)) for i in range(3)]
for i,f in fs:
    print(i)
    f.show()

這不起作用,引發UserWarning: Matplotlib is currently using module://ipykernel.pylab.backend_inline, which is a non-GUI backend, so cannot show the figure.

這種行為差異的解釋是什么? 給定一組圖形句柄,如何以選定的順序呈現 matplotlib 圖形?

figure.show()只能在已經運行事件循環的交互式后端中使用。

在帶有inline后端的 jupyter notebook 中,您沒有事件循環。 然而,類似於Matplotlib - 使用 plt.imshow() 時序列關閉,並且這個答案你可以只做后端也會做的事情,即調用display(figure)

單元格 1

%matplotlib inline
import matplotlib.pyplot as plt
from IPython.display import display

def make_figure(i):
    f = plt.figure(i)
    plt.plot([1,i,3])
    return f

單元格 2

%%capture

fs = [(i,make_figure(i)) for i in range(3)]

單元格 3

for i, f in fs[::-1]:
    display(f)

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM