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

Matplotlib show()失效:图表窗口弹出1秒后自动关闭

Matplotlib图表弹出后自动关闭的解决办法

图表窗口瞬间关闭的核心原因是脚本执行到fig.show()后没有阻塞,程序直接运行结束,导致进程退出,窗口被关闭。以下是几种可行的解决方式:

方法1:替换fig.show()为plt.show()

plt.show()默认会阻塞程序运行,直到手动关闭图表窗口,是脚本模式下保持窗口打开的标准做法。修改后的代码如下:

def plot_all(levels, df):    
    fig, ax = plt.subplots(figsize=(16, 9))   
    candlestick_ohlc(ax, df.values, width=0.6, colorup='green', 
                    colordown='red', alpha=0.8)    
    date_format = mpl_dates.DateFormatter('%d %b %Y')
    ax.xaxis.set_major_formatter(date_format)    
    for level in levels:        
        plt.hlines(level[1], xmin=df['Date'][level[0]], 
                  xmax=max(df['Date']), colors='blue', linestyle='--')    
    plt.show()  # 替换fig.show()为plt.show()

方法2:为fig.show()添加阻塞参数

如果坚持使用fig.show(),可以手动设置阻塞模式:

def plot_all(levels, df):    
    fig, ax = plt.subplots(figsize=(16, 9))   
    candlestick_ohlc(ax, df.values, width=0.6, colorup='green', 
                    colordown='red', alpha=0.8)    
    date_format = mpl_dates.DateFormatter('%d %b %Y')
    ax.xaxis.set_major_formatter(date_format)    
    for level in levels:        
        plt.hlines(level[1], xmin=df['Date'][level[0]], 
                  xmax=max(df['Date']), colors='blue', linestyle='--')    
    fig.show(block=True)  # 添加block=True参数

额外注意事项

  • 如果脚本在函数执行后还有其他代码,确保没有提前退出进程的逻辑(比如sys.exit())。
  • 若使用交互式环境(如Jupyter Notebook),可以通过%matplotlib inline或%matplotlib notebook命令调整显示模式,但脚本环境下优先用上述阻塞方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:50:30