绘制在同一轴上的for循环内生成的多个图python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26355313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:23:20  来源:igfitidea点击:

plotting multiple plots generated inside a for loop on the same axes python

pythonpython-3.xmatplotlib

提问by Michael Hlabathe

My code is as follows, the problem is instead of having one plot, I get 242 plots. I tried putting the plt.show()outside the loop, it didn't work.

我的代码如下,问题是不是只有一个图,我得到了 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()

回答by Ffisegydd

Your issue is that you're creating a new figure with every iteration using plt.figure(). Remove this line from your forloop and it should work fine, as this short example below shows.

您的问题是您正在使用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()

Example plot

示例图

回答by MaxNoe

Let me improve your code a bit:

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

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