R - axis number format ggplot - remove leading zero
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 to share