Search code examples
pythonpython-3.xmatplotlibplotscatter-plot

How to plot different plots on same page in Python?


I have plotted 10 plots but they are showing in different windows but I want to plot grid of separate plots of descent size on same page or within few pages.

Code that reproduces my condition is:

matrix=np.random.randint(0,100,(50,10))
df=pd.DataFrame(matrix)
df.columns=['a','b','c','d','e','f','g','h','i','j']


f=pd.DataFrame(np.random.randint(0,100,(50,1)))
f.columns=['f']

for i in range(len(df.columns)):
    plt.scatter(df.iloc[:,i],f)
    plt.show()

The desired output should look something like:

enter image description here


Solution

  • You need to use plt.subplot() for this. Documentation

    With subplot, you can place multiple plots in a single figure:

    import matplotlib.pyplot as plt
    
    # Arguments to subplot are (# rows, # cols, index in grid)
    plt.subplot(1, 2, 1)
    # Modify left plot here
    plt.title("Left Plot")
    plt.text(0.4, 0.4, "1", fontsize=50)
    
    plt.subplot(1, 2, 2)
    # Modify right plot here
    plt.title("Right Plot")
    plt.text(0.4, 0.4, "2", fontsize=50)
    
    plt.show()
    

    This code produces:

    side by side plot

    Simply change the first two digits in the argument to subplot to increase the number of rows and columns in the grid.

    For your application with 10 plots, you could do this:

    # Increase figure size so plots are big
    plt.figure(figsize=(10, 40))
    
    for i in range(len(df.columns)):
        plt.subplot(5, 2, i+1)
        plt.scatter(df.iloc[:,i],f)
    
    plt.show()
    

    This will create a grid of plots with 5 rows and 2 columns.

    Reference: