I am trying to plot multiple plots in a 2Y plot.

I have the following code:

  • Has a list of files to get some data;
  • Gets the x and y components of data to plot in y-axis 1 and y-axis 2;
  • Plots data.

When the loop iterates, it plots on different figures. I would like to get all the plots in the same figure. Can anyone give me some help on this?

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
file=[list of paths]

for i in files:

 # Loads Data from an excel file
    data = pd.read_excel(files[i],sheet_name='Results',dtype=float)

 # Gets x and y data from the loaded files
    x=data.iloc[:,-3]
    y1=data.iloc[:,-2]
    y12=data.iloc[:,-1]
    y2=data.iloc[:,3]

    fig1=plt.figure()
    ax1 = fig1.add_subplot(111)    
    ax1.set_xlabel=('x')
    ax1.set_ylabel=('y')

    ax1.plot(x,y1)
    ax1.semilogy(x,y12)

    ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis
    ax2.plot(x,y2)

    fig1.tight_layout()  

    plt.show()








1 Answers

1
Community On

You should instantiate the figure outside the loop, and then add the subplots while iterating. In this way you will have a single figure and all the plots inside it.

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
files=[list of paths]

fig1=plt.figure()

for i in files:

 # Loads Data from an excel file
    data = pd.read_excel(files[i],sheet_name='Results',dtype=float)

 # Gets x and y data from the loaded files
    x=data.iloc[:,-3]
    y1=data.iloc[:,-2]
    y12=data.iloc[:,-1]
    y2=data.iloc[:,3]

    ax1 = fig1.add_subplot(111)    
    ax1.set_xlabel=('x')
    ax1.set_ylabel=('y')

    ax1.plot(x,y1)
    ax1.semilogy(x,y12)

    ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis
    ax2.plot(x,y2)

    fig1.tight_layout()  

    plt.show()