pythonmatplotlib

Get seperate plots and one accumulated in matplotlib.pyplot


As to expect I get 2 different plots from the code below. Besides those two I would also like to have one seperate plot that shows both lines in the same graph, with different colours and legend.

I do not want them as sublots, I want each of them as a single plot and one with all the lines in the same plot.

import matplotlib.pyplot as plt
import numpy as np

for i in range(2):

    x = np.arange(0, 4*np.pi, 0.1)
    y = np.sin(x)

    plt.plot(x, i*y+i)
    plt.title("Values")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.show()

I had a look at this stack exchange question.

I could write x and y values of each graph to a list to save for later, but for large dataset that does not seem clever.


Solution

  • I'm not sure which IDE you're using, but your code technically doesn't create two figures. If you only call plt.plot, it will create a figure if none exist or add to the last figure if one does exist. You would need to call plt.figure if you want to create a new figure.

    So, for your case, you want to create a main figure for the combined plots and then create a new figure each loop for the individual plots. The figures can be created using plt.subplots() (without any nrows or ncols arguments it creates a single plot, not a matrix of plots).

    In the loop I chose to create fig_i and ax_i for the individual plots and fig and ax for the global plots. Since you want a legend, you should add a label for the combined plot.

    import matplotlib.pyplot as plt
    import numpy as np
    
    plt.close("all")
    
    # figure for the combined plot
    fig, ax = plt.subplots()
    ax.set_xlabel("x")
    ax.set_ylabel("y")
    ax.set_title("Combined Plot")
    
    x = np.arange(0, 4*np.pi, 0.1)
    y = np.sin(x)
    
    for i in range(2):
        # creates a new figure each loop
        fig_i, ax_i = plt.subplots()
        ax_i.plot(x, i*y+i)
        ax_i.set_title("Values")
        ax_i.set_xlabel("x")
        ax_i.set_ylabel("y")
        fig_i.show()
    
        # adds the data to the combine figure with a label for the legend
        ax.plot(x, i*y+i, label=i)
    
    ax.legend()
    fig.show()
    

    Individual 1:

    Individual 2:

    Combined: