Skip to content

Instantly share code, notes, and snippets.

@munoztd0
Created August 26, 2022 15:07
Show Gist options
  • Save munoztd0/c860717d1f29e8a1b9114c46e945202e to your computer and use it in GitHub Desktop.
Save munoztd0/c860717d1f29e8a1b9114c46e945202e to your computer and use it in GitHub Desktop.
Generate grouped boxplot in echarts4R
#' Generate grouped boxplot
#'
#' @description A helper to generate echarts4r grouped boxplots.
#'
#' @param var continous dependent variable (y).
#' @param grouped continous dependent variable (x).
#' @param data data to use.
#' @param title Plot title.
#' @param connect Group to connect echarts obejcts to.
#' @param top legend position.
#'
#' @export
#'
#'
generate_grouped_boxplot <- function(
data,
var,
grouped,
title = "",
connect = NULL,
top = 275
){
df <- split(data, data %>% select(!!quo_name(grouped)))
lst <- levels(as.factor(data[which(colnames(data) == grouped)][[1]]))
grps <- list() # data in groups
seriesData <- list() # series
for (grp in 1:length(lst)) {
seriesData <- list(df[[grp]][[which(colnames(data) == var)]])
tmp <- lapply(seriesData, boxplot.stats)
grps[[grp]] <- lapply(tmp, function(x) x$stats)
grps[[grp]] <- lapply(grps[[grp]], round, 2)
}
e <- e_chart()
for (grp in 1:length(lst)) {
e$x$opts$series[[grp]] <- list(
name = lst[grp],
type = "boxplot",
data = grps[[grp]]
)
}
e$x$opts$xAxis <- list(
type = "category",
data = as.list(c(as.character(var))),
boundaryGap = TRUE,
nameGap = 30,
axisLabel = list(formatter = "")
)
e$x$opts$legend$data <- as.list(lst)
e$x$opts$tooltip <- list(
trigger = "item",
axisPointer = list(type = "shadow")
)
e %>%
e_title("text" = title) %>%
e_legend( top = top) %>%
e_toolbox_feature(feature = "saveAsImage") %>%
e_toolbox_feature(feature = "dataView") %>%
e_connect_group(connect)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment