Home > database >  How can I add a new plots to existing figures?
How can I add a new plots to existing figures?

Time:03-20

I am new to Python and have mainly used MatLab in the past. I am re-writing one of my MatLab scripts and am wondering how to add plots to figures. It seems in python I can only have one figure open at a time and have to manually close the window before a second figure will open. My original script is a couple hundred lines long, but here is a MWE of what I want to do.

import matplotlib.pyplot as plt
import numpy as np
#from mpl_toolkits import mplot3d

lst = [ 1, 1.5, 2, 4.5]
alpha= np.array(lst) 

#initialize tables for plots
xtable = []
ytable = []
y2table = []

#determine whether lst is a vector or an array for number of iterations of inner and outer loops
def size(arr):
    if len(arr.shape) == 1:
        return arr.shape[0], 1
    return arr.shape
[nn,mm] = size(alpha)

#create and plot data
for kk in range(nn):#= 1:nn
    x = [i for i in range(0, 10)]
    y = [alpha[kk]*i for i in range(0, 10)]
    y2 = [alpha[kk]*i**2 for i in range(0, 10)]

    #data for plot(s)
    xtable  = [x]
    ytable  = [y]
    y2table  = [y2]
    
    #plot1 
    plt.plot(xtable,ytable)
    plt.hold on

    #plot2   
    plt.plot(xtable,y2table)
    plt.hold on 

In my script these will actually be 3D plots, but I don't think that's necessary here. I just want the for-loop to run for each value in lst and end up with two figures, each with 4 plots. The size of lst is not fixed or I'd generate the data in the loop and plot later.

Thank you in advance for your help

CodePudding user response:

follow up on tdy's comment:

#create plots:
fig1, ax1 = plt.subplots()
fig2, ax2 = plt.subplots()

#plot data
for kk in range(nn):#= 1:nn
    x = [i for i in range(0, 10)]
    y = [alpha[kk]*i for i in range(0, 10)]
    y2 = [alpha[kk]*i**2 for i in range(0, 10)]

    #data for plot(s)
    xtable  = [x]
    ytable  = [y]
    y2table  = [y2]
    
    #plot1 
    ax1.plot(xtable,ytable)
    
    #plot2   
    ax2.plot(xtable,y2table)
  • Related