我的代码如下,问题是没有一个情节,我得到242个情节。我尝试将plt.show()
置于循环之外,但它不起作用。
import numpy as np
import matplotlib.pyplot as plt
import csv
names = list()
with open('selected.csv','rb') as infile:
reader = csv.reader(infile, delimiter = ' ')
for row in reader:
names.append(row[0])
names.pop(0)
for j in range(len(names)):
filename = '/home/mh/Masters_Project/Sigma/%s.dat' %(names[j])
average, sigma = np.loadtxt(filename, usecols = (0,1), unpack = True, delimiter = ' ')
name = '%s' %(names[j])
plt.figure()
plt.xlabel('Magnitude(average)', fontsize = 16)
plt.ylabel('$\sigma$', fontsize = 16)
plt.plot(average, sigma, marker = '+', linestyle = '', label = name)
plt.legend(loc = 'best')
plt.show()
答案 0 :(得分:9)
您的问题是,您使用plt.figure()
每次迭代都会创建一个新数字。从for
循环中删除此行,它应该可以正常工作,如下面的简短示例所示。
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
for a in [1.0, 2.0, 3.0]:
plt.plot(x, a*x)
plt.show()
答案 1 :(得分:0)
让我稍微改进你的代码:
import numpy as np
import matplotlib.pyplot as plt
# set the font size globally to get the ticklabels big too:
plt.rcParams["font.size"] = 16
# use numpy to read in the names
names = np.genfromtxt("selected.csv", delimiter=" ", dtype=np.str, skiprows=1)
# not necessary butyou might want to add options to the figure
plt.figure()
# don't use a for i in range loop to loop over array elements
for name in names:
# use the format function
filename = '/home/mh/Masters_Project/Sigma/{}.dat'.format(name)
# use genfromtxt because of better error handling (missing numbers, etc)
average, sigma = np.genfromtxt(filename, usecols = (0,1), unpack = True, delimiter = ' ')
plt.xlabel('Magnitude(average)')
plt.ylabel('$\sigma$')
plt.plot(average, sigma, marker = '+', linestyle = '', label = name)
plt.legend(loc = 'best')
plt.show()