3

what is the option/code to drop the leading zero from a R ggplot geom_bar axis?

i.e., I'd like 0.05 to appear as .05

All I can manage to find are built-in formats like percent, comma, etc.

thx!

2
  • 3
    It'a needing to be coerced to a character value at some point, so hit it with sub("^0","", vec)
    – IRTFM
    Commented Aug 4, 2014 at 22:46
  • I wonder if you can create a custom format with scales() package. I have done that to create percentage or other formats with my preferred set of decimal places. Then you can use it anywhere, such as plots, tables, labels etc.
    – Mark Neal
    Commented Mar 6, 2020 at 20:43

2 Answers 2

3

As a simple alternative inspired by the answer given by m.evans, dropping the leading zero can be be achieved quite easily using the stringr package.

library(stringr)

dropLeadingZero <- function(l){
  str_replace(l, '0(?=.)', '')
}

ggplot(data=iris, aes(x=Petal.Width, y = Sepal.Length))+
  geom_bar(stat = "identity")+
  scale_x_continuous(breaks = seq(0,2.5, by = 0.5), 
                     labels = dropLeadingZero)
2

You can write a function that you can call into the labels bit of your plot:

#create reprex
data(iris)
library(ggplot2)

#write the function
dropLeadingZero <- function(l){
  lnew <- c()
  for(i in l){
    if(i==0){ #zeros stay zero
      lnew <- c(lnew,"0")
    } else if (i>1){ #above one stays the same
      lnew <- c(lnew, as.character(i))
    } else
      lnew <- c(lnew, gsub("(?<![0-9])0+", "", i, perl = TRUE))
  }
  as.character(lnew)
}

You can then just call this in your ggplot call. Example:

ggplot(data=iris, aes(x=Petal.Width, y = Sepal.Length))+
  geom_bar(stat = "identity")+
  scale_x_continuous(breaks = seq(0,2.5, by = 0.5), 
                     labels = dropLeadingZero)

Not the answer you're looking for? Browse other questions tagged or ask your own question.