'misalign of segments in R plotbar

I am using this code to generate a barplot with localization of Mean, Median and Mode:

I define the mode as

    mode <- function(v) {
     uniqv <- unique(v)
     uniqv[which.max(tabulate(match(v, uniqv)))]
     }

and plot the bar plot with the barplotfunction of base R:

   x <- rep(c(1,2,3,4,5,6,7,8,9,10),times=c(1,30,20,15,10,5,4,3,2,1))
   a = min(x)
   b = max(x)

  pacman::p_load(latex2exp)

  barplot(table(x),col="royalblue",
  ylab=expression(F[y]),xlab="y", main="",axis.lty=1,ylim=c(0,34))
  segments(x0 = mean(x),x1 = mean(x), y0=0,y=31)
  text(x=mean(x),y=33,TeX(r'($\bar{Y}$)'))
  segments(x0 = median(x),x1 = median(x), y0=0,y=31)
  text(x=median(x),y=33,TeX(r'($\tilde{Y}$)'))
  segments(x0 = mode(x),x1 = mode(x), y0=0,y=31)
  text(x=mode(x),y=33,TeX(r'($Mo$)'))

This is the final plot:

Bar plot with mean, median, mode

My question is since median(x)=3 and mode(x)=2 why aren't the segments aligned with the "3" and "2" x-axis label in barplot? Any idea? Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source