Hi, I am a bit struggle with the following code and want to add secondary Y axis (which I did) with proper counts as addition to first Y axis with percentages. Please help.
Additionally my next question is, how to adjust position of counts or percentages on bars with vjust or hjust for individual values not all of them simultaneously ?
And next if I would like to round percentages on bars to two digits, how do I do it here ?
Maybe is there a cleaner way of writing this code as well ?
Thank you for any help regarding this matter.
What I tried so far:
library(tidyverse)
#
recoded <- structure(list(Sex_recod = structure(c(1L, 1L, 1L, 2L, 2L, 2L
), .Label = c("Women", "Men"), class = "factor"), Education_recod = structure(c(1L,
2L, 3L, 1L, 2L, 3L), .Label = c("basic", "secondary", "high"), class = "factor"),
Sex_length = c(10L, 50L, 22L, 18L, 11L, 11L), Sex_prop = c(12.2,
61, 26.8, 45, 27.5, 27.5)), row.names = c(NA, -6L), groups = structure(list(
Sex_recod = structure(1:2, .Label = c("Women", "Men"), class = "factor"),
.rows = structure(list(1:3, 4:6), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -2L), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))
recoded$Education_recod <- factor(recoded$Education_recod)
recoded$Sex_recod <- factor(recoded$Sex_recod)
levels(recoded$Education_recod) <- c("basic", "secondary", "high")
levels(recoded$Sex_recod) <- c("Women", "Men")
colnames(recoded) <- c("Sex_recod", "Education_recod", "Sex_length", "Sex_prop")
ggplot(recoded, aes(x = "",
y = Sex_prop,
fill = Education_recod,
group = Education_recod)) +
geom_bar(stat = "identity", position = position_dodge(width = 0.9)) +
geom_text(aes(label = paste(Sex_prop, "%", sep = ""),
group = Education_recod),
position = position_dodge(width = 0.9),
vjust = -0.8)+
facet_wrap(~ Sex_recod) +
scale_y_continuous("Percentage (%)", sec.axis = sec_axis(~., name = "Counts")) +
scale_x_discrete("") +
theme(plot.title = element_text(hjust = 0.5), panel.grid.major.x = element_blank())+
scale_x_discrete("Divided into groups: Women and Men")+
geom_text(position=position_dodge(width = 0.9), aes(label=(Sex_length), vjust = 3.5))
#> Scale for 'x' is already present. Adding another scale for 'x', which will
#> replace the existing scale.
Created on 2021-11-13 by the reprex package (v2.0.1)