【发布时间】:2019-01-17 00:06:40
【问题描述】:
将百分比添加到条形图时(请参见下面的代码),属于同一“变量”的三个百分比处于相同高度,因此未与各自的条对齐。怎么改?
#Sum plot
myd<- data.frame( var1 = rep(c("Newly infected","Mortality","TDR level"),each=3),
samp = rep(c("Scen1","Scen2","Scen3"),3),
V3 = c(3.5,2,NA,8,2,NA,4,5,NA)/1.5, V2 = c(3.5,2,NA,8,3,NA,4,4.3,NA), V1 = c(1.5,0.2,5,5,3,0.2,4,-5,2) )
# rshaping data to long form for ggplot2
library(reshape2)
library(ggplot2)
meltd<- melt(myd, id.vars=1:2)
ggplot(meltd, aes(x=var1, y=value, fill=variable)) +
geom_bar(stat="identity",position=position_dodge(width=0.6),width=0.5) +
facet_grid(samp~., switch = "y", scales = "free_y", space = "free") +
theme_bw()+
theme(legend.position = "bottom")+
theme(strip.placement = "outside")+
theme(axis.title.x = element_blank()) +
theme(axis.title.y = element_blank()) +
theme(axis.text.y = element_text(colour="black"))+
theme(strip.text.y = element_text(size = 12, colour = "black"))+
#scale_y_continuous(labels=percent,limits = c(0,1))
coord_flip()+
scale_fill_manual("legend", values = c("V3"="orange","V2" = "red", "V1" = "blue", "Baseline" = "black"))+
geom_text(data=meltd, aes(label=paste0(round(value*100,1),"%"), y=value+0.4*sign(value)), size=4)
【问题讨论】:
-
您可以在
geom_text中使用一些参数来进行水平和垂直对齐。这里有一些信息:sthda.com/english/wiki/…