在 Matplotlib 中使用组合列表的几个带有子图的图形

Several figures with subplots using a combination list in Matplotlib

我想制作一个矢量场的流图,其中包含一些我想更改的自由常量。所以我已经组合了这些常量,我可以用这个成功地一个一个地绘制流图:

Y, X = np.mgrid[-1:10:200j, 0:10:200j]

tau_x = [0.01, 0.1, 1., 10.]
tau_y = [0.01, 0.1, 1., 10.]
alpha = [0.01, 0.1, 1., 10.]
r = [0.1, 0.01, 0.001]
K = [0.1, 0.5, 1.0, 1.5]

combinations_list = list(itertools.product(tau_x,tau_y,alpha,r,K))

for a in combinations_list:

    (tau_x, tau_y, alpha, r, K) = a

    Fx = (1/tau_x) * ( (-8/3)*(2*r-alpha)*(X-1) + K*X )
    Fy = (2/(tau_y*X**(3/2))) * ( -2*(Y-1) + 3*Y*(X-1)/X + K*X*Y )

    fig, ax = plt.subplots()
    strm = ax.streamplot(X, Y, Fx, Fy, linewidth=0.5)

    plt.show()

现在,因为我们讨论的是非常多的组合,所以我想制作一个带有子图的图(比如每个图 9 个,但可能更多),这会减少很多图的数量。

注意:我希望每次都能看到一个图,这就是为什么 plt.show() 在循环内以避免一次打开所有图。

编辑:根据 ImportanceOfBeingErnest 的建议,我将代码更改为

Y, X = np.mgrid[-1:10:200j, 0:10:200j]

tau_x = [0.01, 0.1, 1., 10.]
tau_y = [0.01, 0.1, 1., 10.]
alpha = [0.01, 0.1, 1., 10.]
r = [0.1, 0.01, 0.001]
K = [0.1, 0.5, 1.0, 1.5]

combinations_list = list(itertools.product(tau_x,tau_y,alpha,r,K))
length = len(combinations_list)

N = 9 #number of subplots per figure

for i in range(0,100):

    subset = combinations_list[9*i:9*i+9]

    fig = plt.figure()

    j = 1
    for a in subset:

        (tau_x, tau_y, alpha, r, K) = a

        Fx = (1/tau_x) * ( (-8/3)*(2*r-alpha)*(X-1) + K*X )
        Fy = (2/(tau_y*X**(3/2))) * ( -2*(Y-1) + 3*Y*(X-1)/X + K*X*Y )

        ax = fig.add_subplot(3,3,j)
        ax.streamplot(X, Y, Fx, Fy, linewidth=0.5)
        ++j


    plt.show()

但它只绘制每个子集中的第一个,并且以一种奇怪的方式在向量中添加颜色。

您没有正确更新 j++j 不会更新 j 的值。如果将 ++j 替换为 j += 1j = j+1,您的代码将正常工作。两者是等价的。

for i in range(0,100):
    subset = combinations_list[9*i:9*i+9]
    fig = plt.figure()

    j = 1
    for a in subset:
        (tau_x, tau_y, alpha, r, K) = a

        Fx = (1/tau_x) * ( (-8/3)*(2*r-alpha)*(X-1) + K*X )
        Fy = (2/(tau_y*X**(3/2))) * ( -2*(Y-1) + 3*Y*(X-1)/X + K*X*Y )

        ax = fig.add_subplot(3,3,j)
        ax.streamplot(X, Y, Fx, Fy, linewidth=0.5)
        j += 1 # <--- change here