Hi,
I have a local function which calculates counts by group vars and plots via ggplot2
Here is the function definition:
plot_by_two_groups <- function(comments_df, # should be a a dataframe
group_var_y, #variable to be plotted on y axis
group_var_x,
get_all_word_counts = F,
...){
group_var_y <- enquo(group_var_y)
group_var_x <- enquo(group_var_x)
total_comments_by_group_var_y <- comments_df%>%
count(!! group_var_y) %>% rename(total_comments_by_group_var_y = n)
comments_df%>%
count(!! group_var_x,!! group_var_y)%>%
inner_join(total_comments_by_group_var_y)%>%
mutate(perc_of_comments_by_group_var_y = n/total_comments_by_group_var_y)%>%
ggplot(aes(x=!! group_var_y,y=perc_of_comments_by_group_var_y,fill=!! group_var_x))+
geom_bar(stat = "identity")+
geom_text(aes(label = paste0("(",n,")")),position = position_stack(vjust = 0.5),
fontface="bold",colour = "white") +
geom_text(aes(label=sprintf("%1.0f%%", 100*perc_of_comments_by_group_var_y)),
position = position_stack(vjust = 0.2),fontface="bold",colour = "white")+
theme_BT()+
scale_y_continuous(labels=percent)+
# scale_fill_manual(values = c("Passive"="#E60050","Detractor"="#00A0D6","Promoter"="#6400AA",
# "other"="#DDDDDD"),
# guide = guide_legend(reverse = FALSE))+
coord_flip()+
theme(axis.title.y = element_blank()) +
labs(title = "Rating Distibution by CP",
y = "% of customers",
subtitle =paste("% of customers by", quo_name(group_var_y),
"Total verbatim = ",nrow(comments_df)),
fill = NULL)
}
I have two challenges:
1- I wish to pass all the labs
via function call i.e. labs(x="example text")
2- How do i pass fill colours depending on the number of data levels (see the commented lines of scale_fill_manuel)
thanks
when I call the function like:
#debugonce(plot_by_two_groups)
verbatims%>%
filter(between(visit_date, as.Date("2018-01-01"),as.Date("2018-09-17"))) %>%
plot_by_two_groups(., # should be a a dataframe
cp_code, #variable to be plotted on y axis
NPS_RATING,
get_all_word_counts = F)
It works fine
But when i do this:
#debugonce(plot_by_two_groups)
verbatims%>%
filter(between(visit_date, as.Date("2018-01-01"),as.Date("2018-09-17"))) %>%
plot_by_two_groups(., # should be a a dataframe
cp_code, #variable to be plotted on y axis
NPS_RATING,
get_all_word_counts = F,
xlab = "example xlab")
and change the lab(y=xlab) this gives the following error:
Error in as.character(x$label) : cannot coerce type 'closure' to vector of type 'character'