你如何在 Jupyter Notebook 的 for 循环中抑制 matplotlib 输出?

voy*_*ger 3 python matplotlib jupyter-notebook

我正在遍历 DataFrame 列名称列表以在 Jupyter Notebook 中使用 matplotlib.pyplot 创建条形图。每次迭代,我都使用列来对条进行分组。像这样:

%matplotlib inline

import pandas as pd
from matplotlib import pyplot as plt


# Run all output interactively
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"


df = pd.DataFrame({'col1': ['A', 'B', 'C'], 'col2': ['X', 'Y', 'Z'], 'col3': [10, 20, 30]})

#This DOES NOT suppress output
cols_to_plot = ['col1', 'col2']
for col in cols_to_plot:
    fig, ax = plt.subplots()
    ax.bar(df[col], df['col3'])
    plt.show();
Run Code Online (Sandbox Code Playgroud)

分号 (';') 应该抑制文本输出,但是当我运行代码时,在第一次运行之后:

在此处输入图片说明

如果我在for循环外运行类似的代码段,它会按预期工作 - 以下内容成功抑制了输出:

# This DOES suppress output
fig, ax = plt.subplots()
ax.bar(df['col1'], df['col3'])
plt.show();
Run Code Online (Sandbox Code Playgroud)

循环时如何抑制此文本输出?


笔记:

在此问题的先前版本中,我使用了一些评论所引用的以下代码,但我将其更改为上述代码以更好地显示问题。

cols_to_boxplot = ['country', 'province']
for col in cols_to_boxplot:
    fig, ax = plt.subplots(figsize = (15, 10))
    sns.boxplot(y=wine['log_price'], x=wine[col])
    labels = ax.get_xticklabels()
    ax.set_xticklabels(labels, rotation=90);
    ax.set_title('log_price vs {0}'.format(col))
    plt.show();
Run Code Online (Sandbox Code Playgroud)

voy*_*ger 6

我发现是什么导致了这种行为。我使用以下命令运行我的笔记本:

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
Run Code Online (Sandbox Code Playgroud)

此处记录

这具有在循环绘图时不抑制 matplotlib 输出的效果。但是,如原始帖子中所述,它确实不在循环内时按预期抑制了输出。无论如何,我通过像这样“撤消”我上面的代码来解决这个问题:

InteractiveShell.ast_node_interactivity = "last_expr"
Run Code Online (Sandbox Code Playgroud)

我不确定为什么会发生这种情况。