rggplot2plotgraphscale

Log scale equivalent for values around 0


Is there a way to have a graph where axis are in a pseudo log scale for values between -1 and 1? I would like to have -1, -0.1, -0.01, 0, 0.01, 0.1, 1 to be equidistant on the axis.
What would be perfect would be to have a normal scale back after -1 / 1, but I would accept also to continue logarithmic if needed.

For now I use the sqrt solution mentioned here, but I have strange results when I don't trim the values of my violin plot (but maybe I just didn't understand how the trim works) and anyway I would prefer a pseudo logarithmic.

1 - When trim = TRUE (values goes from -0.68 to 2.12 as expected)

When trim = TRUE (values goes from -0.68 to 2.12 as expected)

2 - When trim = FALSE (plot goes to -1 and 3 although I don't have these values in my data)

When trim = FALSE (plot goes to -1 and 3 although I don't have these values in my data)


Solution

  • I've used scales::pseudo_log_trans() in the ggplot2::scale_x_continuous() for this (with a low sigma):

    You didnt provide reproducible data, so adding in some here:

    # Sample data
    df <- data.frame(y = seq(-1, 1, length.out = 500))
    df$x <- df$y^2  
    
    #            y         x
    # 1 -1.0000000 1.0000000
    # 2 -0.9959920 0.9920000
    # 3 -0.9919840 0.9840322
    # 4 -0.9879760 0.9760965
    # 5 -0.9839679 0.9681929
    # 6 -0.9799599 0.9603214
    # ...
    # 495 0.9799599 0.9603214
    # 496 0.9839679 0.9681929
    # 497 0.9879760 0.9760965
    # 498 0.9919840 0.9840322
    # 499 0.9959920 0.9920000
    # 500 1.0000000 1.0000000
    
    ggplot(df, aes(x, y)) +
      geom_line() +
      scale_x_continuous(
        trans = scales::pseudo_log_trans(sigma = 0.01, base = 10),
        breaks = c(-1, -0.1, -0.01, 0, 0.01, 0.1, 1)) +
      labs(y = "Transformed Value", x = "Value squared")
    

    enter image description here