0
votes

How can I set inward facing bar labels in a bar chart with positive and negative values in ggplot2? I.e. the bar labels should be facing the 0 axis.

df <- data.frame(trt = c("a", "b", "c", "d"), 
                 outcome = c(2.3, 1.9, 0.5, -0.5))

ggplot(df, aes(trt, outcome, label = outcome)) +
  geom_bar(stat = "identity", 
           position = "identity") + 
  geom_text(vjust = "inward", color = 'red') 

vjust = "inward" is obviously not the way to go, since "Inward and outward are relative to the physical middle of the plot, not where the 0 axes are".

Update:

geom_bar inward

1
Is geom_text(vjust=c(1, 1, 1, 0), nudge_y=c(-0.1, -0.1, -0.1, 0.4), color = 'red') something like you're after? - hrbrmstr
@hrbrmstr: In principle yes, the looks are fine (well, I'd rather use (-)0.05 for all nudge_y values, but that's just optics). My main concern is, however, that I want to make many graphs like this and I would have to adjust each graph by hand depending on the values of the variables. So overall, not quite. - dpprdan

1 Answers

2
votes

You should be able to set the vjust inside of the aes mappings to control differently for each row, here based on whether it is positive or negative:

ggplot(df, aes(trt, outcome, label = outcome)) +
  geom_bar(stat = "identity", 
           position = "identity") + 
  geom_text(aes(vjust = outcome > 0)
            , color = 'red')

enter image description here

If you want to move the labels around more precisely (instead of just vjust = 0 or vjust = 1 that you can get from a logical), you can use ifelse and define you positions more exactly:

ggplot(df, aes(trt, outcome, label = outcome)) +
  geom_bar(stat = "identity", 
           position = "identity") + 
  geom_text(aes(vjust = ifelse(outcome > 0
                               , 1.5, -0.5) )
            , color = 'red'
            )

enter image description here