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

如何在代码末尾批量单独保存所有Matplotlib绘图且不修改原有代码?

How to Batch Save All Matplotlib Plots at the End Without Modifying Previous Code

Absolutely! You don’t need to tweak your existing plotting code at all, and you don’t even have to run it once first to figure out how many plots were generated. Matplotlib automatically tracks every Figure object you create behind the scenes, so we can leverage that to batch-save all your plots in one go.

Here’s the straightforward solution:

Add this block of code at the very end of your script, right after all your existing plotting code:

import matplotlib.pyplot as plt

# --- Your original plotting code goes here (no changes needed!) ---
# Example:
# plt.plot([1, 2, 3])
# plt.figure()
# plt.scatter([4,5,6], [7,8,9])
# ... any number of plots you generate ...

# --- Batch save code starts here ---
# Get a list of all figure objects Matplotlib is tracking
all_figures = plt.get_figures()

# Loop through each figure and save it with a sequential filename
for idx, fig in enumerate(all_figures):
    fig.savefig(f'test{idx}.png')
    # Optional: Close the figure to free up memory (good for large numbers of plots)
    plt.close(fig)

How this works:

  • plt.get_figures() grabs every Figure instance you’ve created with your original code—no need to hardcode or pre-calculate the number of plots.
  • The enumerate() function gives us a sequential index (idx) for each plot, so we can name files test0.png, test1.png, ..., testN-1.png where N is the total number of plots.
  • If you prefer working with figure numbers instead of direct objects, you can use plt.get_fignums() to get a list of figure IDs, then fetch each figure with plt.figure(fig_num):
figure_ids = plt.get_fignums()
for idx, fig_id in enumerate(figure_ids):
    fig = plt.figure(fig_id)
    fig.savefig(f'test{idx}.png')
    plt.close(fig)

Key benefits:

  • Zero changes required to your existing plotting code—just append the batch save block.
  • Automatically adapts to any number of plots you generate, whether it’s 10, 50, or more.
  • No need to run your code once first to count plots; Matplotlib gives us that info directly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:11:48