在同一轴上绘制在for循环内生成的多个图python [英] plotting multiple plots generated inside a for loop on the same axes python

查看:57
本文介绍了在同一轴上绘制在for循环内生成的多个图python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下,问题是我没有242个图,而是有一个图.我尝试将 plt.show() 放在循环之外,但没有用.

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.

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

推荐答案

您的问题是,您每次使用

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

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循环内生成的多个图python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆