Search code examples
rhighchartsr-highcharter

How to create a tooltip chart in r using highcharter?


I am using highcharter library and referred to below link to create an interactive tooltip chart in a bubble chart

https://jkunst.com/blog/posts/2019-02-04-using-tooltips-in-unexpected-ways/

Plot image:

enter image description here

Using gapminder data as shown in link I was able to reproduce the same but when I use my other data then the tool tip chart doesn't appear.

Code for my other data:

libs

library(tidyverse)
library(highcharter)

data

grouped_cases_df <- read.csv("https://raw.githubusercontent.com/johnsnow09/covid19-df_stack-code/main/grouped_cases.csv")
tt_base <- grouped_cases_df %>% 
  arrange(desc(Date)) %>% 
  distinct(Country.Region, .keep_all = TRUE)

tt_base 
tt_inner <- grouped_cases_df %>% 
  select(Country.Region, Date, Daily_cases) %>% 
  nest(-Country.Region) %>% 
  mutate(
    data = map(data, mutate_mapping, hcaes(x = Date, y = Daily_cases), drop = TRUE),
    data = map(data, list_parse)
  ) %>% 
  rename(tt_nestdata = data)

tt_inner
tt_daily <- left_join(tt_base, tt_inner, by = "Country.Region")

tt_daily
hchart(
  tt_daily,
  "point",
  hcaes(x = Active, y = Confirmed, name = Country.Region,
        size = Daily_cases, group = continent, name = Country.Region) 
) %>% 
  
  hc_yAxis(type = "logarithmic") %>%
  
  hc_tooltip(
  useHTML = TRUE,
  headerFormat = "<b>{point.key}</b>",
  pointFormatter = tooltip_chart(accesor = "tt_nestdata")
  ) %>% 
  
  hc_title(text = "Active Vs Confirmed Cases as of latest Date") %>% 
  hc_subtitle(text = "Size of bubble based on Deaths <br> (ttchart: population growth)")

Issue: Getting blank tooltip chart for every country.

enter image description here

I also tried by changing Country.Region to as.factor() but didn't help. I am not sure whats wrong with this.


Solution

  • It's needed make two changes:

    1. The tooltip data needs to be ready to highcharter. So you need to transform the Date column from text to date then to a numeric value which highcharts can interpret as date:
    mutate(Date = highcharter::datetime_to_timestamp(lubridate::ymd(Date)))
    
    1. Then, in the hc_opts argument in the tooltip_chart function you need to specify the x Axis treat the values as date.
    pointFormatter = tooltip_chart(accesor = "tt_nestdata", hc_opts = list(xAxis = list(type = "datetime")))
    

    Then:

    enter image description here