问题
I have below interactive plot using highchart
js
library in 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))
I wanted to match the color of markers
based on the line color which is dynamic based on the y-value
. Currently color of all markers as set as black
which I did not want.
Any pointer how to change the color dynamically will be highly helpful
回答1:
The is no such option in the API. You need to write some custom code. The simplest way is to use chart.events.load event, loop through all points of your series, find the ones in the red or green zone and update their marker options separately. To write a JavaScript code in R, you can use JS("") function.
Here is the whole sample code:
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 Reference: 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
来源:https://stackoverflow.com/questions/62091113/how-to-change-the-color-of-marker-points-dynamically-based-on-y-position