通过循环和函数填充matplotlib子图 [英] populating matplotlib subplots through a loop and a function

查看:61
本文介绍了通过循环和函数填充matplotlib子图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过循环迭代绘制图形的子图;每次迭代都调用另一个模块(=另一个py文件)中定义的函数,该模块绘制一对子图.这是我尝试的方法-las不起作用:

I need to draw subplots of a figure through loop iterations; each iteration calls a function defined in another module (=another py file), which draws a pair of subplots. Here is what I tried -- and alas does not work:

1) 在循环之前,创建一个具有足够行数和 2 列的图形:

1) Before the loop, create a figure with the adequate number of rows, and 2 columns:

 import matplotlib.pyplot as plt     
 fig, axarr = plt.subplots(nber_rows,2)

2) 在循环内部,在迭代次数 iter_nber 处,调用绘制每个子图的函数:

2) Inside the loop, at iteration number iter_nber, call on the function drawing each subplot:

 fig, axarr = module.graph_function(fig,axarr,iter_nber,some_parameters, some_data)

3)问题中的函数基本是这样的;每次迭代在同一行上创建一对子图:

3) The function in question is basically like this; each iteration creates a pair of subplots on the same row:

 def graph_function(fig,axarr,iter_nber,some_parameters, some_data):

     axarr[iter_nber,1].plot(--some plotting 1--)
     axarr[iter_nber,2].plot(--some plotting 2--)

     return fig,axarr

这不起作用.我最终在循环结束时得到一个空图形.我已经尝试了上述方法的各种组合,例如在函数的return参数中仅保留axarr,但无济于事.显然,我不了解该图及其子图的逻辑.

This does not work. I end up with an empty figure at the end of the loop. I have tried various combinations of the above, like leaving only axarr in the function's return argument, to no avail. Obviously I do not understand the logic of this figure and its subplots.

任何建议都值得赞赏.

推荐答案

您发布的代码似乎基本正确.除了@hitzg提到的索引编制之外,您正在做的任何事情看上去都与众不同.

The code you've posted seems largely correct. Other than the indexing, as @hitzg mentioned, nothing you're doing looks terribly out of the ordinary.

但是,从绘图函数返回图形和轴数组并没有多大意义.(如果需要访问图形对象,则始终可以通过 ax.figure 来获取它.)尽管如此,它不会更改传递给它们并返回它们的任何内容.

However, it doesn't make much sense to return the figure and axes array from your plotting function. (If you need access to the figure object, you can always get it through ax.figure.) It won't change anything to pass them in and return them, though.

这里有一个简单的例子,说明您正在尝试做的事情类型.也许这有助于消除一些困惑?

Here's a quick example of the type of thing it sounds like you're trying to do. Maybe it helps clear some confusion?

import numpy as np
import matplotlib.pyplot as plt

def main():
    nrows = 3
    fig, axes = plt.subplots(nrows, 2)

    for row in axes:
        x = np.random.normal(0, 1, 100).cumsum()
        y = np.random.normal(0, 0.5, 100).cumsum()
        plot(row, x, y)

    plt.show()

def plot(axrow, x, y):
    axrow[0].plot(x, color='red')
    axrow[1].plot(y, color='green')

main()

这篇关于通过循环和函数填充matplotlib子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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