Last active
March 12, 2019 11:06
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FIXED
Values like 0.25 become .2.5
Second dot needs to be fixed (removed)