在同一坐标轴上绘制在for循环内生成的多个图形。

24
我的代码如下,问题是我得到了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()

在遍历数组元素时,不应使用for i in range(len(xs))xs[i]的方式。应该使用for x in xs:的方式。 另外一个要点是:为什么要使用这样复杂的方式读取名称? names = np.genfromtxt("selected.csv", delimiter=" ", dtype=np.str, skiprows=1) - MaxNoe
非常感谢。通常我不使用csv文件,但你的方法是一种简洁而整洁的方式。 - Michael Hlabathe
2个回答

28

你的问题在于每次迭代都使用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()

示例图


谢谢,已经注意到了。有没有避免使用for循环的方法? - Michael Hlabathe
@MichaelHlabathe,那是完全不同的问题,与您所问的问题无关。在这种情况下,我建议您提出一个新问题,而不是让我编辑我的答案来回答另一个问题。 - Ffisegydd

4

让我稍微改进一下你的代码:

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()

这是我第一次遇到genfromtxt,它很方便,谢谢更新。 - Michael Hlabathe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接