简体   繁体   中英

Plotting multiple lines onto one graph from for loop

I have a for loop running through my data to find dips in my data set. This gives me five different graphs. I need to superimpose these five graphs onto each other with different colors. Yes, it will ve very messy. I've done this before but not while it's in a four loop so I'm not sure how to go about it. Here is my data

# data
data = np.loadtxt('student_021.txt') # loading light curve data file 
time_x = data[:,0] # taking the first column of data
lum_y = data[:,1] # second column

mean = lum_y.mean() # mean value of the light curve
std = lum_y.std() # standard deviation of the light curve

light_dip = [] # initalize empty array for areas where the light curve dips 
end = None # cut off the values here where the data goes to normal

# for loop to go through the data and find where the light dips are 
for i, x in enumerate(lum_y): #enumerate to assign positional values so I can identify and sepparate them 
    if x < mean - (std *4): # if the iterator is less than the mean - an arbitrarly chosen 4stds 
        if not light_dip: # is it an outlier or not?
            light_dip.append(i) # if it is, let me know and append the data
            end = i
        else:
            if i > end + 250: # find the end of the light dip
                end = light_dip.append(i)
                end = i
                
print(light_dip)
# plotting the primary chart
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlabel('Time(s)')
ax.set_ylabel('Brightnes')
ax.plot(time_x,lum_y)
plt.title('Original Graph')
for dip in light_dip: # sort through and print out the five different light dips
    i = max(dip - 50, 0) # left limit
    j = dip + 150 # right limit

    factor_x = time_x[i:j]
    factor_y = lum_y[i:j]
    
    # plotting
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_xlabel('Time (s)')
    ax.set_ylabel('Brightnes')
    #ax.plot(time_x,lum_y)
    ax.plot(factor_x, factor_y)

在此处输入图像描述 在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

Your light_dip loop currently creates a new fig and ax in each iteration. Instead, create fig and ax before the loop (but still within the same jupyter cell) and reuse them inside the loop:

# create fig/ax before the loop (but in the same jupyter cell)
fig = plt.figure()
ax = fig.add_subplot()

for dip in light_dip:
    i = max(dip - 50, 0)
    j = dip + 150

    factor_x = time_x[i:j]
    factor_y = lum_y[i:j]
    
    ax.set_xlabel('Time (s)')
    ax.set_ylabel('Brightness')
    ax.plot(factor_x, factor_y)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM