1

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

halfer
  • 19,824
  • 17
  • 99
  • 186

2 Answers2

3

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:

luc
  • 526
  • 3
  • 6
  • i tried this method earlier but got very small plots –  Jun 25 '20 at 19:35
  • 1
    You can increase the figure size with `plt.figure(figsize=(10, 40))`. This will make your figure 10 inches wide by 40 inches tall. @Razeun – luc Jun 25 '20 at 19:37
0

Will this give you a clue as to how to achieve your goal?

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

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']
fig,axs = plt.subplots(2,2)

axs[0,0].scatter(df.iloc[:,0],f)
axs[0,1].scatter(df.iloc[:,1],f)
axs[1,0].scatter(df.iloc[:,2],f)
axs[1,1].scatter(df.iloc[:,3],f)

plt.show()

Output:

enter image description here


UPDATED FOR LOOP:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

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']

fig,axs = plt.subplots(2,2)

i = 0
for a in axs:
    for b in a:
        ax[a,b].scatter(df.iloc[:,i],f)
        i += 1

plt.show()
Red
  • 26,798
  • 7
  • 36
  • 58