Created
August 26, 2022 15:07
-
-
Save munoztd0/c860717d1f29e8a1b9114c46e945202e to your computer and use it in GitHub Desktop.
Generate grouped boxplot in echarts4R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' 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