Search code examples
rhighchartsdata-visualizationtreemapr-highcharter

How to add data labels for a treemap in highcharter in r?


I want to add data labels for a treemap I have created. I am using this treemap for an image so having the pts and fgpct for each box would be helpful. I want what's listed in the tooltip and the legend to appear in each box.

My code:

library(highcharter)

gamelogs %>%
  filter(slugTeam == "MEM") %>%
  group_by(namePlayer) %>%
  summarise(pts = sum(pts), fgpct = sum(fgm) / sum(fga)) %>%
  hchart("treemap", hcaes(name = namePlayer, value = pts, color = fgpct)) %>%
  hc_title(text = "Grizzlies Scoring") %>%
  hc_subtitle(text = "Shaded by Field Goal %") %>%
  hc_chart(
    backgroundColor = '#FFFFFF' # Chart Background Color
  ) %>%
  hc_exporting(enabled = TRUE,
               filename = "Grizzlies Scoring")

My Output: Grizzlies Team Points Breakdown

The output I would like: enter image description here

This output would have the points 1,041 in the box and also the fgpct of 49% that is shown in the legend. Anyway to add the data labels using highcharter treemap?


Solution

  • Try this

    gamelogs %>%
      filter(slugTeam == "MEM") %>%
      group_by(namePlayer) %>%
      summarise(pts = sum(pts), fgpct = round(sum(fgm) / sum(fga),digits=2)) %>% 
      hchart("treemap", hcaes(name = namePlayer, value = pts, color = fgpct),
             dataLabels = list(enabled = TRUE, format='{point.namePlayer}<br/>{point.pts} pts<br/>{point.fgpct} fgpct'),
             tooltip = list(pointFormat = "{point.namePlayer}: {point.pts}, {point.fgpct}%")) %>%
      hc_title(text = "Grizzlies Scoring") %>%
      hc_subtitle(text = "Shaded by Field Goal %") %>%
      hc_chart(
        backgroundColor = '#FFFFFF' # Chart Background Color
      ) %>%
      hc_exporting(enabled = TRUE,
                   filename = "Grizzlies Scoring") %>% 
      hc_tooltip(crosshairs = TRUE)
    

    you will get this output

    output