簡體   English   中英

防止情節顯示在 jupyter notebook 中

[英]prevent plot from showing in jupyter notebook

如何防止在 Jupyter 筆記本中顯示特定圖? 我在筆記本中有幾個圖,但我希望將其中的一個子集保存到一個文件中,而不是在筆記本上顯示,因為這會大大減慢速度。

Jupyter 筆記本的最小工作示例是:

%matplotlib inline 
from numpy.random import randn
from matplotlib.pyplot import plot, figure
a=randn(3)
b=randn(3)
for i in range(10):
    fig=figure()
    plot(b)
    fname='s%03d.png'%i
    fig.savefig(fname)
    if(i%5==0):
        figure()
        plot(a)

如您所見,我有兩種類型的圖,a 和 b。 我想要繪制和顯示 a,我不想顯示 b 圖,我只想將它們保存在一個文件中。 希望這會加快速度,並且不會用我不需要看到的數字污染我的筆記本。

感謝您的時間

也許只是清除軸,例如:

fig= plt.figure()
plt.plot(range(10))
fig.savefig("save_file_name.pdf")
plt.close()

不會在內inline模式下繪制輸出。 我不知道是否真的在清除數據。

我能夠通過使用該功能關閉交互模式來阻止我的數字顯示

plt.ioff()

為了防止來自 jupyter notebook 單元的任何輸出,您可以使用以下命令啟動單元

%%capture

這在此處顯示的所有其他方法失敗的情況下可能很有用。

從 IPython 6.0 開始,還有另一個選項可以關閉內聯輸出(暫時或永久)。 這已在此拉取請求中引入。

您將使用“agg”后端不顯示任何內聯輸出。

%matplotlib agg

似乎如果您先激活了內聯后端,則需要調用兩次才能生效。

%matplotlib agg
%matplotlib agg

這是它在行動中的樣子

不過,我是初學者,當您不想通過以下方式在筆記本中看到輸出時,會關閉內聯模式:

%matplotlib auto

或者:

%matplotlib

使用它回來:

%matplotlib inline

更好的解決方案是使用:

plt.ioff()

這表示內聯模式關閉。

希望能幫助到你。

在 Jupyter 6.0 上,我使用以下代碼片段選擇性地不顯示 matplot lib 圖形。

import matplotlib as mpl

...

backend_ =  mpl.get_backend() 
mpl.use("Agg")  # Prevent showing stuff

# Your code

mpl.use(backend_) # Reset backend

基於@importanceofbeingernest 的答案,人們可​​能會在循環中調用某個函數,並且在每次迭代時都想要渲染一個圖。 但是,在每個圖之間,您可能想要渲染其他內容。

具體來說:

  1. 迭代 ID 列表
  2. 調用一個函數,以便為每個“ID”呈現一個圖
  3. 在每個情節之間,渲染一些降價

# <cell begins>
def render(id):
   fig, axes = plt.subplots(2, 1)
   plt.suptitle(f'Metrics for {id}')

   df.ColA.plot.bar(ax=axes[0])
   df.ColB.plot.bar(ax=axes[1])

   return fig

# <cell ends>

# -------------------------------------

# <cell begins>
%matplotlib agg

for id in df.ID.value_counts().index:
   fig = render(id)

   display(fig)
   display(Markdown('---'))

# <cell ends>

暫無
暫無

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

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