2

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 :)

panuffel
  • 624
  • 1
  • 8
  • 15
  • 1
    The second answer here could help you : https://stackoverflow.com/questions/20924705/plot-negative-values-in-logarithmic-scale-with-ggplot-2 – Basti Jun 01 '21 at 09:22

1 Answers1

2

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.

Tim
  • 697
  • 2
  • 9
  • Nice, I didn't know about the 'pseudo_log' option. For better labels and grid lines, add for instance `breaks = c(-1, -100, -10000, 1, 100, 10000), minor_breaks = NULL` inside the `scale_y_continuous` parantheses. (`breaks` define where you have labels and grid lines, `minor_breaks` defines where you have grid lines only.) – Dag Hjermann Jun 01 '21 at 13:55