gpt4 book ai didi

python - 来自函数 Matplotlib 的多个图

转载 作者:行者123 更新时间:2023-12-05 05:50:35 24 4
gpt4 key购买 nike

(根据建议调整)我已经有一个执行一些情节的函数:

def plot_i(Y, ax = None):
if ax == None:
ax = plt.gca()
fig = plt.figure()
ax.plot(Y)
plt.close(fig)
return fig

我希望用它来绘制 n 个数组的网格。为简单起见,我们假设网格是 (n//2, 2) 并且 n 是偶数。此刻,我想到了这个:

def multi_plot(Y_arr, function):
n = len(Y_arr)
fig, ax = plt.subplots(n // 2, 2)
for i in range(n):
# assign to one axis a call of the function = plot_i that draws a plot
plt.close(fig)
return fig

不幸的是,如果我这样做会得到什么:

# inside the loop
plot_i(Y[:, i], ax = ax[k,j])

是正确的,但我每次都需要在最后关闭数字,否则我会继续向 plt 添加数字。有什么办法可以避免每次都调用 plt.close(fig)?

最佳答案

如果我没理解错的话,你正在寻找这样的东西:

import numpy as np
import matplotlib.pyplot as plt

def plot_i(Y, ax=None):
if ax == None:
ax = plt.gca()
ax.plot(Y)
return

def multi_plot(Y_arr, function, n_cols=2):
n = Y_arr.shape[1]
fig, ax = plt.subplots(n // n_cols + (1 if n % n_cols else 0), n_cols)
for i in range(n):
# assign to one axis a call of the function = plot_i that draws a plot
function(Y_arr[:, i], ax = ax[i//n_cols, i%n_cols])
return fig

if __name__ == '__main__':
x = np.linspace(0,12.6, 100)
# let's create some fake data
data = np.exp(-np.linspace(0,.5, 14)[np.newaxis, :] * x[:, np.newaxis]) * np.sin(x[:, np.newaxis])
fig = multi_plot(data, plot_i, 3)

使用 gca() 时要小心:如果没有事件图形,它将创建一个新图形。

关于python - 来自函数 Matplotlib 的多个图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70499932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com