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

Matplotlib中第二次调用plt.show()无反应,是否为正常现象?

Why plt.show() Doesn't Work the Second Time in REPL?

Hey there! This is totally normal behavior for matplotlib in a REPL environment—here's why it happens and how you can work around it:

The Root Cause

When you call plt.show() for the first time, matplotlib renders the current figure and then clears the entire plotting context (the figure and axes objects) by default. So by the time you run plt.show() again, there's no existing plot data left to display—hence nothing pops up.

Also, quick note: I spotted a tiny typo in your pop list—6,127 should be 6127 (the comma is causing it to be treated as two separate values, which would break your plot entirely!). Fix that first to make sure your initial plot works correctly.

Fixes to Repeat Plot Displays

Here are a few straightforward ways to show your plot multiple times without retyping the entire plt.plot() call:

  1. Save the Figure Object
    Capture the figure when you create it, then you can call show() on that object whenever you want:

    import matplotlib.pyplot as plt
    year = [1500, 1600, 1700, 1800, 1900, 2000]
    pop = [458, 580, 682, 1000, 1650, 6127]  # Fixed the comma issue
    
    # Save the figure reference
    fig = plt.figure()
    plt.plot(year, pop)
    plt.show()  # First display
    
    # Show it again later
    fig.show()
    
  2. Enable Interactive Mode
    Turn on matplotlib's interactive mode with plt.ion()—this keeps the plotting context alive after plt.show(), so you can redraw or re-display plots without re-creating them:

    import matplotlib.pyplot as plt
    plt.ion()  # Turn on interactive mode
    
    year = [1500, 1600, 1700, 1800, 1900, 2000]
    pop = [458, 580, 682, 1000, 1650, 6127]
    
    plt.plot(year, pop)
    plt.show()  # Window stays open, context isn't cleared
    
    # To show again later (or update the plot), you can use:
    plt.draw()
    # Or if the window was closed, re-show with:
    plt.show()
    
  3. Wrap Plotting in a Function
    If you want to easily re-run the plotting code, wrap it in a function—this avoids repeating lines manually:

    import matplotlib.pyplot as plt
    
    def plot_population():
        year = [1500, 1600, 1700, 1800, 1900, 2000]
        pop = [458, 580, 682, 1000, 1650, 6127]
        plt.plot(year, pop)
        plt.show()
    
    plot_population()  # First display
    plot_population()  # Second display (works perfectly)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:26:52