在 matlab 中,您始终可以返回任何图形,使用命令
figure(the_figure_number);
更新或添加内容
这在 for 循环中非常有用,例如
x=0:0.2:20;
for n=[1 2 3 4]
figure(1);
plot(x,n*x);
hold on
figure(2);
plot(x,x.^n);
hold on
end
之前的代码将生成 2 个图形,每个图形有 4 个共享轴的图形。
在带有 matplotlib 的 python 中,这看起来实现起来相当乏味(不太擅长 python)。 有没有一种方法可以在不使用子图或更糟糕的情况下执行单独的 for 循环的情况下实现此目的?
我想要绘制的真实数据很大,因此多个 for 循环非常慢,而且出于发布目的,每个图形都需要是自己的 .svg 文件,因此子图不方便。
我认为您可以使用与 matlab 中相同的代码结构获得相同的行为。下面的代码将生成两个图,每个图有 4 个图,而不使用子图。 matplotlib 中使用子图在同一个图形上显示多个图形,但这里您想要将多个图添加到同一个图形中。
import numpy as np
import matplotlib.pyplot as plt
# Create the x vector
x = np.arange(0, 20.2, 0.2)
# Loop over the values of n
for n in [1, 2, 3, 4]:
# Plot n*x for each n in the first figure
plt.figure(1)
plt.plot(x, n*x, label=f'n={n}')
# Plot x^n for each n in the second figure
plt.figure(2)
plt.plot(x, x**n, label=f'n={n}')
# Set up legends and show the first figure
plt.figure(1)
plt.legend()
plt.title('n*x for n in [1, 2, 3, 4]')
plt.xlabel('x')
plt.ylabel('n*x')
# Set up legends and show the second figure
plt.figure(2)
plt.legend()
plt.title('x^n for n in [1, 2, 3, 4]')
plt.xlabel('x')
plt.ylabel('x^n')
# Show all figures
plt.show()