如何将多个图显示为单独的图形? [重复]

问题描述 投票:0回答:3

我有以下代码:

import matplotlib.pyplot as plt
import numpy as np

# Create scatter plot with all the results
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")


# Create scatter plot of Quantitative Scores vs. Admissions
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")

# Create scatter plot of Verbal Scores vs. Admissions
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")

生成三个数字。然而,当我尝试运行它并绘制三个图形时,它们都被绘制为同一个图形。例如,

quant.png
还具有来自已保存图形
scores_plot.png
的数据,然后
verbal.png
具有来自
scores_plot.png
quant.png
的数据。我怎样才能让它们全部单独保存,这样我就不必注释掉前面的图来单独生成每个图?

python matplotlib figure
3个回答
1
投票

如果您在每个绘图之前使用

plt.figure()
命令将每个图形定义为单独的图形,则它们不会相互重叠绘制。例如:

import matplotlib.pyplot as plt
import numpy as np

# Create scatter plot with all the results
x = np.loadtxt("combined_data.txt")[:,0]
y = np.loadtxt("combined_data.txt")[:,1]

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

plt.savefig("scores_plot.png")


# Create scatter plot of Quantitative Scores vs. Admissions
y_quant = np.loadtxt("combined_data.txt")[:,0]
x_quant = np.loadtxt("admit_data.txt")[:]

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

plt.savefig("quant.png")

# Create scatter plot of Verbal Scores vs. Admissions
y_verb = np.loadtxt("combined_data.txt")[:,1]
x_verb = np.loadtxt("admit_data.txt")[:]

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

plt.savefig("verbal.png")

1
投票

除了即兴的交互式探索之外,不要使用 pyplot 界面进行任何其他事情。

这就是我要做的:

import matplotlib.pyplot as plt
import numpy as np

# Create scatter plot with all the results
x = np.loadtxt("combined_data.txt")[:,0]
y = np.loadtxt("combined_data.txt")[:,1]

fig1, ax1 = plt.subplots()
ax1.plot(x, y, "o")
ax1.set_ylabel("Verbal")
ax2.set_xlabel("Quantitative")
fig1.savefig("scores_plot.png")


# Create scatter plot of Quantitative Scores vs. Admissions
y_quant = np.loadtxt("combined_data.txt")[:,0]
x_quant = np.loadtxt("admit_data.txt")[:]

fig2, ax2 = plt.subplots()
ax2.plot(x_quant, y_quant, "o")
ax2.set_ylabel("Quantitative")
ax2.set_xlabel("Admission")
fig2.savefig("quant.png")

# yada yada

-2
投票

您可以调用

pyplot.clf()
来清除图之间的图形。

© www.soinside.com 2019 - 2024. All rights reserved.