防止在木星笔记本上显示阴谋

如何防止特定情节出现在 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 图被显示出来,我只希望它们被保存在一个文件中。希望这样可以加快速度,不会让我的笔记本上出现我不需要看到的数字。

打扰了

85659 次浏览

Perhaps just clear the axis, for example:

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

will not plot the output in inline mode. I can't work out if is really clearing the data though.

I was able to prevent my figures from displaying by turning interactive mode off using the function

plt.ioff()

To prevent any output from a jupyter notebook cell you may start the cell with

%%capture

This might be usefull in cases all other methods shown here fail.

I'm a beginner though,off the inline mode when you don't want to see the output in your notebook by:

%matplotlib auto

or:

%matplotlib

to use it back:

%matplotlib inline

more better solution would be to use:

plt.ioff()

which says inline mode off.

hope it helps.

From IPython 6.0 on, there is another option to turn the inline output off (temporarily or persistently). This has been introduced in this pull request.

You would use the "agg" backend to not show any inline output.

%matplotlib agg

It seems though that if you had activated the inline backend first, this needs to be called twice to take effect.

%matplotlib agg
%matplotlib agg

Here is how it would look in action

On Jupyter 6.0, I use the following snippet to selectively not display the matplot lib figures.

import matplotlib as mpl


...


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


# Your code


mpl.use(backend_) # Reset backend

Building off @importanceofbeingernest's answer, one may call some function in a loop, and at each iteration, want to render a plot. However, between the each plot, you may want to render additional stuff.

Concretely:

  1. Iterate a list of IDs
  2. Call a function so a plot is rendered for each "ID"
  3. Between each plot, render some markdown

# <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>