【问题标题】:How to change the color of marker-points dynamically based on y-position如何根据 y 位置动态更改标记点的颜色
【发布时间】:2020-09-17 07:51:24
【问题描述】:

我在R 中使用highchart js 库在下面的交互式绘图中使用R

library(highcharter)
hchart(data.frame('Date' = seq(Sys.Date(), Sys.Date() - 10, by = '-1 day'), 'Value' = sample(c(-1, 1), 11, replace = T), 'variable' = 'aa') %>% mutate(color = ifelse(Value < 0, "#41c83b", "#E0245E")), 
                            "line", 
                            zIndex = 1, opacity = 0.9,
                            hcaes(x = Date, y = Value, group = variable),
                            zones = list(list(value = 0, color = hex_to_rgba("#41c83b", 1)), list(color = hex_to_rgba("#E0245E", 1))),
                            marker = list(fillColor = "#fff", lineColor = '#000', radius = 5, lineWidth = 2))

我想根据基于y-value 的动态线条颜色来匹配markers 的颜色。目前所有标记的颜色设置为black,这是我不想要的。

任何如何动态更改颜色的指针都会非常有帮助

【问题讨论】:

    标签: javascript highcharts r-highcharter


    【解决方案1】:

    API 中没有这样的选项。您需要编写一些自定义代码。 最简单的方法是使用 chart.events.load 事件,遍历系列的所有点,找到红色或绿色区域中的点,并分别更新它们的标记选项。 要在 R 中编写 JavaScript 代码,可以使用 JS("") 函数。

    这是整个示例代码:

    library(highcharter)
    hchart(data.frame('Date' = seq(Sys.Date(), Sys.Date() - 10, by = '-1 day'), 'Value' = sample(c(-1, 1), 11, replace = T), 'variable' = 'aa') %>%
             mutate(color = ifelse(Value < 0, "#41c83b", "#E0245E")), 
           "line", 
           zIndex = 1, opacity = 0.9,
           hcaes(x = Date, y = Value, group = variable),
           zones = list(list(value = 0, color = hex_to_rgba("#41c83b", 1)), list(color = hex_to_rgba("#E0245E", 1))),
           marker = list(fillColor = "#fff", radius = 5, lineWidth = 2)) %>%
      hc_chart(events = list(load = JS("function () {
        this.series[0].points.forEach(function (point) {
          if (point.y > 0) {
            point.update({
              marker: {
                lineColor: 'red'
              }
            }, false);
          } else {
            point.update({
              marker: {
                lineColor: 'green'
              }
            }, false);
          }
        });
        this.redraw();
      }")))
    

    API 参考:https://api.highcharts.com/highcharts/chart.events.load https://api.highcharts.com/class-reference/Highcharts.Chart#update https://api.highcharts.com/class-reference/Highcharts.Point#update

    【讨论】:

      猜你喜欢
      • 2018-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-03
      • 2014-08-06
      • 1970-01-01
      相关资源
      最近更新 更多