gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:20:05 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

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

(documented here)

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

InteractiveShell.ast_node_interactivity = "last_expr"

我不确定为什么会这样。

关于python - 如何在 Jupyter Notebook 的 for 循环中抑制 matplotlib 输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49218457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com