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

Google Colab中plt.show()无法显示绘图问题求助

修复Google Colab中matplotlib绘图不显示的问题

核心问题分析

你代码里使用的plt.show(block=False)参数,仅适用于本地Python的桌面绘图环境,在Colab的网页交互环境中完全不兼容,这是导致绘图无法正常渲染的关键原因。另外,需要确保Colab使用正确的matplotlib后端来嵌入绘图。

具体修复方案

1. 移除无效的block=False参数

将循环内的plt.show(block=False)改为普通的plt.show(),或者调整绘图逻辑,把所有曲线绘制在同一张图后再统一显示(更高效整洁)。

2. 显式设置Colab专用绘图后端(稳妥操作)

在代码最开头添加Colab专用魔法命令,强制matplotlib使用内嵌后端渲染:

%matplotlib inline

3. 优化后的完整代码

修复后的代码同时调整了绘图逻辑,为不同步数的曲线添加标签,方便区分,且移除了重复的matplotlib导入:

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

k      = 1.0 # Spring constant
m      = 1.0 # Mass
cycles = 2.0 # No. of periods to integrate over
x0     = 1.0 # Initial displacement
v0     = 0.0 # Initial velocity

def leapfrog( steps ):
    """Solve the simple harmonic motion equations for several oscillation cycles,
    assuming that the mass (m) and spring constant (k) are defined in the
    global space.
    """
    omega = (k/m)**0.5
    delta = 2.0*cycles*np.pi/omega/steps
    x     = np.empty( steps+1 )
    v     = np.empty( steps+1 )
    t     = np.empty( steps+1 )
    t[0]  = 0.0
    x[0]  = x0
    v[0]  = v0 + 0.5*delta*x[0]*omega**2.0
    for i in range(steps):
        t[i+1] = t[i] + delta
        v[i+1] = v[i] - omega**2*delta*x[i]
        x[i+1] = x[i] + delta*v[i+1]
    return t, x, v

def l2_error_norm( t , x ):
    """Calculate the L2 relative error norm."""
    steps  = len( x ) - 1
    omega  = (k/m)**0.5
    l2_err = 0.0
    l2     = 0.0
    for i in range(steps):
        x_exact = x0*np.cos( omega*t[i] )
        l2_err += (x[i] - x_exact)**2.0
        l2     += x[i]**2.0
    return (l2_err/l2)**0.5

# 循环计算并绘制简谐运动曲线
n        = 14
steps    = 8
l2_error = np.empty( n )
delta    = np.empty( n )

plt.figure()
for i in range(0,n):
    t, x, v     = leapfrog( steps )
    delta[i]    = (k/m)**0.5*(t[1]-t[0])
    l2_error[i] = l2_error_norm( t , x )
    plt.plot( t , x, label=f"步数: {steps}" )
    steps *= 2

plt.xlabel("时间")
plt.ylabel("位移")
plt.title("蛙跳法求解简谐运动")
plt.legend()
plt.show()

# 绘制误差收敛图
plt.figure()
plt.loglog( delta , l2_error , 'o', label="蛙跳法误差" )
plt.loglog( delta , l2_error[0]*(delta/delta[0])**1.0, label="O(Δt)" )
plt.loglog( delta , l2_error[0]*(delta/delta[0])**2.0, label="O(Δt²)" )
plt.loglog( delta , l2_error[0]*(delta/delta[0])**3.0, label="O(Δt³)" )
plt.xlabel("Δt·ω")
plt.ylabel("L2相对误差")
plt.title("蛙跳法收敛性分析")
plt.legend()
plt.show()

4. 额外注意点

  • 无需重复导入matplotlib.pyplot,原代码中的import matplotlib.pyplot是冗余操作,保留import matplotlib.pyplot as plt即可。
  • Colab默认已预装matplotlib和numpy,无需额外安装依赖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 22:16:16