0

I am trying to make a graph using ggplot2 with a log scale on the y-axis to plot small values, including negative values. It currently looks similar to this:

df        <- data.frame(matrix(ncol = 2, nrow = 4))
names(df) <- c("x", "y")
df$x      <- as.factor(c(1, 2, 3, 4))
df$y      <- c(0.1, 0.2, -0.3, 0.05)
ggplot(df, aes(x = x, y= y)) +
  geom_point() +
  scale_y_log10()

The plot that comes out of that looks like this:

picture log10

As you can see, one value is missing. This is a know problem, and I've seen a solution for a similar question with larger values on the x-axis: I need ggplot scale_x_log10() to give me both negative and positive numbers as output which would work out to:

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

df        <- data.frame(matrix(ncol = 2, nrow = 4))
names(df) <- c("x", "y")
df$x      <- as.factor(c(1, 2, 3, 4))
df$y      <- c(0.1, 0.2, -0.3, 0.05)
ggplot(df, aes(x = x, y= y)) +
  geom_point() +
  scale_y_continuous(trans=weird)

But this solution doesn't work for me. As that post warns, this solution doesn't work for small numbers so it comes up with nonsense:

enter image description here

How can I use a log scale for these small and negative values? In this example, all values are small and a log scale is not needed, but I have several graphs where some values are much larger and the log scale is needed to distinguish the small values from each other.

r2evans
  • 141,215
  • 6
  • 77
  • 149
Stully
  • 31
  • 3
  • 1
    Do you mean that "log is undefined for negative numbers" is a known problem? Can you sketch out what you would like the result to be? Maybe you could try a transformation that is defined for negative numbers and avoids problems of infinite limits, like a signed square root? – Gregor Thomas Jul 11 '18 at 17:48
  • Log being undefined for negative numbers may be the cause of the missing value. I want essentially what I already have in the top plot (with the missing value) but then with a similar scale in the negative direction, similar to the example I linked to (they do it on the x-axis). Problem is that their solution, as they warn, doesn't work for small (-1 to 1) values, which are exactly the kind of values I have. I ultimately want a clear plot in which all of my values can easily be distinguished, even when some are very big. If another axis transformation accomplishes that, that's also fine. – Stully Jul 12 '18 at 08:37
  • In fact I have now used the square root described here https://andrewpwheeler.wordpress.com/2015/07/31/custom-square-root-scale-with-negative-values-in-ggplot2-r/ as it fits my purpose. I'd still be interested in a logarithmic solution if anyone knows one though! – Stully Jul 12 '18 at 13:11

0 Answers0