rggplot2transformaxis

ggplot2::sec_axis does not compute log10 values correctly


I want to replicate Figure 3.15 from Fox, J., & Weisberg, S. (2018). An R Companion to Applied Regression (3rd ed.). SAGE Publications, Inc. with the {ggplot2} package.

This is the original Figure 3.15 using the {car} package and the dataset Ornstein from the {carData} package.

graphics::par(mfrow = c(1, 2), mar = c(5, 4, 6, 2) + 0.1)

car::densityPlot( ~ assets,
             data = carData::Ornstein,
             xlab = "assets",
             main = "(a)"
             )
car::densityPlot(
          ~ base::log10(assets),
          data = carData::Ornstein,
          adjust = 0.65,
          xlab = base::expression(log[10] ~ "(assets)"),
          main = "(b)"
          )
car::basicPowerAxis(
      0,
      base = 10,
      side = "above",
      at = 10 ^ (2:5),
      axis.title = ""
      )

Created on 2024-06-13 with reprex v2.1.0

What follows is my replication with {ggplot2}:

gg1 <- carData::Ornstein |> 
  ggplot2::ggplot(
    ggplot2::aes(x = assets)
  ) +
  ggplot2::geom_density() +
  ggplot2::ylab("Density") +
  ggplot2::geom_rug() +
  ggplot2::ggtitle("(a)") +
  ggplot2::theme_bw()

gg2 <- carData::Ornstein |> 
  ggplot2::ggplot(
    ggplot2::aes(x = base::log10(assets))
  ) +
  ggplot2::geom_density(
    adjust = 0.65
  ) +
  ggplot2::labs(
    y = "Density",
    x = base::expression(log[10](assets))
  ) +
  ggplot2::geom_rug() +
  ggplot2::scale_x_continuous(
    sec.axis = ggplot2::sec_axis(
      transform = ~. ^10,
      breaks = c(100, 1000, 1e+5)
      )
    ) +
  ggplot2::theme_bw()


gridExtra::grid.arrange(gg1, gg2, ncol = 2)

Created on 2024-06-13 with reprex v2.1.0

The second x-axis in the ggplot2-example is incorrect. It should show 1e+02 corresponding to 2 and 1e+05 corresponding to 5 of the log10 scale.

What is wrong in my replication?


Solution

  • You have transform = .^10 but you meant transform = 10^.. Fixing that typo and adjusting labels = \(x) ifelse(x <= 1000, x, scales::scientific(x)) yields:

    enter image description here