如何在plt.show()后保留/恢复Matplotlib上下文以生成包含新增数据的多幅图表
plt.show() Got it, let's break down how to fix this! The core issue is that when you call plt.show() in Matplotlib, it automatically closes the current figure and clears its associated axes by default. That’s why your second plt.plot() starts fresh instead of building on the first plot’s data.
Since you want two independent figures (not an updated single plot), here are two simple, effective approaches:
Option 1: Save Your Data and Replot for the Second Figure
This is the most straightforward method—just store your first dataset so you can reuse it when creating the second figure.
import matplotlib.pyplot as plt # First figure: only show [1,2,3] data_first = [1, 2, 3] plt.plot(data_first) plt.show() # Second figure: show both datasets plt.plot(data_first) plt.plot([3, 2, 1]) plt.show()
Option 2: Use Matplotlib's Object-Oriented API (Recommended)
For more control over your plots, use Matplotlib's object-oriented interface. This lets you explicitly create and manage separate figure/axes pairs, so you never lose track of your plot context.
import matplotlib.pyplot as plt # Create first figure and axes, plot the first dataset fig1, ax1 = plt.subplots() ax1.plot([1, 2, 3]) plt.show() # Create second figure and axes, plot both datasets fig2, ax2 = plt.subplots() ax2.plot([1, 2, 3]) ax2.plot([3, 2, 1]) plt.show()
Both approaches will give you exactly what you want:
- First figure displays only the
[1,2,3]line - Second figure displays both the
[1,2,3]and[3,2,1]lines as separate plots
内容的提问来源于stack exchange,提问作者MaciejLisCK

