Text in barplot in R

Viewed 16970

I have a problem when adding values in a barplot in R. The problem is that I cannot place the values in the middle of each bar

balance<- c(-4.3963714,0.2335795,-0.2777250,-2.0037130,-1.2526801, -6.4556516)
barnames<-c("E1","E11","E12","E5","E7","E9")
barplot(balance,ylim=c(-8,2),col=c(if ((balance[1])>0) "blue"  else "red",(if ((balance[2])>0) "blue"  else "red"),(if ((balance[3])>0) "blue"  else "red"), (if ((balance[4])>0) "blue"  else "red"),(if ((balance[5])>0) "blue"  else "red"), (if ((balance[6])>0) "blue"  else "red")),main="Balance del Stock de Carbono",names.arg= barnames,ylab="Variacion del Stock de C kg/m2")    
abline(h=0)
text((balance/2),labels=round(balance,digits=2))

Here is the barplot:

Barplot

2 Answers

All you need is to save the x positions of the bars, returned by barplot.

You can also make the col argument much simpler. Use ifelse, the vectorized version of if.

bp <- barplot(balance, ylim = c(-8, 2), 
              col = ifelse(balance > 0, "blue", "red"),
              main = "Balance del Stock de Carbono",
              names.arg = barnames,
              ylab="Variacion del Stock de C kg/m2")

abline(h=0)
text(bp, balance/2, labels = round(balance, digits = 2))

enter image description here

If you don't mind using ggplot2, you can make the labels look a little nicer

library(tidyverse)

tibble(barnames, balance) %>% 
  mutate(lab_loc = balance/2
         , col = factor(sign(balance))) %>% 
  ggplot(aes(x = barnames, y = balance)) +
    geom_col(aes(fill = col)) +
    geom_label(aes(y = lab_loc, label = round(balance, 2))) +
    scale_fill_manual(name = 'sign', values = c('1' = 'blue', '-1' = 'red')) +
    ylab('Variacion del Stock de C kg/m2') +
    ggtitle('Balance del Stock de Carbono') +
    theme(plot.title = element_text(hjust = 0.5))

enter image description here

Related