Spyder中Matplotlib绘图命令为何每次执行都生成新画布而非叠加?
Hey there! I get how frustrating it is when every single Matplotlib line in Spyder spits out a new figure window instead of building on the same plot—let’s get this sorted out for you.
Why This Happens
This issue almost always ties back to how Spyder’s IPython console handles Matplotlib’s interactive mode and backend settings. When interactive mode is enabled (plt.ion()), Spyder might auto-render changes after every line of code, which triggers a new window instead of updating the existing one.逐行执行代码而不是一次性运行整个脚本也会加重这个问题。
Solutions to Try
1. Adjust Spyder’s Matplotlib Backend Settings
First, let’s make sure Spyder is using a backend that supports persistent plots:
- Go to Tools > Preferences (or Settings on some systems)
- Navigate to IPython Console > Graphics
- Set the Backend option to Automatic, Qt5Agg, or Qt6Agg (avoid "Inline" if you need separate interactive windows)
- Restart Spyder to apply the changes
2. Use Matplotlib’s Object-Oriented Syntax (Most Reliable Fix)
Instead of relying on plt’s global functions, explicitly create a figure and axes object—this way you’re always modifying the same plot:
import matplotlib.pyplot as plt # Create a single figure and axes to work with fig, ax = plt.subplots() x = [1,2,3] y = [5,7,4] x2 = [1,2,3] y2 = [10,14,12] # Plot directly on the axes object ax.plot(x, y, label='First Line') ax.plot(x2, y2, label='Second Line') ax.set_xlabel('Plot Number') ax.set_ylabel('Important var') ax.set_title('Interesting Graph\nCheck it out') ax.legend() plt.show()
3. Disable Interactive Mode Temporarily
If you want to stick with the plt global functions, turn off interactive mode at the start of your script:
import matplotlib.pyplot as plt plt.ioff() # Turn off auto-rendering after each line # Rest of your original code here...
You can also run %matplotlib qt in the IPython console first—this switches to the Qt backend and disables auto-rendering until you call plt.show().
4. Run the Entire Script at Once
If you’ve been executing code line-by-line (hitting Enter after each line), try clicking Spyder’s Run File button (the green triangle in the toolbar) instead. Running the full script in one go ensures all plotting commands are applied to the same figure before it’s displayed.
内容的提问来源于stack exchange,提问作者saxonryan

