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

yqlxgs2m  于 2023-10-20  发布在  Highcharts
关注(0)|答案(1)|浏览(135)

我的目标是使用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

如果有人能将代码推广到不止一种资产,我将非常感激。

km0tfn4u

km0tfn4u1#

这可以通过使用plotOptions.series.compare和HighCharts中的相关选项来解决。
继续上面的例子:

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

相关问题