1

When adding the percentages to the barplots (see code below), the three percentages that belong to the same "variable" are on the same height, and thus not aligned to their respective bar. How to change that?

#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

mnm
  • 1,962
  • 4
  • 19
  • 46
Anthony Hauser
  • 659
  • 1
  • 6
  • 14
  • 1
    There are some parameters you can use within `geom_text` for horizontal and vertical alignment. Some info here: http://www.sthda.com/english/wiki/ggplot2-barplots-quick-start-guide-r-software-and-data-visualization – AntoniosK Aug 09 '18 at 13:40

1 Answers1

1

Do you mean this?

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

Use position = position_dodge(width = 0.6) inside geom_text to dodge labels (equivalent to dodging the bars in geom_bar).

Axeman
  • 32,068
  • 8
  • 81
  • 94
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68