Search code examples
pythonmatplotlibsubplot

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()

Solution

  • 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])