2

This is an extension question to: How to put labels over geom_bar for each bar in R with ggplot2

My data has some negatives and so the labels intrude into the bar. How can I adjust this? I need the label placements to be read dynamically.

Thanks!

growth<-data.frame(ElapsedTimeMonths=c(3,6,12,24),MedianGrowth=c(-0.011,-0.002,0.014,0.052))
g<-ggplot(growth, aes(x=factor(ElapsedTimeMonths),y=MedianGrowth))
g<-g+geom_bar(position="dodge", stat="identity")
g<-g+scale_y_continuous(labels = percent)
g<-g+geom_text(aes(label=as.character(100*MedianGrowth)), position=position_dodge(width=0.9), vjust=-0.25)
g

enter image description here

Community
  • 1
  • 1
user1100825
  • 107
  • 1
  • 5

1 Answers1

3

Graphical parameter settings can be vectors so that different shapes (geom text here)can have different appearances.

You need to give vjust as a vector, with opposite sign of MedianGrowth

Your data

growth <- data.frame(ElapsedTimeMonths=c(3,6,12,24),
                   MedianGrowth=c(-0.011,-0.002,0.014,0.052),
                  )

I create the vjust vector

 vvjust <- rep(1, length(growth$MedianGrowth))
 vvjust[growth$MedianGrowth > 0 ] <- -0.25
 [1]  1.00  1.00 -0.25 -0.25

Then I plot

g<- ggplot(growth, aes(x=factor(ElapsedTimeMonths),y=MedianGrowth))
g<- g+ geom_bar(stat='identity',position='dodge')
g<- g+ scale_y_continuous(labels = percent)
g<- g+ geom_text(aes(label=as.character(100*MedianGrowth)), 
                 position=position_dodge(width=0.9), vjust=vvjust)

enter image description here

agstudy
  • 119,832
  • 17
  • 199
  • 261