pythonmatplotlibmatlab-figure

multiple figures each one with multiple graphs matplotlib + python foor loop


In matlab you can always come back to any figure, update this or add to it by using the comand figure(the_figure_number);

This is very useful in for loops, for example

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

The previous code will produce 2 figures each of this with 4 graphs sharing axes.

In python with matplotlib this looks rather tedious to achieve (not very good at python). Is there a way to achieve this without using subplots or worse doing individual for loops?

The real data I want to plot is to big so multiple for loops is very slow, plus for publication purposes each figure needs to be its own .svg file so subplots is inconvenient.


Solution

  • I think you can get the same behavior using the same code structure than in matlab. The code below will produce two figures with 4 plots each, without using subplots. Subplots are used in matplotlib to display several graphs on the same figure, but here you want to add several plots to the same graph. And you can come back to a figure number to add legend, titles, defines axis limits, display any formating like grids, tickers and so on...

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