绘制多个Matplotlib图形数组

0 投票
2 回答
72 浏览
提问于 2025-04-14 16:55

我有一个函数可以创建图形,现在我想在一个循环里多次调用这个函数,给它不同的参数,收集这些图形并把它们画出来。以下是我在Julia中会怎么做的:

using Plots

plots = Array{Plots.Plot{Plots.GRBackend},2}(undef, 3,3)

for i in 1:3
    for j in 1:3
        plots[i,j] = scatter(rand(10), rand(10))
        title!(plots[i,j], "Plot $(i),$(j)")
    end
end

plot(plots..., layout=(3,3))

不过我现在需要用Python来写。所以我目前有一个函数,它会创建一个新的图形并返回这个图形。我不太想改变这个函数的调用方式(比如传递一个轴对象),因为它已经在其他地方使用了。这是一个简单的工作示例。奇怪的是,虽然我没有调用plt.display(),但这里的每个图形都显示出来了,而在主代码中却没有显示。这里的最终图形是空的。

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(3,3)

def plottingfunction(x,y):
    plt.figure()
    plt.scatter(x, y)
    return plt.gcf()

for i in range(3):
    for j in range(3):
        x = np.random.rand(10)
        y = np.random.rand(10)
        ax[i,j] = plottingfunction(x,y)

plt.show()

那么我该如何在Python的matplotlib中,把已经存在的函数绘制成一个网格,比如说这些函数是存放在一个数组里的呢?

2 个回答

0

也许你可以试着设置或获取当前的坐标轴。这样做对我来说不是很有意义,但在这个简单的例子中,似乎是有效的。

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(3, 3)


def plottingfunction(x, y):
    axis = plt.gca()
    axis.scatter(x, y)


for i in range(3):
    for j in range(3):
        plt.sca(ax[i, j])
        x = np.random.rand(10)
        y = np.random.rand(10)
        plottingfunction(x, y)


plt.show()

编辑:我这样做其实有点不情愿,但确实有效。

import matplotlib.pyplot as plt
import numpy as np

fig1, ax1 = plt.subplots(3, 3)
fig2, ax2 = plt.subplots(3, 3)


def plottingfunction1(x, y):
    axis = plt.gca()
    axis.scatter(x, y)


def plottingfunction2(x, y):
    axis = plt.gca()
    axis.plot(x, y)


for ax_ind in range(0, 9):
    x = np.random.rand(10)
    y = np.random.rand(10)

    plt.sca(fig1.axes[ax_ind])
    plottingfunction1(x, y)

    plt.sca(fig2.axes[ax_ind])
    plottingfunction2(x, y)

编辑 2:根据需要创建图形和坐标轴,然后把坐标轴传递给绘图函数。

import matplotlib.pyplot as plt
import numpy as np


def plottingfunction1(x, y, axis):
    axis.scatter(x, y)


def plottingfunction2(x, y, axis):
    axis.plot(x, y)


_, ax1 = plt.subplots(3, 3)
_, ax2 = plt.subplots(3, 3)

for i in range(0, 3):
    for j in range(0, 3):
        x = np.random.rand(10)
        y = np.random.rand(10)

        plottingfunction1(x, y, axis=ax1[i, j])
        plottingfunction2(x, y, axis=ax2[i, j])

plottingfunction2(x, y, axis=ax1[1, 2])
0

怎么样把 ax 这个参数变成可选的?这样你就可以在需要的时候用上它,但又不会影响到你现在的用法。

def plottingfunction(x, y, ax=None):
    if ax is None:
        # Set up a new figure and axes
        fig, ax = plt.subplots()
    else:
        fig = ax.get_figure()

    # Plot the data
    ax.scatter(x, y)
    
    return fig

撰写回答