我在下面有使用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))
我想根据基于markers
动态的线条颜色来匹配y-value
的颜色。当前所有标记的颜色设置为我不想要的black
。
任何指针如何动态更改颜色将非常有帮助
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.loadhttps://api.highcharts.com/class-reference/Highcharts.Chart#updatehttps://api.highcharts.com/class-reference/Highcharts.Point#update