Mavridis M.
Mavridis M.

Reputation: 115

Plot a matplotlib figure within a for loop at each step

I am trying to analyse data using Python from various different files. So I use a function that looks like this:

def multi_estimate(a , b):
    ids = np.linspace(0.3 , 0.7 ,num = 17, endpoint = True) #files name identifier
    for i in ids:
          dat = np.loadtxt('Qn'+ str(int(i*1000))+'.txt') # reading filename
          q = np.array(dat[:,1]); # take the second column
          x , y = hurst(q); # calculate lags and R/S values for Hurst exponent
          coef = linear_fit(x, y , a , b)    # make a linear fit and estimate slope
    return None

In my linear fit function I am plotting the result because I would like to check if the fit is done properly and the points are in a straight line. If it is not done properly I would like to make a new fit by adding some code in my function. My problem is that during execution empty figures appear and the are filled with the plots only when the for loop comes to end.

How can I get each plot to appear at each for step I, check it and then move on to the next one?

My fit function is:

def linear_fit(x, y, xmin, xmax):
    idx1 = (np.abs(x-xmin)).argmin()
    idx2 = (np.abs(x-xmax)).argmin()
    coef = np.polyfit(np.log2(x[idx1:idx2+1]), np.log2(y[idx1:idx2+1]), 1)
    plt.figure()
    plt.plot(np.log2(x), np.log2(y), 'r+', label = 'data')
    plt.plot(np.log2(x[idx1:idx2+1]) , coef[1]+coef[0]*np.log2(x[idx1:idx2+1]), label = 'H = %1.2f' %coef[0] )
    plt.grid()
    plt.legend(loc = 'best')
    plt.show()
    return coef

Upvotes: 1

Views: 4073

Answers (2)

Mavridis M.
Mavridis M.

Reputation: 115

It turns out that when i am using Ipython from a terminal everything work as they are expected to work. Problems appear when i am using Canopy, so i guess this is a Canopy Bug.

Upvotes: 0

tglaria
tglaria

Reputation: 5866

Well, this works for me.

import matplotlib.pyplot as pl

def test(x):
    pl.figure()
    pl.plot(x)
    pl.show()

for i in range(1,3):
    eje = range(i*10)
    test(eje)

I get one plot for each function call.

Upvotes: 1

Related Questions