Skip to content

Instantly share code, notes, and snippets.

@djnavarro
Created January 21, 2020 23:53
Show Gist options
  • Save djnavarro/c58c47faff36232b741b556d7798c498 to your computer and use it in GitHub Desktop.
Save djnavarro/c58c47faff36232b741b556d7798c498 to your computer and use it in GitHub Desktop.
Custom ggplot2 log-scale transformation that preserves sign
library(ggplot2)
library(scales)
# transformation
log_sign_trans <- trans_new(
name = "log_sign",
transform = function(x) {sign(x) * log(abs(x))},
inverse = function(x){sign(x)} * exp(abs(x))
)
# ugly, random sign
df <- data.frame(
x = exp(rnorm(10000)) * sample(c(-1,1), 10000, TRUE)
)
# histogram on the raw scale masks outliers
p <- ggplot(df,aes(x)) +
geom_histogram()
plot(p)
# transformed version looks like this. the breaks aren't well
# placed, but can be fixed by specifying breaks argument when
# calling trans_new()
plot(p + scale_x_continuous(trans = log_sign_trans))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment