Plotly双X双Y轴图表:调整框选缩放工具的聚焦轴对方法
解决方案
1. 将框选缩放默认聚焦x1,y1
要让框选缩放工具默认作用于x1,y1轴对,只需在布局中禁用x2,y2轴的拖拽缩放响应,同时保留x1,y1轴的响应能力。修改后的代码如下:
import plotly.graph_objects as go x1 = [1,20] y1 = [1,10] x2 = [1,20] y2 = [1,20] layout = go.Layout( xaxis=dict( title="XAxis1", dragaxis=True # 允许x1轴响应框选缩放 ), xaxis2 = dict( title="XAxis2", overlaying='x', side='top', dragaxis=False # 禁用x2轴响应框选缩放 ), yaxis=dict( title="YAxis1", range=[0,20], dragaxis=True # 允许y1轴响应框选缩放 ), yaxis2=dict( title="YAxis2", range=[0,20], side='right', dragaxis=False # 禁用y2轴响应框选缩放 ), dragmode='select' # 显式设置默认拖拽模式为框选缩放 ) fig = go.Figure(layout=layout) fig.add_trace( go.Scattergl(x=x1, y=y1, name=f'Trace 1') ) fig.add_trace( go.Scattergl(x=x2, y=y2, name=f'Trace 2', xaxis='x2', yaxis='y2') ) fig.show()
设置完成后,框选缩放工具会默认只对x1,y1对应的轨迹生效。
2. 添加单选按钮关联框选缩放工具
纯Plotly静态图表无法添加交互控件,需要使用Dash框架实现单选按钮与框选缩放的关联。通过Dash的回调函数,切换单选按钮时可动态启用/禁用对应轴对的拖拽缩放响应:
import dash from dash import dcc, html, Input, Output, State import plotly.graph_objects as go x1 = [1,20] y1 = [1,10] x2 = [1,20] y2 = [1,20] # 创建初始图表 fig = go.Figure() fig.add_trace(go.Scattergl(x=x1, y=y1, name='Trace 1')) fig.add_trace(go.Scattergl(x=x2, y=y2, name='Trace 2', xaxis='x2', yaxis='y2')) fig.update_layout( xaxis=dict(title="XAxis1", dragaxis=True), xaxis2=dict(title="XAxis2", overlaying='x', side='top', dragaxis=False), yaxis=dict(title="YAxis1", range=[0,20], dragaxis=True), yaxis2=dict(title="YAxis2", range=[0,20], side='right', dragaxis=False), dragmode='select' ) # 初始化Dash应用 app = dash.Dash(__name__) app.layout = html.Div([ dcc.RadioItems( id='trace-selector', options=[ {'label': '轨迹1 (x1,y1)', 'value': 'trace1'}, {'label': '轨迹2 (x2,y2)', 'value': 'trace2'} ], value='trace1', # 默认选中轨迹1 inline=True ), dcc.Graph(id='dual-axis-plot', figure=fig) ]) # 回调函数:切换单选按钮时更新轴的拖拽响应 @app.callback( Output('dual-axis-plot', 'figure'), Input('trace-selector', 'value'), State('dual-axis-plot', 'figure') ) def update_drag_axis(selected_trace, current_fig): if selected_trace == 'trace1': # 启用x1,y1的拖拽响应,禁用x2,y2 current_fig['layout']['xaxis']['dragaxis'] = True current_fig['layout']['xaxis2']['dragaxis'] = False current_fig['layout']['yaxis']['dragaxis'] = True current_fig['layout']['yaxis2']['dragaxis'] = False else: # 启用x2,y2的拖拽响应,禁用x1,y1 current_fig['layout']['xaxis']['dragaxis'] = False current_fig['layout']['xaxis2']['dragaxis'] = True current_fig['layout']['yaxis']['dragaxis'] = False current_fig['layout']['yaxis2']['dragaxis'] = True return current_fig if __name__ == '__main__': app.run_server(debug=True)
运行代码后,选择不同的单选按钮,框选缩放工具会自动切换到对应的轴对生效。
内容的提问来源于stack exchange,提问作者StephanT
相关产品推荐
相关产品推荐

