You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Plotly的make_subplots绘制不同时间X轴的子图?

解决Plotly make_subplots不同时间索引子图显示异常问题

你的问题出在设置了shared_xaxes=True——当两个子图的X轴是不同的datetime时间索引时,共享X轴会强制将两个子图的时间轴对齐,导致其中一个子图的蜡烛图被压缩甚至显示异常。

解决方案:

  • 关闭共享X轴,让每个子图拥有独立的时间轴
  • 显式指定X轴类型为datetime,确保时间渲染正确
  • 调整布局优化标签显示

修改后的代码如下:

import plotly.graph_objects as go
from plotly.subplots import make_subplots

# 创建子图,关闭共享X轴
fig = make_subplots(rows=2, cols=1, row_heights=[0.5, 0.5], shared_xaxes=False)

# 添加上方子图蜡烛图
fig.add_trace(go.Candlestick(
    x=dfpl.index,
    open=dfpl['open'],
    high=dfpl['high'],
    low=dfpl['low'],
    close=dfpl['close']
), row=1, col=1)

# 添加下方子图蜡烛图
fig.add_trace(go.Candlestick(
    x=dfDiv.index,
    open=dfDiv['open'],
    high=dfDiv['high'],
    low=dfDiv['low'],
    close=dfDiv['close']
), row=2, col=1)

# 显式设置两个X轴为datetime类型
fig.update_xaxes(type='datetime', row=1, col=1)
fig.update_xaxes(type='datetime', row=2, col=1)

# 调整布局,避免X轴标签重叠,优化显示高度
fig.update_layout(
    height=600,
    xaxis=dict(showticklabels=True),
    xaxis2=dict(showticklabels=True)
)

fig.show()

如果需要保留子图缩放联动但不强制时间轴对齐,可以将shared_xaxes设为'columns'并添加matches=None,但对于你的场景,直接关闭共享X轴是最简洁有效的解决方式。

内容的提问来源于stack exchange,提问作者Ali Afkari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 01:35:11