Python 通过循环和函数填充 matplotlib 子图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27569306/
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
populating matplotlib subplots through a loop and a function
提问by Charles
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:
我需要通过循环迭代绘制图形的子图;每次迭代都会调用另一个模块(=另一个 py 文件)中定义的函数,该函数绘制一对子图。这是我尝试过的 - 可惜不起作用:
1) Before the loop, create a figure with the adequate number of rows, and 2 columns:
1) 在循环之前,创建一个具有足够行数和 2 列的图形:
import matplotlib.pyplot as plt
fig, axarr = plt.subplots(nber_rows,2)
2) Inside the loop, at iteration number iter_nber, call on the function drawing each subplot:
2) 在循环内部,在迭代次数 iter_nber 处,调用绘制每个子图的函数:
fig, axarr = module.graph_function(fig,axarr,iter_nber,some_parameters, some_data)
3) The function in question is basically like this; each iteration creates a pair of subplots on the same row:
3)问题中的函数基本是这样的;每次迭代在同一行上创建一对子图:
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
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.
这不起作用。我最终在循环结束时得到一个空图形。我已经尝试了上述的各种组合,比如在函数的返回参数中只留下 axarr ,但无济于事。显然我不明白这个图及其子图的逻辑。
Any suggestions much appreciated.
任何建议非常感谢。
采纳答案by Joe Kington
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.
您发布的代码似乎基本正确。除了索引,正如@hitzg 提到的,你所做的一切看起来都非常不寻常。
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.
但是,从绘图函数返回图形和轴数组没有多大意义。(如果您需要访问图形对象,您总是可以通过ax.figure
。)但是,传入和返回它们不会改变任何内容。
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()