I have this data:
library(highcharter)
library(dplyr)
the_dates <- as.Date(c(rep("2021-01-01",3),
rep("2021-02-01",3)))
the_values <- c(2,3,4,5,6,7)
the_group <- c("Group_A","Group_B","Group_B",
"Group_A","Group_B","Group_B")
the_class <- c("X","Y","Z",
"X","Y","Z")
the_data <- data.frame(the_dates,
the_group,
the_class,
the_values,
stringsAsFactors = FALSE)
> the_data
the_dates the_group the_class the_values
1 2021-01-01 Group_A X 2
2 2021-01-01 Group_B Y 3
3 2021-01-01 Group_B Z 4
4 2021-02-01 Group_A X 5
5 2021-02-01 Group_B Y 6
6 2021-02-01 Group_B Z 7
And I want to create a drill down plot. So I would like to see the groups and if I drill down, I would like to see the class. What I have tried is:
the_data %>%
hchart(
type = "spline",
hcaes(x = the_dates, y = the_values, drilldown = the_class),
colorByPoint = TRUE)
But the link to drill down is in the dates. Any help will be greatly appreciated.
Here's one potential solution with a few caveats.
I had some issues with as.Date()
in the drilldown x axis names, so I've left them as characters. I've also done a quick mean()
on the the_values
by the_date
so there's actually something to drilldown to.
library(highcharter)
library(dplyr)
library(purrr) # for the map() function
the_dates <- c(rep("2021-01-01",3),
rep("2021-02-01",3))
the_values <- c(2,3,4,5,6,7)
the_group <- c("Group_A","Group_B","Group_B",
"Group_A","Group_B","Group_B")
the_class <- c("X","Y","Z",
"X","Y","Z")
the_data <- data.frame(the_dates,
the_group,
the_class,
the_values,
stringsAsFactors = FALSE)
mean_data <- the_data %>%
group_by(the_dates) %>%
summarise(mean_values = mean(the_values))
drill_data <- the_data %>%
group_nest(the_dates) %>%
mutate(
id = the_dates,
type = "column",
data = map(data, ~ .x %>%
mutate(
name = the_class,
y = the_values
) %>%
list_parse())
)
Now let's build the plot:
mean_data %>%
hchart(
type = "spline",
hcaes(x = the_dates, y = mean_values, drilldown = the_dates, name = the_dates),
name = "Dates",
colorByPoint = TRUE) %>%
hc_drilldown(
allowPointDrilldown = TRUE,
series = list_parse(drill_data)
)