Jupyter中运行绘图代码时禁用图表显示,仅保存图表到对象用于后续写入Excel的方法
Jupyter中运行绘图代码时禁用图表显示,仅保存图表到对象用于后续写入Excel的方法
嗨,我来帮你解决这个问题!你遇到的情况是Jupyter Notebook的默认行为导致的——当你用matplotlib或seaborn绘制图表后,它会自动渲染并显示当前的Figure对象。要实现“只存图不显示”的需求,有两个简单好用的办法:
方法一:保存图表后关闭Figure对象
这是最直接的方式,在你把图表保存到BytesIO缓冲区之后,调用plt.close()关闭当前的绘图对象,这样Jupyter就不会把它渲染出来了。
另外要注意,你的原始代码里缺少几个必要的导入语句,我已经帮你补全了,避免运行报错:
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from io import BytesIO df = pd.DataFrame({'Label': ['a', 'b', 'c', 'd', 'e', 'f'], 'Val': [np.random.rand() for _ in range(6)], }) sns.set_style('whitegrid') plt.figure(figsize=(6, 4)) sns.barplot(df, x='Label', y='Val', color='steelblue') plt.xlabel('Bin', fontsize=9) plt.ylabel('Value', fontsize=9) plt.title('Trend', fontsize=11) plt.tight_layout() all_plots = dict() buffer = BytesIO() plt.savefig(buffer, format='png', bbox_inches='tight') # 关键:关闭当前Figure,阻止Jupyter显示 plt.close() buffer.seek(0) all_plots['p1'] = buffer
方法二:切换到无显示的绘图后端
如果你需要在整个Notebook会话中都禁用图表显示(比如要批量生成很多图表),可以在导入matplotlib之后,切换到Agg后端——这个后端专门用于离线绘图,只负责保存图表,不会产生任何显示输出。
import numpy as np import pandas as pd import matplotlib.pyplot as plt # 切换到无显示后端 plt.switch_backend('Agg') import seaborn as sns from io import BytesIO df = pd.DataFrame({'Label': ['a', 'b', 'c', 'd', 'e', 'f'], 'Val': [np.random.rand() for _ in range(6)], }) sns.set_style('whitegrid') plt.figure(figsize=(6, 4)) sns.barplot(df, x='Label', y='Val', color='steelblue') plt.xlabel('Bin', fontsize=9) plt.ylabel('Value', fontsize=9) plt.title('Trend', fontsize=11) plt.tight_layout() all_plots = dict() buffer = BytesIO() plt.savefig(buffer, format='png', bbox_inches='tight') buffer.seek(0) all_plots['p1'] = buffer
如果之后你又需要恢复图表显示,只需要执行plt.switch_backend('inline')即可(这是Jupyter默认的显示后端)。
备注:内容来源于stack exchange,提问作者Abhishek Jain
相关产品推荐
相关产品推荐

