Hello,
I'm trying to write a function to generate custom grouped bar plots which include group totals (achieved) and bar totals (not achieved).
Here is an example of what I’m hoping for:
How can I add the totals on the right edges of the bars?
I used the following code to produce a function giving me the group totals.
library(tidyverse)
library(rlang)
#>
#> Attaching package: 'rlang'
#> The following objects are masked from 'package:purrr':
#>
#> %@%, as_function, flatten, flatten_chr, flatten_dbl,
#> flatten_int, flatten_lgl, flatten_raw, invoke, list_along,
#> modify, prepend, splice
my.dt <- data.frame(
X = sample(c("Black","Blue","Red","Green","Violet"), 1000, replace = TRUE),
Y = sample(c("Yes", "No","Maybe"), 1000, replace = TRUE)
)
bar_totals <- function(.data, vallue, group_var = Y) {
vallue <- rlang::enquo(vallue)
group_var <- rlang::enquo(group_var)
.data %>%
mutate(vallue = !!vallue %>% fct_infreq() %>% fct_rev()) %>%
ggplot(aes(x=vallue,..count..,fill=!! group_var))+
geom_bar()+
geom_text(stat = "count", aes(label = ..count.., y = ..count..),position=position_stack(0.5))+
theme(legend.position="top",
axis.title.y = element_blank(),
axis.title.x = element_blank(),
axis.ticks.y = element_blank())+
labs(fill = "")+
coord_flip()
}
bar_totals(my.dt, X)
# The totals I would like to add to the grouped bar graph
table(my.dt$X)
#>
#> Black Blue Green Red Violet
#> 178 216 209 204 193
Created on 2019-07-19 by the reprex package (v0.3.0)
I would really appreciate the help.
André