在barplot ggplot2中添加数字

时间:2018-08-09 13:33:48

标签: r ggplot2

在将百分比添加到条形图时(请参见下面的代码),属于同一“变量”的三个百分比处于相同的高度,因此未与各自的条对齐。如何更改?

#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)

Percentages written in barplot

1 个答案:

答案 0 :(得分:1)

你是这个意思吗?

ggplot(meltd, aes(x = var1, y = value, fill = variable, label = paste0(round(value * 100, 1), "%"))) +
    geom_bar(stat = "identity", position = position_dodge(width = 0.6), width = 0.5) +
    facet_grid(samp ~ ., switch = "y", scales = "free_y", space = "free") +
    coord_flip() +
    scale_fill_manual(
        "legend",
        values = c("V3" = "orange", "V2" = "red", "V1" = "blue", "Baseline" = "black")) +
    geom_text(aes(y = value + 0.4 * sign(value)), position = position_dodge(width = 0.6)) +
    theme_bw() +
    theme(
        legend.position = "bottom",
        strip.placement = "outside",
        axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        axis.text.y = element_text(colour="black"),
        strip.text.y = element_text(size = 12, colour = "black"))

enter image description here

position = position_dodge(width = 0.6)内使用geom_text来躲避标签(等同于躲避geom_bar中的小节)。