python - 从 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)
解决方案
您的循环当前在每次迭代中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)
推荐阅读
- json - mulesoft中的json到xml转换
- java - 如何更改方面顺序?
- java - 关于在 Interceptor 中读取 POST 方法参数
- sql-server - 在同一 SQL 查询上运行的 10 个值
- javascript - 如何使用 Jest 和 Enzyme 测试 getDerivedStateFromProps
- oracle - 是否可以将 DBMS_SQLHASH.GETHASH 与绑定变量一起使用?
- vba - VBA如何在使用特定字符串时验证单元格?
- sql - 根据最高值比较分组值
- if-statement - SAS %If else 宏
- javascript - 使用powershell更改js文件中的this.Apiurl