Working in highcharts where the years will be selectable….I want to include a % change from the other year in the tooltips.
Test data:
test <- tribble(
~Year, ~Type, ~Total, ~Median,
1995, 'A', 20198, 1873,
1995, 'B', 4589, 324,
1995, 'C', 12984, 1209,
1996, 'A', 3829, 2091,
1996, 'B', 3829, 3045,
1996, 'C', 3829, 9291,
1997, 'A', 14023, 1829,
1997, 'B', 16093, 2129,
1997, 'C', 1893, 529
)
Calculate percent change between the two years
percent_change <- function(year2_fig, year1_fig) {
((year1_fig - year2_fig) / year2_fig) * 100
}
How to refer to the the mouse selector position on the chart to feed in variables to this percent change function?
# --- create tooltip table ----
tooltip_category_text <- c("Median: ", "Percent change: " )
tooltip_formatted_values <- c(" {point.Median}", "{point.percent_change()}")
my_tooltips <- tooltip_table(tooltip_category_text, tooltip_formatted_values)
Chart
highchart() %>%
hc_chart(type = "column",
marginLeft = 200) %>%
hc_plotOptions(series = list(pointWidth = 18)) %>%
hc_yAxis(labels = list(style =
list(fontFamily = "Segoe UI",
fontWeight = 100), enabled =TRUE)) %>%
hc_xAxis(categories = test$Type,
labels = list(style =
list(color = '#344a5e',
fontFamily = "Segoe UI",
fontWeight = 100,
fontSize = '12px'), enabled = TRUE)) %>%
hc_add_series(dataSorting = list(enabled = TRUE),
data = test, type = 'bar', hcaes(x = Type, y = Total, group = Year),
dataLabels = list(enabled = FALSE, style = list(color ='#344a5e',
fontFamily = "Segoe UI",
fontWeight = 200))) %>%
hc_tooltip(
pointFormat = my_tooltips,
useHTML = TRUE
)
Have seen the method to use a Javascript formatter but again cannot reference a function within this…
hc_tooltip(
formatter = JS("function(){return ('Type: ' + this.point.Type +
'<br> Median : ' + this.point.test$Median ) +
'<br> Percent Change: ' + this.point.percent_change(year2, year1)}")
This tooltip formatter is only working with the first point, why not the second, and what way can I include the third?