Here is my plan: a stacked barchart with outcome 0/1 in 4 age groups.
As geom_text
labels, I want to show the percentages per age group for outcome=1
.
First I tried to exclude the Outcome =="0"
using geom_text(data=subset(df, outcome=="1")
, but it did not work.
Then I put NA's for the unwanted group percentages, to only show the percentages where outcome=="1"
. (plot 1)
However, when I add a "%" to the geom_text
aes with paste()
, the NA re-appears. (plot 2)
Furthermore, I wish to put the percentages above each bar. With vjust, it has different distances from the top of the bar to the text label.
Any hints how to achieve this? Many Thanks!
# generating data frame
n <- c(450,20,470,30,750,40,650,35)
age_group <- as.factor(c("neonate","neonate", "infant","infant", "child", "child", "adolescent","adolescent"))
outcome <- as.factor(c(0,1,0,1,0,1,0,1))
percent <- c(NA,20/470, NA, 30/500,NA, 40/790,NA,35/685)
# convert to factors and adjust label order
df <- data.frame(n, age_group, outcome, percent)
df$age_group <- factor(df$age_group, levels=c("neonate","infant","child","adolescent"))
df$outcome <- factor(df$outcome, levels =c("1","0"))
# Plot 1: percentages not in place, missing "%" sign
p1 <- ggplot(df, aes(x=age_group, y=n, fill=outcome))
geom_bar(stat="identity")
geom_text(aes(label=round(percent*100,1)))
p1
Plot1:
# Plot 2: with percentages, not in place, by adding "%", the NA values appeard
p2 <- ggplot(df, aes(x=age_group, y=n, fill=outcome))
geom_bar(stat="identity")
geom_text(aes(label=paste(round(percent*100,1), "%")))
p2
Plot2:
CodePudding user response:
# generating data frame
n <- c(450,20,470,30,750,40,650,35)
age_group <- as.factor(c("neonate","neonate", "infant","infant", "child", "child", "adolescent","adolescent"))
outcome <- as.factor(c(0,1,0,1,0,1,0,1))
percent <- c(NA,20/470, NA, 30/500,NA, 40/790,NA,35/685)
# convert to factors and adjust label order
df <- data.frame(n, age_group, outcome, percent)
df$age_group <- factor(df$age_group, levels=c("neonate","infant","child","adolescent"))
df$outcome <- factor(df$outcome, levels =c("1","0"))
per <- paste(round(percent*100,1),"%")
per[per == "NA %"] <- ""
# Plot 1: percentages not in place, missing "%" sign
p1 <- ggplot(df, aes(x=age_group, y=n, fill=outcome))
geom_bar(stat="identity")
geom_text(
aes(x = age_group, y = n, label = per, group = outcome),
position = position_stack(),
vjust = -0.5, size = 3.5
)
p1