1

When I add a secondary axis to a plot, something weird happens with the transformation formula. I'm very confused, so I created a very simple reprex. I expect the ~ -. formula to just show negative numbers, but this doesn't work. Please help :)

library(tibble)
library(ggplot2)

dat <- tibble(x = 1:10, y = 11:20)

pl <- ggplot(dat, aes(x = x, y = y)) +
  geom_point()

# add a secondary "negative" axis as an example
pl +
  scale_y_continuous("positive", sec.axis = sec_axis(~ -., "negative!"))

# do the same on a reversed axis
pl +
  scale_y_reverse("positive", sec.axis = sec_axis(~ -., "negative!"))

# my actual formula that isn't showing up correctly
pl +
  scale_y_reverse(sec.axis = sec_axis(
                    ~ sqrt((0.0449 * 1e6) / (. - 0.167)) - 273.15,
                    "Temperature (°C)"))
Japhir
  • 564
  • 3
  • 17
  • 2
    Unfortunately this is a known problem, but they're working on it: https://github.com/tidyverse/ggplot2/issues/3133 – Brian Mar 11 '19 at 16:12
  • 1
    @Brian If that's the issue, then that would make this a duplicate of this question, right?: https://stackoverflow.com/questions/54610847/ggplot2-secondary-axis-not-mapping-to-transformation – divibisan Mar 11 '19 at 16:29

2 Answers2

1

As a workaround, you can operate on the labels rather than transforming the axis. The labels argument can be a function that takes the breaks as input and returns the labels as output:

pl +
  scale_y_continuous("positive", 
                     sec.axis = sec_axis(trans= ~ ., labels= function(x) -x, "negative!"))

or you can use the `-` function directly to save a little typing:

pl +
  scale_y_continuous("positive", 
                     sec.axis = sec_axis(trans= ~ ., labels= `-`, "negative!"))

So, for your actual use case, take the negative of your transformation, which results in positive values on the secondary axis (avoiding the transformation bug), and then make the labels the negative of those positive transformed values:

pl +
  scale_y_reverse(sec.axis = sec_axis(
    ~ -(sqrt((0.0449 * 1e6) / (. - 0.167)) - 273.15),
    labels = `-`,
    "Temperature (°C)"))
eipi10
  • 91,525
  • 24
  • 209
  • 285
  • while this solution does draw the chart again, I don't think it does so correctly, the sqrt transformation apparently is messed up in this release. – Japhir Mar 11 '19 at 17:59
1

Brian pointed me to the issue on github, in which they now mention that this will be fixed in a future release. Installing the development version of this pull request allowed me to get it to work without another workaround:

devtools::install_github("tidyverse/ggplot2#3040")
Japhir
  • 564
  • 3
  • 17