VanN
VanN

Reputation: 17

Create multiple plots using loop and show separate plot in one

I come across the answer from this forum and have a question. How to show separate plot in one plot. Try to use plt.subplots(1, 4) but not work. Here is the sample codes:

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
for i in range(len(x)):
    plt.figure()
    plt.plot(x[i],y[i])
    

#plt.show()

Upvotes: 1

Views: 4438

Answers (2)

Bayes706
Bayes706

Reputation: 11

You can use plt.subplot() as following:

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
plt.figure(figsize=[10,10])

for i in range(len(x)):
    plt.subplot(1,len(x)+1,i+1)
    plt.plot(x[i],y[i])
    plt.title('Plot: '+str(i+1))
plt.show()

Here is output figure:

Here is output figure

Upvotes: 1

Ruthger Righart
Ruthger Righart

Reputation: 4921

The following may do it. It is looping through the lists (x and y have 4 nested lists) and subplots (in this example 2 by 2) using zip.

x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]

fig = plt.figure(figsize=(10, 6))

for i,j in zip(list(range(0,4)), list(range(1,5)) ):
    ax = fig.add_subplot(2,2,j)
    ax.plot(x[i], y[i])

Upvotes: 0

Related Questions