在 Highcharter 中,每次导航器更改绘图区域时是否可以重新规范化数据并重新绘制数据?

问题描述 投票:0回答:1

我的目标是使用 highcharter 绘制不同金融资产的多个总回报时间序列,其中所有序列的第一个 y 轴值为 1(或 100%)。然后,当导航器更改 x 轴的可见范围时,我想重新规范化所有系列,以便它们再次从新的 x 轴范围内的 1 开始(以便我们可以比较任何时间跨度的性能)。

我能够修改现有的小提琴以对一小部分数据点执行类似的操作:https://jsfiddle.net/jgcdh46e/12/

但是我无法让以下(玩具示例)R highcharter 代码正常工作。它运行并绘制序列,但是当我移动导航栏以更改 x 轴范围时,它不会重新规范化数据。

library(quantmod)
library(highcharter)

#Use SPY as an example asset
SPY <- getSymbols('SPY', src = 'yahoo', auto.assign = FALSE)$SPY.Adjusted
SPY <- SPY / as.numeric(SPY[1]) #Normalize the data to start at 1

hc <- highchart(type = 'stock')
hc <- hc_chart(hc, events = list(
  selection = JS("function(event) {
    if (event.xAxis) {
        let min = Highcharts.numberFormat(event.xAxis[0].min, 2),
            max = Highcharts.numberFormat(event.xAxis[0].max, 2)
          
          // Get the y value of the first x value in the zoomed-in plot area
          let firstX = event.xAxis[0].min;
          let series = this.series[0];
          let firstY = null;
          for (let i = 0; i < series.data.length; i++) {
            if (series.data[i].x >= firstX) {
              firstY = series.data[i].y;
              break;
            }
          }

          // Normalize data by dividing all values by the first y value
          for (let i = 0; i < series.data.length; i++) {
            series.data[i].update(series.data[i].y / firstY);
          }
        } else { 
          
          // Restore original data when zoomed out to full range
          let series = this.series[0];
          for (let i = 0; i < series.options.data.length; i++) {
            series.data[i].update(series.options.data[i]);
          }
        }
    }")
)
)
hc <- hc_add_series(hc, SPY, type = "line", name = "SPY")
hc

我将不胜感激任何对可能出现问题的见解,并且如果有人能够将代码推广到多个资产,我将非常感激。

javascript r events highcharts r-highcharter
1个回答
0
投票

这可以通过使用 HighCharts 中的plotOptions.series.compare 和相关选项来解决。

继续上面的例子:

library(quantmod)
library(highcharter)

SPY <- getSymbols('SPY', src = 'yahoo', auto.assign = FALSE)$SPY.Adjusted
QQQ <- getSymbols('QQQ', src = 'yahoo', auto.assign = FALSE)$QQQ.Adjusted

mat <- na.omit(cbind(SPY, QQQ))
spy <- mat[,1]/as.numeric(mat[1,1])
qqq <- mat[,2]/as.numeric(mat[1,2])

hc <- highchart(type = 'stock')
hc <- hc_add_series(hc, spy, type = "line", name = "SPY")
hc <- hc_add_series(hc, qqq, type = "line", name = "QQQ")
hc <- hc_plotOptions(hc, series = list(compareStart = TRUE, compare = 'percent', compareBase = 100))
hc
© www.soinside.com 2019 - 2024. All rights reserved.