2

The development version of ggplot2 (2.1.0.9001) provides a nice shorthand for creating a secondary axis that is a duplication of the primary axis if the original axis is continuous:

devtools::install_github("hadley/ggplot2")
library(ggplot2)

ggplot(mpg, aes(displ, cyl)) + 
  geom_point() + 
  scale_y_continuous(
    sec.axis = dup_axis()
  )

How can a discrete axis be duplicated?

ggplot(mpg, aes(displ, factor(cyl))) + 
  geom_point() +
  ...?
davechilders
  • 8,693
  • 2
  • 18
  • 18

1 Answers1

1

The switch_axis_position is now deprecated, and in fact is gone. Issues with ggdraw since ggplot2 update

Outdated material: The cowplot library has used to have that that facility:

library(cowplot)
gpv <- ggplot(mpg, aes(displ, factor(cyl))) + 
   geom_point()
ggdraw( switch_axis_position( gpv, axis="y", keep="y"))

Don't forget that you need to print grid-based graphics when sending to a file:

png()
  print(ggdraw(switch_axis_position(gpv, axis="y", keep="y")) )
dev.off()
#quartz 
#     2 

enter image description here

IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • The `switch_axis_position` is now deprecated, and in fact is gone. https://stackoverflow.com/questions/42322303/issues-with-ggdraw-since-ggplot2-update – Edward Apr 09 '20 at 03:34
  • I think this question and answer should be kept. I just wanted to add a comment so that if anyone came to this post (by searching on keywords - like me !!), then they would realize why that function didn't exist anymore. I'm still trying to figure out a way to duplicate a discrete y-axis. – Edward Apr 09 '20 at 06:29
  • I think editing the question will save future users time. – IRTFM Apr 09 '20 at 19:23