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

Plotly蜡烛图添加散点轨迹报错:无'y'、'mode'属性求助

问题解决:Plotly蜡烛图添加散点序列报错

问题场景

使用Plotly绘制OHLC蜡烛图的代码:

pp = dff %>% 
  plot_ly(x = ~time_terminal, type="candlestick",
          open = ~open.ha, 
          close = ~close.ha,
          high = ~high, low = ~low)

尝试添加散点序列时触发警告:

>  pp %>% add_trace(y = ~close, name = 'close', mode = 'points') 
Warning message:
'candlestick' objects don't have these attributes: 'y', 'mode'
Valid attributes include:
'close', 'closesrc', 'customdata', 'customdatasrc', 'decreasing', 'high', 'highsrc', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'hovertext', 'hovertextsrc', 'ids', 'idssrc', 'increasing', 'legendgroup', 'legendgrouptitle', 'legendrank', 'line', 'low', 'lowsrc', 'meta', 'metasrc', 'name', 'opacity', 'open', 'opensrc', 'selectedpoints', 'showlegend', 'stream', 'text', 'textsrc', 'transforms', 'type', 'uid', 'uirevision', 'visible', 'whiskerwidth', 'x', 'xaxis', 'xcalendar', 'xhoverformat', 'xperiod', 'xperiod0', 'xperiodalignment', 'xsrc', 'yaxis', 'yhoverformat', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

数据集结构:

dff <- structure(list(time_terminal = structure(c(1663973640, 1663973700, 
1663973760, 1663973820, 1663973880, 1663973940), class = c("POSIXct", 
"POSIXt"), tzone = "UTC"), open.ha = c(12310.0220066959, 12308.473503348, 
12306.386751674, 12303.655875837, 12306.1654379185, 12308.9202189592
), high = c(12311.3, 12310.3, 12303.8, 12316.8, 12321.3, 12312.8
), low = c(12301.3, 12300.3, 12294.8, 12300.3, 12302.8, 12300.8
), close.ha = c(12306.925, 12304.3, 12300.925, 12308.675, 12311.675, 
12305.425)), row.names = 825:830, class = "data.frame")

报错原因

  1. 调用add_trace时未指定type='scatter',Plotly默认沿用蜡烛图的candlestick类型,而该类型不支持y和mode参数
  2. 代码中~close为无效列名,数据集实际对应的收盘价列是close.ha

解决方案

在add_trace中明确指定散点类型,同时修正y轴数据列名:

pp = dff %>% 
  plot_ly(x = ~time_terminal, type="candlestick",
          open = ~open.ha, 
          close = ~close.ha,
          high = ~high, low = ~low) %>%
  add_trace(x = ~time_terminal, y = ~close.ha, name = 'close', 
            type = 'scatter', mode = 'points', 
            marker = list(color = 'red', size = 6)) # 可选:自定义散点样式

关键说明

  • 必须指定type='scatter',明确告知Plotly这是一个独立的散点序列
  • 显式传入x参数,避免继承冲突(即使和蜡烛图x轴一致)
  • 修正y参数为数据集实际存在的close.ha列
  • 可通过marker参数自定义散点的颜色、大小等样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 19:10:50