Jupyter中Plotly循环绘图仅显示最后8个,如何解决?
解决Jupyter Notebook中Plotly循环绘图超过8个后旧图消失的问题
问题原因
Jupyter Notebook默认对交互式输出(如Plotly图表)的缓存数量有限制,当输出的图表数量超过阈值(默认约8个)时,会自动清理早期生成的图表渲染资源,导致旧图无法显示。
解决方案
方案1:合并所有图表为子图统一展示
将所有两两变量的散点图整合到同一个Figure的子网格中,仅生成一个交互式输出,彻底避免缓存清理问题。同时修正原代码的语法错误(第二个for循环缺失冒号):
import plotly.subplots as sp import plotly.express as px n = len(myColumnList) # 创建对应行列数的子图网格 fig = sp.make_subplots( rows=n, cols=n, subplot_titles=[f"{x} vs {y}" for x in myColumnList for y in myColumnList] ) # 循环添加每个散点图到子图对应位置 for row, x_col in enumerate(myColumnList, start=1): for col, y_col in enumerate(myColumnList, start=1): scatter_trace = px.scatter(df, x=x_col, y=y_col).data[0] fig.add_trace(scatter_trace, row=row, col=col) # 调整布局适配子图数量 fig.update_layout( height=70*n, width=70*n, title_text="变量两两散点图矩阵", showlegend=False ) fig.show()
方案2:用IPython Display强制输出每个图表
改用IPython.display.display()替代fig.show(),强制Jupyter保留每个图表的输出,绕过默认缓存限制:
from IPython.display import display # 修正语法错误后的循环代码 for i in myColumnList: for j in myColumnList: fig = px.scatter(df, x=i, y=j) display(fig) # 强制输出每个图表
方案3:调整Jupyter输出缓存上限
临时或永久修改IPython的输出缓存大小,允许保留更多交互式输出:
- 临时生效(当前Notebook会话):
from IPython.core.interactiveshell import InteractiveShell InteractiveShell.cache_size = 100 # 设置缓存为100个输出,可按需调整 - 永久生效:
- 运行
ipython profile create生成IPython配置文件 - 找到生成的
ipython_config.py,添加或修改:c.InteractiveShell.cache_size = 100
- 运行
内容的提问来源于stack exchange,提问作者Mehmet Ates
相关产品推荐
相关产品推荐

