R - axis number format ggplot - remove leading zero

what is the option / code to reset a leading zero from the g-axis of gplplot of geometry R?

ie, I would like 0.05 to display as .05

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

THH!

+3


source to share


1 answer


You can write a function that you can call on a bit of labels

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)
}

      



Then you can just call this in your call ggplot

. 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)

      

+1


source







All Articles