简体   繁体   English

Python:使用for循环在一个图形中创建多个图

[英]Python: Creating multiple plots in one figure with for loop

I have tried to create a 2 row, 3 column grid of plots (each having multiple data plotted on it) using matplotlib. 我试图使用matplotlib创建一个2行3列的绘图网格(每个网格都有多个数据)。 However, no matter what I try, the final saved figure is just one of the plots, with the rest blank. 但是,无论我尝试什么,最终保存的图形只是其中之一,其余为空白。 I know the other were produced, but they are not appearing in the final image. 我知道其他照片是制作出来的,但是它们没有出现在最终图像中。 Here is one basic version of what I'm trying. 这是我正在尝试的一个基本版本。

The commented out pieces show some alternatives that I have seen. 注释掉的片段显示了我看到的一些替代方法。

f,axarr = plt.subplots(2,3, sharex='col', sharey='row')

for i,someargs in enumerate(namelist):
    x1,y1,x2,y2 = somefunction(someargs)  #output data
    ax = axarr.flat[i]  #or ax=axarr[row,col]
    ax.plot(x1,y1)
    ax.plot(x2,y2)
plt.savefig("name")
#or f.savefig("name")

Is there something wrong with the way I am doing this? 我的操作方式有问题吗? The image I am getting is located at http://i.imgur.com/QxYRnPT.png Any help would be greatly appreciated. 我得到的图像位于http://i.imgur.com/QxYRnPT.png任何帮助将不胜感激。

here is the way you can use a loop to generate your subplots and you can hide the axes which you do not need: 这是您可以使用循环生成subplots并隐藏不需要的轴的方法:

import pylab as plt
import numpy as np
fig ,axs=plt.subplots(2,3, sharex='col', sharey='row')
axs[-1,-1].axis('off')
namelist=['a','b','c','d','e']
ax=axs.ravel()
for i,someargs in enumerate(namelist):
    x1,y1,x2,y2 = somefunction(someargs)
    ax[i].plot(x1,y1)
    ax[i].plot(x2,y2)

After spending some some time closely looking at what I'm running, I've found that the problem might lie somewhere with the function I am using to generate data and how it interacts with the loop. 在花了一些时间仔细查看我正在运行的内容之后,我发现问题可能出在我用来生成数据的函数以及它与循环的交互方式中。 Indeed, using basic test data causes no problem. 确实,使用基本测试数据不会造成任何问题。

That function does a lot of stuff (and requires parallelism), so it's difficult to tell exactly what it's doing. 该函数完成了很多工作(并且需要并行处理),因此很难准确地知道它在做什么。

I'm not really sure what went wrong, but I fixed my problem by storing the data first, and then accessing/plotting it in the manner I posted or similarly to the other answer. 我不太确定出了什么问题,但我先解决了问题,方法是先存储数据,然后再按我发布的方式或与其他答案类似的方式访问/绘图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM