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!
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)
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)
sub("^0","", vec)