Python Plotly嵌套循环绘制测井图出现重叠问题求助
测井图绘制重叠问题解决方案
问题描述
使用嵌套for循环通过Plotly自动化绘制测井图时,第一个循环生成的Well 1F曲线会重叠在第二个循环生成的Well 2F图上,导致第二个图出现双重曲线叠加的异常效果;预期效果应为每个井的测井图仅显示自身的曲线,无重叠。
问题原因
你将make_subplots()创建图对象的代码写在了外层循环之外,所有井的曲线都被添加到了同一个logplot对象中:第一次循环为Well 1F添加完曲线后,第二次循环没有重置图对象,直接在原有基础上继续添加Well 2F的曲线,最终两个井的曲线重叠在一起。
解决方案
将创建子图对象的代码移至外层循环内部,确保处理每个井时都新建一个独立的空白图对象,让每个井的绘图操作在全新的图上进行。
修改后的完整代码
#Read all the well log data paths = sorted(glob.glob(os.path.join("well_contoh", "*.LAS"))) well_df = [0]*2 for i in range(len(paths)): well = lasio.read(paths[i]) df = well.df() well_df[i] = df.reset_index() well1, well2 = well_df #only 2 wells #Automatic well log plots if any well log data comes in in the future html_list = [] dataframe_well = {'Well 1F':well1, 'Well 2F':well2} #defining dataframe wells = ['Well 1F','Well 2F'] #list of well for looping #list of longitude and latitude for well 1 and well 2 respectively (a dummy coordinate) Longitude = [96.083956, 96.356427] Latitude = [5.456862, 5.328133] #list of logs and their colors logs = ['CALI', 'GR', 'RT', 'NPHI', 'RHOB', 'DT'] colors = ['black', 'green', 'red', 'royalblue', 'mediumaquamarine', 'goldenrod'] #plot log_cols = np.arange(1,8) # 每次处理一个井时,新建独立的子图对象 for i in range(len(wells)): logplot = make_subplots(rows=1, cols=len(logs), shared_yaxes = True, specs=[[{},{},{},{},{},{}]], horizontal_spacing=0.005) for j in range(len(logs)): if j == 2: logplot.add_trace(go.Scatter(x=dataframe_well[wells[i]][logs[j]], y=dataframe_well[wells[i]]['DEPTH'], name=logs[j], line_color=colors[j]), row=1, col=log_cols[j]) logplot.update_xaxes(type='log', row=1, col=log_cols[j], title_text=logs[j], tickfont_size=12, linecolor='#585858') else: logplot.add_trace(go.Scatter(x=dataframe_well[wells[i]][logs[j]], y=dataframe_well[wells[i]]['DEPTH'], name=logs[j], line_color=colors[j]), row=1, col=log_cols[j]) logplot.update_xaxes(col=log_cols[j], title_text=logs[j], linecolor='#585858') logplot.update_xaxes(showline=True, linewidth=2, linecolor='black', mirror=True, ticks='inside', tickangle=45) logplot.update_yaxes(tickmode='linear', tick0=0, dtick=250, showline=True, linewidth=2, ticks='outside', mirror=True, linecolor='black') logplot.update_yaxes(row=1, col=1, autorange='reversed') logplot.update_layout(height=700, width=800, showlegend=False) logplot.update_layout( title_text="Example of " + '<b>' + str(wells[i]) + '</b>', #Add a chart title title_font_family="Arial", title_font_size = 25, title_x=0.5) logplot.write_html('fig'+str(wells[i])+'.html') # the plot is automatically saved as html #list html plots to show what pop up folium should show on the map html_list.append('fig'+str(wells[i])+'.html')
关键修改点
- 将
logplot = make_subplots(...)从循环外移到for i in range(len(wells)):循环的第一行,确保每个井对应一个全新的图对象。 - 每次循环都会创建空白子图,添加当前井的所有曲线,保存后再处理下一个井,彻底避免曲线叠加问题。
内容的提问来源于stack exchange,提问作者naranara
相关产品推荐
相关产品推荐

