多个图形每个包含多个图表 matplotlib + python for 循环

1 投票
1 回答
24 浏览
提问于 2025-04-12 15:45

在matlab中,你可以随时回到任何一个图形,更新它或者在上面添加内容,只需要用命令 figure(the_figure_number); 就可以了。

这在循环中非常有用,比如说:

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

上面的代码会生成两个图形,每个图形里面有四个共享坐标轴的图。

在python中用matplotlib实现这个功能看起来比较麻烦(我对python不太熟)。有没有办法不使用子图,或者更糟糕的是,不用单独的循环呢?

我想绘制的真实数据太大了,所以多个循环会很慢,而且为了发表,每个图形都需要单独保存为.svg文件,这样子图就不太方便了。

1 个回答

1

我觉得你可以用和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}')

# Format the first figure
# title, legends, grids, tickers, axis limits, colors, ...
plt.figure(1)
plt.legend()
plt.title('n*x for n in [1, 2, 3, 4]')
plt.xlabel('x')
plt.ylabel('n*x')

# Format 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()

撰写回答