我需要通过循环迭代绘制图形的子图;每次迭代调用另一个模块(=另一个 py 文件)中定义的函数,该函数绘制一对子图。这是我尝试过的——唉,行不通:
1) 在循环之前,创建一个具有足够行数和 2 列的图形:
import matplotlib.pyplot as plt
fig, axarr = plt.subplots(nber_rows,2)
2) 在循环内,在迭代次数 iter_nber 处,调用绘制每个子图的函数:
fig, axarr = module.graph_function(fig,axarr,iter_nber,some_parameters, some_data)
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
这是行不通的。我在循环结束时得到一个空图。 我已经尝试了上述的各种组合,比如在函数的返回参数中只留下 axarr,但无济于事。显然我不明白这个图及其子图的逻辑。
非常感谢任何建议。
最佳答案
您发布的代码似乎基本正确。正如@hitzg 所提到的,除了索引之外,您所做的一切看起来都非常不寻常。
但是,从您的绘图函数返回图形和轴数组没有多大意义。 (如果您需要访问 figure 对象,您始终可以通过 ax.figure
获取它。)不过,传入和返回它们不会改变任何内容。
这是一个简单的示例,说明您正在尝试做的事情类型。也许它有助于消除一些困惑?
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()
关于python - 通过循环和函数填充 matplotlib 子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27569306/