jbkunst / highcharter

R wrapper for highcharts
http://jkunst.com/highcharter/
Other
719 stars 148 forks source link

Additional variable in hover tooltips #13

Closed royfrancis closed 8 years ago

royfrancis commented 8 years ago

How can we show additional variables in tooltips? Say I have a dataframe with x,y and z. df <- data.frame(x=c(4,5,6,3),y=c(2,4,3,2),z=c("A","A","A","B")) x and y are on x and y axis respectively. z is not used in anyway for plotting. Not even as grouping variable. How do I show z variable in the tooltip?

jbkunst commented 8 years ago

Hi @royfrancis !

This package is a really straight forward wrapper for highcharts. So we need to construct the data as highcharts need. So it is really useful if you study the api via examples. In particular lets see http://www.highcharts.com/demo/bubble, and click View options then look how is the data and you'll see:

   series: [{
            data: [
                { x: 95, y: 95, z: 13.8, name: 'BE', country: 'Belgium' },
                { x: 86.5, y: 102.9, z: 14.7, name: 'DE', country: 'Germany' },
                ....

To add this type of data to highcarts via highcarter we need to parse the data frame using list.parse (basically put a dataframe in a list form) function from rlist package (I change the z name colum because if the type of chart is bubble this value will be used to get the bubble's size:

So internally we'll have something like:

   series: [{
            data: [
                { x: 4, y: 2, text: 'A'},
                { x: 5, y: 4, text: 'A'},
                ....

Well TLDR. Here's the code.

library("highcharter")
library("rlist")

df <- data.frame(
  x=c(4,5,6,3),
  y=c(2,4,3,2),
  text=c("A","A","A","B"), stringsAsFactors = FALSE)

# ds: data series
ds <- list.parse(df)
names(ds) <- NULL

head(ds)

highchart() %>% 
  hc_add_serie(data = ds, name = "data.frame data",
               type = "scatter") %>% 
  hc_tooltip(headerFormat = "<b>This is a custom tooltip</b><br>",
             pointFormat = "x: {point.x} <br> y: {point.y} <br> text: {point.text}")