首页 > 解决方案 > 从 for 循环将多条线绘制到一个图上

问题描述

我有一个 for 循环遍历我的数据以查找我的数据集中的下降。这给了我五个不同的图表。我需要用不同的颜色将这五个图叠加在一起。是的,它会非常混乱。我以前做过,但不是在四个循环中,所以我不知道该怎么做。这是我的数据

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

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

标签: pythonmatplotlib

解决方案


您的循环当前在每次迭代中light_dip创建一个新的fig和。ax相反,在循环之前fig创建and (但仍在同一个 jupyter 单元中)并在循环中重用它们:ax

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

推荐阅读