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

fruv7luv  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(110)

此问题在此处已有答案

How to show two figures using matplotlib?(4个答案)
matplotlib Axes.plot() vs pyplot.plot()(5个答案)
12天前关门了。
我有以下代码:

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.pngquant.png的数据。我如何让它们都单独保存,这样我就不必注解掉以前的地块分别生成每个?

qaxu7uf2

qaxu7uf21#

如果在每次绘图之前使用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")

字符串

wqlqzqxt

wqlqzqxt2#

不要将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

字符串

相关问题