Reputation: 684
I have data that have exponential behavior in positive and negative direction. How can I log-scale them in ggplot?
Example:
dat <- data.frame(x=sample(c(exp(runif(100,0,10)),-exp(runif(100,0,10)))))
ggplot(dat, aes(seq_along(x),x)) +
geom_point()
Not working
dat <- data.frame(x=sample(c(exp(runif(100,0,10)),-exp(runif(100,0,10)))))
ggplot(dat, aes(seq_along(x),x)) +
geom_point() +
scale_y_continuous(trans='log')
Thanks :)
Upvotes: 2
Views: 1065
Reputation: 737
The log transformation is not defined for negative values, which is why it does not work. An alternative would be to use a pseudo-log transformation, which is defined for all real numbers:
dat <- data.frame(x=sample(c(exp(runif(100, 0, 10)), -exp(runif(100, 0, 10)))))
ggplot(dat, aes(seq_along(x), x)) +
geom_point() +
scale_y_continuous(trans='pseudo_log')
Do note that for values close to zero the pseudo-log transformation approaches a linear transformation instead of a log transformation. This means a value like 0.2
will be plotted close to 0.2
, instead of close to log(0.2)
, which equals to about -1.6
.
Upvotes: 3