jbkunst / highcharter

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

Grouped drilldown series names #794

Closed natalieoshea closed 1 year ago

natalieoshea commented 1 year ago

I've figured out some clean syntax for maintaining groupings in drilldowns, but when you click through the legend names default to "Series 1" and "Series 2". I'd like to make sure legend names are consistent throughout... Any ideas on how I can achieve that?

# load libraries
library(dplyr)
library(purrr)
library(tibble)
library(highcharter)

# example data
data <- as_tibble(datasets::HairEyeColor) |>
  rename_all(tolower)

# split into column and drilldown datasets
column <- data |>
  group_by(sex, hair) |>
  summarize(n = sum(n),
            # set column id to match drilldown id
            id = paste0(hair, "-", sex))

drilldown <- data |>
  group_nest(sex, hair) |>
  mutate(
    # set drilldown id to match column id
    id = paste0(hair, "-", sex),
    type = "column",
    data = data |> map(mutate, name = eye, y = n),
    data = data |> map(list_parse)
  )

# create highcharts plot
column |>
  hchart(
    "column",
    hcaes(x = hair, y = n, name = hair, drilldown = id, group = sex)
  ) |>
  hc_drilldown(
    activeAxisLabelStyle = list(textDecoration = "none"),
    allowPointDrilldown = FALSE,
    series = list_parse(drilldown)
  ) |>
  hc_yAxis(
    title = ""
  ) |>
  hc_xAxis(
    title = ""
  ) #|>
  # trying to alter legend labels
  # hc_legend(
  #   labelFormat = "{sex}"
  # )

I haven’t found an example of it successfully implemented but here’s a JSfiddle with the same functionality. You’ll notice when you click though, the legend label switches from 2010/2014 to Series1/Series2… trying to get the top-level legend labels to persist in the drilldown is proving to be challenging…

natalieoshea commented 1 year ago

internet stranger to the rescue! I thought I had tried this, but I guess I hadn’t… much simpler solve than I anticipated. It works if you simply add a series name to the drilldown dataframe:

drilldown <- data |>
  group_nest(sex, hair) |>
  mutate(
    # set drilldown id to match column id
    id = paste0(hair, "-", sex),
    name = sex, # add 'series.name' to drilldown series
    type = "column",
    data = data |> map(mutate, name = eye, y = n),
    data = data |> map(list_parse)
  )