I am trying to plot multiple graphs using a function. Now the function is supposed to loop and plot charts per hospital and also group by birth weight group.
The function looks like this
myplott <- function(actual_data, hospital, weightsgrp) {
print(paste0("Plot for hospital: ", hospital))
p <- ggplot(actual_data %>% filter(hosp_id == hospital , weight.group == weightsgrp),
aes(x = format(date_discharge,"%b"), y = as.numeric(mortality),
group = weightsgrp)) +
facet_wrap(~weight.group) +
geom_bar( stat = "identity") +
theme_bw() +
ylab("Percentage %") +
ggtitle(hospital) +
theme(axis.text.x = element_text(size = 13, hjust = 1, angle = 45)) +
theme(plot.title = element_text(face = "bold", hjust = 0.5, size = 20), legend.position = "top") +
theme(legend.title = element_blank())
return(p)
print(p)
}
The function works well and I am able to generate a plot for a single hospital this way
myplott(actual_data, "hospital name", "weight group")
Now here is my problem.
When I map my function using purr so that to generate multiple plots, it works well. I do it this way
plot_list <- unique(actual_data$hosp_id) %>%
purrr::set_names() %>%
purrr::map( ~ myplott(actual_data, .x,"weightsgrp"))
Thereafter I create a string of plots this way
str(plot_list, max.level = 1)
So then I do a purr::walk so that to visualize all charts per hospital
purrr::walk(plot_list, print)
When I ran purr::walk I get this error
Error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (1): x and y
I look at aesthetics and I see everything is okey, what am I missing?