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

如何让Matplotlib绘制的多幅图表分别保存为独立图形?

解决Matplotlib绘图叠加问题,生成独立图表

你的问题出在Matplotlib默认会在同一个画布(figure)上继续绘图,未重置画布导致图形叠加。以下三种方法可实现生成独立图表:

方法一:每次绘图后清除当前画布

在调用plt.savefig()后,用plt.clf()清除当前画布的所有元素,确保下次绘图在空白画布上进行。

修改后的代码:

import matplotlib.pyplot as plt
import numpy as np

# 创建第一幅散点图
x = np.loadtxt("combined_data.txt")[:,0]
y = np.loadtxt("combined_data.txt")[:,1]

plt.plot(x, y, "o")
plt.ylabel("Verbal")
plt.xlabel("Quantitative")

plt.savefig("scores_plot.png")
plt.clf()  # 清除当前画布


# 创建第二幅散点图
y_quant = np.loadtxt("combined_data.txt")[:,0]
x_quant = np.loadtxt("admit_data.txt")[:]

plt.plot(x_quant, y_quant, "o")
plt.ylabel("Quantitative")
plt.xlabel("Admission")

plt.savefig("quant.png")
plt.clf()  # 清除当前画布

# 创建第三幅散点图
y_verb = np.loadtxt("combined_data.txt")[:,1]
x_verb = np.loadtxt("admit_data.txt")[:]

plt.plot(x_verb, y_verb, "o")
plt.ylabel("Verbal")
plt.xlabel("Admission")

plt.savefig("verbal.png")

方法二:每次绘图前创建新画布

在每个绘图块开始前调用plt.figure(),强制生成新的空白画布,后续绘图会绑定到这个新画布。

修改后的代码:

import matplotlib.pyplot as plt
import numpy as np

# 创建第一幅散点图
plt.figure()  # 生成新画布
x = np.loadtxt("combined_data.txt")[:,0]
y = np.loadtxt("combined_data.txt")[:,1]

plt.plot(x, y, "o")
plt.ylabel("Verbal")
plt.xlabel("Quantitative")

plt.savefig("scores_plot.png")


# 创建第二幅散点图
plt.figure()  # 生成新画布
y_quant = np.loadtxt("combined_data.txt")[:,0]
x_quant = np.loadtxt("admit_data.txt")[:]

plt.plot(x_quant, y_quant, "o")
plt.ylabel("Quantitative")
plt.xlabel("Admission")

plt.savefig("quant.png")

# 创建第三幅散点图
plt.figure()  # 生成新画布
y_verb = np.loadtxt("combined_data.txt")[:,1]
x_verb = np.loadtxt("admit_data.txt")[:]

plt.plot(x_verb, y_verb, "o")
plt.ylabel("Verbal")
plt.xlabel("Admission")

plt.savefig("verbal.png")

方法三:使用面向对象式绘图(推荐)

Matplotlib官方推荐使用面向对象方式,明确创建Figure和Axes对象,每个绘图对应独立的坐标轴,从根源上避免叠加问题,也便于后续精细化调整图表。

修改后的代码:

import matplotlib.pyplot as plt
import numpy as np

# 创建第一幅散点图
fig1, ax1 = plt.subplots()
x = np.loadtxt("combined_data.txt")[:,0]
y = np.loadtxt("combined_data.txt")[:,1]

ax1.plot(x, y, "o")
ax1.set_ylabel("Verbal")
ax1.set_xlabel("Quantitative")

fig1.savefig("scores_plot.png")


# 创建第二幅散点图
fig2, ax2 = plt.subplots()
y_quant = np.loadtxt("combined_data.txt")[:,0]
x_quant = np.loadtxt("admit_data.txt")[:]

ax2.plot(x_quant, y_quant, "o")
ax2.set_ylabel("Quantitative")
ax2.set_xlabel("Admission")

fig2.savefig("quant.png")

# 创建第三幅散点图
fig3, ax3 = plt.subplots()
y_verb = np.loadtxt("combined_data.txt")[:,1]
x_verb = np.loadtxt("admit_data.txt")[:]

ax3.plot(x_verb, y_verb, "o")
ax3.set_ylabel("Verbal")
ax3.set_xlabel("Admission")

fig3.savefig("verbal.png")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 16:32:48