Matplotlib中第二次调用plt.show()无反应,是否为正常现象?
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:
Save the Figure Object
Capture the figure when you create it, then you can callshow()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()Enable Interactive Mode
Turn on matplotlib's interactive mode withplt.ion()—this keeps the plotting context alive afterplt.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()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

