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

如何在plt.show()后保留/恢复Matplotlib上下文以生成包含新增数据的多幅图表

Solution to Preserve Plot Context After 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()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 12:19:08