1

可能重复:
在 ggplot2 中的堆积条形图上显示数据值

我有以下 ggplot

在此处输入图像描述

dt <- structure(list(Age.group = structure(1:5, .Label = c("0-29 yrs", "30-49 yrs", "50-64 yrs", "65-79 yrs", "80+ years"), class = "factor"),     Rx.Brufen = c(4.91767279891635, 24.849329416471, 39.384529665324,     42.0512030516413, 45.0282816501013), Brufen.C.I = c(9.49857407873833,     10.4942035949849, 11.0935906177108, 16.7322917304551, 18.5232702433842   ), Brufen.declined = c(1.25219908256281, 1.1156980249761,     1.18510539437499, 0.73845826559561, 1.00121613129538)), .Names = c("Age.group", "Rx.Brufen", "Brufen.C.I", "Brufen.declined"), row.names = c(NA, -5L), class = "data.frame")

dt.m <- melt(dt, 1)

colnames(dt.m)[2] <- "Rx"
colnames(dt.m)[3] <- "Proportion"
ggplot(dt.m, aes(x=Age.group,y=Proportion, fill=Rx)) +
    geom_bar() +
    labs(x="Age Group", y="Proportion %",fill = "") +
    theme(legend.position=c(.5, .9), legend.direction = "horizontal" ) +
    ylim(c(0,100))

我想以百分比的形式绘制实际值(在绿色和红色条的条内,蓝色条的上方,因为它们不适合里面)。有人可以建议如何实现这一目标吗?

4

2 回答 2

3
p <-  ggplot(dt.m, aes(x=Age.group,y=Proportion, fill=Rx)) +
geom_bar() +
labs(x="Age Group", y="Proportion %",fill = "") +
theme(legend.position=c(.5, .9), legend.direction = "horizontal" ) +
ylim(c(0,100))

library(plyr)
dt.m.text <- ddply(dt.m, .variables="Age.group", transform, text.y=cumsum(Proportion))
p+geom_text(data=dt.m.text, aes(x = Age.group, y = text.y, label = round(Proportion)))
#close

dt.m.text <- ddply(dt.m, .variables="Age.group", transform, text.y = cumsum(Proportion)-1/2*Proportion)
p+geom_text(data=dt.m.text, aes(x=Age.group,y=text.y, label=round(Proportion)))

#manually increase Brufen.declined
up <-  dt.m.text[dt.m.text$Rx=="Brufen.declined","text.y"]
dt.m.text[dt.m.text$Rx=="Brufen.declined","text.y"] <- up + 1
p+geom_text(data=dt.m.text, aes(x=Age.group,y=text.y, label=round(Proportion)))
于 2012-10-09T10:16:57.497 回答
0

在您定义数据dt以查找标签位置后添加这个 - 根据您的需要:

p=dt
p[,4]=p[,4]+p[,3]+p[,2]
p[,3]=p[,3]/2+p[,2]
p[,2]=p[,2]/2
p.m = melt(p)
colnames(p.m)[2:3]=c("Rx","Proportion")

并将这部分添加到您的ggplot命令中:

+ geom_text(aes(Age.group, `Proportion`, label = sprintf("%2.1f", `Proportion`)), data=p.m) 
于 2012-10-09T10:22:15.133 回答