Skip to content

Instantly share code, notes, and snippets.

@fegue
Last active March 12, 2019 11:06
Show Gist options
  • Select an option

  • Save fegue/8bbdc3a95656753533de5a2f28eee4d2 to your computer and use it in GitHub Desktop.

Select an option

Save fegue/8bbdc3a95656753533de5a2f28eee4d2 to your computer and use it in GitHub Desktop.
[Tidy Plot Axis - No Zeros] remove leading/trailing zeros on continouse axis in ggplot #R #ggplot
no_zero <- function(x, integer_zero = TRUE, digits = 2) {
x <- round(x, digits = digits)
y <- sprintf(paste0('%.', digits,'f'),x)
y[x > 0 & x < 1] <- sprintf('.%s',x[x > 0 & x < 1]*(10**digits))
y[x > -1 & x < 0] <- sprintf('-.%s',x[x > -1 & x < 0]*(-10**digits))
y <- gsub(pattern = "0", replacement = "", x = y)
if(integer_zero){
y[(x%%1) == 0] <- sprintf("%s", x[(x%%1) == 0])
} else {
y[x == 0] <- '0'
}
return(y)
}
## Example
# foo <- data.frame(
# x = runif(n = 100, max = 2),
# y = runif(n = 100)
# )
#
# ggplot(foo, aes(x, y)) +
# geom_point() +
# scale_x_continuous(labels = no_zero) +
# scale_y_continuous(labels = no_zero)
@fegue
Copy link
Author

fegue commented Mar 12, 2019

FIXED

Values like 0.25 become .2.5
Second dot needs to be fixed (removed)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment