You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Matplotlib绘图在Jupyter Notebook中正常显示?

解决Jupyter Notebook中Matplotlib图像不显示的问题

核心原因与修复方案

在Jupyter环境中,fig.show()并非适配的图像显示方式,同时需要配置Matplotlib的后端渲染规则,以下是几种可行的修复方法:

方法1:添加Jupyter专属魔法命令

在代码开头加入魔法命令指定内联渲染后端,同时替换无效的显示方法:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 500)
y = np.sin(x**2)+np.cos(x)
fig, ax = plt.subplots()
ax.plot(x, y, label ='Line 1')
ax.plot(x, y - 0.6, label ='Line 2')
ax.legend()
fig.suptitle("""matplotlib.figure.Figure.show()
function Example

""", fontweight ="bold")
plt.show()
  • %matplotlib inline会让图像直接嵌入Notebook单元格,无需额外调用显示方法
  • 用跨环境通用的plt.show()替换仅适配部分交互式后端的fig.show()

方法2:检查并修改Jupyter配置

若魔法命令无效,可调整Jupyter配置文件:

  • 未生成过配置文件的话,在终端运行jupyter notebook --generate-config
  • 打开配置文件,将c.InlineBackend.figure_format设置为'retina'或'png'
  • 确认c.InteractiveShellApp.matplotlib的值为'inline'

方法3:切换Matplotlib后端(特殊环境适配)

如果上述方法均无效,尝试切换后端(需确保系统支持对应依赖):

import matplotlib
matplotlib.use('TkAgg') # 或'Qt5Agg',根据系统安装的依赖选择
import matplotlib.pyplot as plt

注意:该方法可能需要额外安装依赖库,比如Tkinter或PyQt5。

额外说明

  • Jupyter默认的内联后端不支持fig.show(),仅部分交互式后端(如Qt)可使用该方法
  • 版本兼容问题也可能导致图像不显示,可尝试更新依赖:
pip install --upgrade matplotlib jupyter

内容的提问来源于stack exchange,提问作者user3877654

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 14:55:20