這是我的計劃:4 個年齡組的結果為 0/1 的堆疊條形圖。作為geom_text標簽,我想顯示每個年齡段的百分比outcome=1。
首先,我嘗試排除Outcome =="0"using geom_text(data=subset(df, outcome=="1"),但它不起作用。
然后我將 NA 用于不需要的組百分比,以僅顯示outcome=="1". (情節 1)但是,當我用 向geom_textaes 添加“%”時paste(),NA 會重新出現。(情節2)
此外,我希望將百分比放在每個條形上方。使用 vjust,它從欄的頂部到文本標簽的距離不同。
任何提示如何實作這一目標?非常感謝!
# 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
情節1:

# 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
情節2:

uj5u.com熱心網友回復:
# 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

轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/431951.html
上一篇:用lmer繪制個體和總體回歸線
