I am generating highcharter interactive plots in a Shiny app. The values on the x axis are dates and I have a slider that allows the user to change the min and max limits for the x axis. Except it doesn't work... there's something strange about the way hchart interprets dates. Here is a small example dataframe and plot:
df <- tibble(
visit_date = as.Date(c("2000-01-01", "2002-01-01", "2004-01-01", "2000-01-01", "2002-01-01", "2004-01-01")),
patients = c(140, 150, 120, 20, 30, 24),
level = c(rep("Yes", 3), rep("No", 3))
)
hchart(df,
"column",
hcaes(x = visit_date, y = patients, group = level), stacking = "normal") %>%
hc_yAxis(title = list(text = "Number of Patients")) %>%
hc_xAxis(title = list(text = "Visit Date"))
This code works fine and generates this plot:
But if I want to change the x axis limits, nothing works:
hchart(df,
"column",
hcaes(x = visit_date, y = patients, group = level), stacking = "normal") %>%
hc_yAxis(title = list(text = "Number of Patients")) %>%
hc_xAxis(title = list(text = "Visit Date"),
min = as.Date("2002-01-01"))
Any suggestions?
Use datetime_to_timestamp(as.Date("2002-01-01"))
to convert the date to a numeric format that Highcharts recognizes for the min parameter.
library(tidyverse)
library(highcharter)
library(dplyr)
df <- tibble(
visit_date = as.Date(c("2000-01-01", "2002-01-01", "2004-01-01", "2000-01-01", "2002-01-01", "2004-01-01")),
patients = c(140, 150, 120, 20, 30, 24),
level = c(rep("Yes", 3), rep("No", 3))
)
hchart(df,
"column",
hcaes(x = visit_date, y = patients, group = level), stacking = "normal") %>%
hc_yAxis(title = list(text = "Number of Patients")) %>%
hc_xAxis(title = list(text = "Visit Date"), min = datetime_to_timestamp(as.Date("2002-01-01")))
or filter the df with dplyr directly:
hchart(df %>% filter(visit_date >= as.Date("2002-01-01")),
"column",
hcaes(x = visit_date, y = patients, group = level), stacking = "normal") %>%
hc_yAxis(title = list(text = "Number of Patients")) %>%
hc_xAxis(title = list(text = "Visit Date"))
both will result in the desired output: