Search code examples
pythonmatplotlibfigure

How to display multiple figure with matplotlib?


I try to display 3 figures only one window.

So I have a function make_graph(x) that make a figure of 2 subplots:

%matplotlib
import matplotlib.pyplot as plt
import numpy as np

def make_graph(x):  
    fig = plt.figure()
    ax = fig.add_subplot(2,1,1)
    ax.scatter(x, [x ** 2], s = 50, color = 'blue')
    ax = fig.add_subplot(2,1,2)
    ax.scatter(x, [x ** 3], s = 50, color = 'red')


make_graph(np.arange(10)) #figure_1
make_graph(np.arange(20)) #figure_2
make_graph(np.arange(30)) #figure_3

I want to display this 3 figures in a only one window, but actually, I have 3 windows opening. I don't know how to code this.

Could you help?


Solution

  • Set a list of three parameters as arguments to the function and use the So it draws the length of the list for a number of times (three).

    import matplotlib.pyplot as plt
    import numpy as np
    
    def make_graph(x):  
        fig = plt.figure()
        pos = [[1,2,3],[4,5,6]]
        for i,val in enumerate(x):
            x = np.arange(val)
            ax = fig.add_subplot(2,3,pos[0][i])
            ax.scatter(x, [x ** 2], s = 50, color = 'blue')
            ax = fig.add_subplot(2,3,pos[1][i])
            ax.scatter(x, [x ** 3], s = 50, color = 'red')
    
    make_graph([10,20,30])