I'm trying to create a line chart using highcharts package with a time series dataframe that is similar to this one:
reprexDF <- data.frame(category = c("apples","oranges","bananas","limes"),
month1 = c(5,8,10,2),
month2 = c(NA,7,2,3),
month3 = c(NA, NA, 10,2),
month4 = c(11,12,5,9)
)
I want each row to be a separate line on the line chart that shows the trend for each category across months, all plotted on the same chart.
I tried parsing each row into a list with:
reprexDF <- highcharter::list_parse2(reprexDf)
and then attempting to plot with:
highchart() %>%
hc_plotOptions(line = list(marker = list(enabled = FALSE)))%>%
hc_add_series_list(reprexDF)
but I'm still not being able to plot this data.
I just really want to avoid having to hard code each series because the lists are supposed to be dynamic.
Would first convert your data frame to long. Then you can group_by
category and use list_parse2
to make lists by category.
For this plot, I made sure month
was numeric on x-axis. I renamed category
to name
so it would show up in legend and labels. And added connectNulls
in case you wanted to connect points across missing values (NA
).
library(highcharter)
library(tidyverse)
reprexDF2 <- reprexDF %>%
pivot_longer(cols = -category, names_to = "month", values_to = "value", names_pattern = "month(\\d)$") %>%
group_by(category) %>%
do(data = list_parse2(data.frame(as.numeric(.$month), .$value))) %>%
ungroup() %>%
rename(name = category)
highchart() %>%
hc_plotOptions(series = list(connectNulls = TRUE), line = list(marker = list(enabled = FALSE)))%>%
hc_add_series_list(reprexDF2)