Hi,
I want to split a dataframe in multiple dataframes, apply a plotting function to each dataframe in order to get a ggplot2
object, and finally create a patchwork
ed plot by adding the plots together. However, something is not working:
library(dplyr)
library(ggplot2)
library(purrr)
library(patchwork)
plot_missing_values <- function(missing_value, title = NULL, ggtheme = theme_gray(), theme_config = list("legend.position" = c("bottom"))){
## Create ggplot object
output <- ggplot(missing_value, aes_string(x = "feature", y = "num_missing", fill = "group")) +
geom_bar(stat = "identity") +
geom_text(aes(label = paste0(round(100 * pct_missing, 2), "%"))) +
scale_fill_manual("Group", values = c("Good" = "#1a9641", "OK" = "#a6d96a", "Bad" = "#fdae61", "Remove" = "#d7191c"), breaks = c("Good", "OK", "Bad", "Remove")) +
scale_y_continuous(labels = scales::comma) +
coord_flip() +
xlab("Features") + ylab("Number of missing rows") +
ggtitle(title) +
ggtheme +
do.call(theme, theme_config)
}
plot_mv <- function(missing_value, mytitle){
plot_missing_values(missing_value, title = mytitle)
}
msleep_by_vore <- split(msleep, msleep$vore)
titles <- names(msleep_by_vore)
p_list <- map2(msleep_by_vore, titles, plot_mv)
print(p_list[[1]]+p_list[[2]])
#> Error in FUN(X[[i]], ...): oggetto "feature" non trovato
Basically, once I split msleep
by column vore
, I would like to use plot_mv
to create a ggplot2
object for each dataframe in the list msleep_by_vore
, with corresponding title from the character vector titles
. I thought map2
would allow me to do that, but apparently p_list
is not simply a list of ggplot2
objects (it also contains the original dataframes?). Thus, when trying to add the plots, I get an error. Can you help me?