Julio
Julio

Reputation: 871

How to plot multiple scatter plots in the same window with matplotlib?

I need to plot 15 scatter plots (5 rows and 3 columns) in the same window, using matplotlib. I've already found a code to solve a problem similar to this, but i can't adapt it to my problem. I think it is easy to do, but I'm having difficult with this. Can someone help me?

This is the code I'm trying to reuse:

import numpy as np
import matplotlib.pyplot as plt

w=10
h=10
fig=plt.figure(figsize=(8, 8))
columns = 4
rows = 5
for i in range(1, columns*rows +1):
    img = np.random.randint(10, size=(h,w))
    fig.add_subplot(rows, columns, i)
    plt.imshow(img)
plt.show()

Thank you

Upvotes: 1

Views: 8270

Answers (1)

rahlf23
rahlf23

Reputation: 9019

The following creates two numpy arrays and plots a figure with 15 subplots, arranged in 5 rows and 3 columns. Note that you can dynamically assign your x and y variables inside of the for loop as well, especially if you would like to loop through a set of data while creating each individual subplot:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(1,10,10)
y = np.linspace(1,10,10)

fig = plt.figure(1)

columns = 3
rows = 5

for i in range(1, columns*rows+1):
    fig.add_subplot(rows, columns, i)
    plt.scatter(x, y)

plt.tight_layout()
plt.show()

Upvotes: 3

Related Questions