library(tidyverse)
library(ggplot2)
set.seed(3)
age_f <- factor(c("young","old"))
age_f <-sample(age_f, replace= T, size = 800)
awareness_rating<-sample(c(1:4), replace= T, size = 800)
risk_rating <-sample(c(1:4), replace= T, size = 800)
like_rating <-sample(c(1:4), replace= T, size = 800)
df <- data.frame(age_f, awareness_rating, risk_rating, like_rating)
df<- df %>% mutate(
across(.cols= -(c(1,2)),
.fns = ~ifelse(rbinom(n(), 1, 0.02), NA, .x))
)
df <-df %>% mutate(across(c(2:4), ~factor(.x, levels = c(1,2,3,4),
labels = c("not at all", "a little", "somewhat", "a lot"))))
what I like to do is creating the same plot with a specific format for multiple variables in the dataset using map function. So the code for creating the plot is this:
df %>% filter(!is.na(awareness_rating)) %>% group_by(age_f, awareness_rating) %>%
summarize(Count = n()) %>% mutate(pct = round(prop.table(Count)*100,0), res= str_c(pct, "%")) %>%
ggplot(aes(x=age_f, y=pct, fill=awareness_rating)) +
geom_col(width = 0.6)+ theme_bw() + theme (axis.title.x = element_blank(),
axis.text.y = element_text(size = 25, face= "bold"),
axis.title.y = element_blank(),
legend.text = element_text(size = 25),
legend.title = element_blank(),
axis.line.y.left = element_line(color = 'gray'),
panel.border = element_blank())+
geom_text(aes(label = res), position = position_stack(vjust = .5), size= 10) + coord_flip() +
scale_fill_brewer()
I want to create the plot for risk_rating and like_rating as well.
My attempt was to create function and mapping it around the three columns.
p1func<- function(df){
df %>% filter(!is.na(.x)) %>% group_by(age_f, .x) %>%
summarize(Count = n()) %>% mutate(pct = round(prop.table(Count)*100,0), res= str_c(pct, "%")) %>%
ggplot(aes(x=age_f, y=pct, fill=.x)) +
geom_col(width = 0.6)+ theme_bw() + theme (axis.title.x = element_blank(),
axis.text.y = element_text(size = 25, face= "bold"),
axis.title.y = element_blank(),
legend.text = element_text(size = 25),
legend.title = element_blank(),
axis.line.y.left = element_line(color = 'gray'),
panel.border = element_blank())+
geom_text(aes(label = res), position = position_stack(vjust = .5), size= 10) + coord_flip() +
scale_fill_brewer()
}
df %>% map_at (c(2:4), ~p1func)
However, it does not create any plots.
What am I doing wrong here? How can I achieve my goal with out copying and pasting the same code multiple times? This is not too cumbersome for 3 variables in this mock example, but I need to do that much more times in my actual data.
Your help would be really appreciated.