I need ggplot scale_x_log10() to give me both negative and positive numbers as output

蓝咒 提交于 2019-12-03 20:59:09
Ben Bolker

This is possible to do by defining a new transformation (a "signed log", sign(x)*log(abs(x)); the asinh transformation suggested by Histogram with "negative" logarithmic scale in R might be more principled, or a signed square root as suggested in the comments above), but I question whether it's a good idea or not. Nevertheless ... ("Teach a man to fish and you feed him for a lifetime; give him a rope, and he can go hang himself ...") ... you can define your own axis transformations via trans_new as shown below.

Setup:

library(ggplot2); theme_set(theme_bw())
set.seed(101)
df <- data.frame(x=rnorm(5000,0,1000))

Set up the new transformation:

weird <- scales::trans_new("signed_log",
       transform=function(x) sign(x)*log(abs(x)),
       inverse=function(x) sign(x)*exp(abs(x)))

Try it out -- first on the raw points:

ggplot(df,aes(x,x))+geom_point()+
    scale_y_continuous(trans=weird)

Now on the histogram:

ggplot(df, aes(x = x)) + geom_histogram()+
    scale_x_continuous(trans=weird)

Things you should worry about:

  • this transformation is going to be nonsensical when you have values between -1 and 1
  • you might have to worry about transforming the axis of a histogram without scaling bin height appropriately: it may give you a misleading impression of the probability density -- although in this case ggplot(df, aes(x = weird$transform(x))) + geom_histogram() looks about the same as the plot above ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!