Created
January 21, 2020 23:53
-
-
Save djnavarro/c58c47faff36232b741b556d7798c498 to your computer and use it in GitHub Desktop.
Custom ggplot2 log-scale transformation that preserves sign
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
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