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

时间:2018-03-11 09:17:42

标签: 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();

分号(&#39 ;;')应该禁止文本输出,但是当我运行第一次运行后得到的代码时:

enter image description here

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

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

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

注意:

在此问题的先前版本中,我使用了以下代码中的一些注释,但我将其更改为上面的内容以更好地显示问题。

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();

1 个答案:

答案 0 :(得分:2)

我发现了造成这种行为的原因。我用以下内容运行了我的笔记本:

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

documented here

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

InteractiveShell.ast_node_interactivity = "last_expr"

我不确定为什么会这样。