Plotly堆叠子图水平滚动条覆盖中间子图的修复咨询
共享X轴Plotly堆叠子图添加水平滚动条的布局修复
问题场景
用Plotly创建了3行共享X轴的堆叠子图,想要在底部添加水平滚动条,但添加后滚动条覆盖中间子图,且首个子图显示异常,原代码如下:
from plotly.subplots import make_subplots import plotly.graph_objects as go fig = make_subplots(rows=3, cols=1, shared_xaxes=True, vertical_spacing=0.02) fig.add_trace(go.Scatter(x=[0, 1, 2, 3], y=[10, 11, 12, 13]), row=3, col=1) fig.add_trace(go.Scatter(x=[0, 1, 2, 3], y=[100, 110, 120, 130]), row=2, col=1) fig.add_trace(go.Scatter(x=[0, 1, 2, 3], y=[1000, 1100, 1200, 1300]), row=1, col=1) fig.update_layout(height=500,xaxis=dict(rangeslider=dict(visible=True), type="linear")) fig.show()
修复方案
问题出在给默认的xaxis添加滚动条,而共享X轴的布局里,最底部的子图对应的是xaxis3(行索引从1开始,第3行的x轴),直接修改xaxis会干扰上层子图的布局。正确做法是给最底部的x轴添加滚动条,同时适当调整垂直间距避免挤压:
修改后的代码:
from plotly.subplots import make_subplots import plotly.graph_objects as go fig = make_subplots(rows=3, cols=1, shared_xaxes=True, vertical_spacing=0.05) # 适当增大垂直间距,给滚动条留出空间 fig.add_trace(go.Scatter(x=[0, 1, 2, 3], y=[10, 11, 12, 13]), row=3, col=1) fig.add_trace(go.Scatter(x=[0, 1, 2, 3], y=[100, 110, 120, 130]), row=2, col=1) fig.add_trace(go.Scatter(x=[0, 1, 2, 3], y=[1000, 1100, 1200, 1300]), row=1, col=1) # 给最底部的第3行x轴添加滚动条 fig.update_layout(height=500) fig.update_xaxes(rangeslider=dict(visible=True), type="linear", row=3, col=1) fig.show()
关键改动说明
- 增大
vertical_spacing值,避免滚动条挤压中间子图 - 使用
update_xaxes指定针对第3行的x轴添加滚动条,不会影响共享X轴的其他子图布局
内容的提问来源于stack exchange,提问作者intrigued_66
相关产品推荐
相关产品推荐

