1
votes

I want to display the differences of two bar charts in the tooltip. I guess that i can access these values via the formatter function. However everything i tried does not work. This is my code:

highchart() %>%
    hc_add_series(Marktvolumen$`2017`, type = "column", name = "2017") %>%
    hc_add_series(Marktvolumen$`2018`, type = "column", name = "2018") %>%
    hc_add_series(Marktvolumen$Aenderung, type = "column", name = "change", visible=FALSE, showInLegend=FALSE) %>%
    hc_xAxis(categories = Marktvolumen$Familie) %>%
    hc_plotOptions(series = list(showInLegend = TRUE, dataLabels = list(enabled = TRUE, color = "#FFFFFF"))) %>%
    hc_tooltip(formatter = JS(paste0('function () {
                       return this.y[1] - this.y[0];
    }')))

The differences are already chart object, but invisible (Marktvolumen$Aenderung). For me is does not matter if I show the difference via the series object or calculate it via javascript :-)

Here is the barchart:

enter image description here

Thank you!

1
In highcharts javascript you can do it like this: jsfiddle.net/f3o6nqd2/1. I don't know how to translate that to work in R.ewolden
unfortunately it does not render the chart when I use this formatter :(user7353167
Have you tried defining formatter callback function like here (without paste0)?: stackoverflow.com/questions/42882018/…Kamil Kulig

1 Answers

0
votes

You are using this.y, which is used when the tooltip is unshared (meaning that each column would have its own tooltip). In your case the tooltip should be shared! The parameter shared should be TRUE in function hc_tooltip, because both columns (in each "Familie") should share same tooltip.

Then you can use the variable this.points[i].y as described here: https://api.highcharts.com/highcharts/tooltip.formatter

Here is the code (without Marktvolumen$Aenderung):

Marktvolumen <- data.frame(c(72.451, 56280.439, 9020.455),
                           c(21.978, 59044.848, 9752.833),
                           c("Kuchen", "Riegel", "Süßgebäck"))
names(Marktvolumen) <- c('2017', '2018', "Familie")

highchart() %>%
  hc_add_series(Marktvolumen$`2017`, type = "column", name = "2017") %>%
  hc_add_series(Marktvolumen$`2018`, type = "column", name = "2018") %>%
  hc_xAxis(categories = Marktvolumen$Familie) %>%
  hc_plotOptions(series = list(showInLegend = TRUE,
                               dataLabels = list(enabled = TRUE,
                                                 color = "#FFFFFF"))) %>%
  hc_tooltip(formatter = JS(paste0('function ()
                                   {return "Änderung: " +
                                   (this.points[1].y - this.points[0].y);}')
                            ), shared = TRUE)

enter image description here

I hope that was helpful :)