DMC DMC - 1 month ago 23
R Question

Duplicating Discrete Axis in ggplot2

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() +
...?

42- 42-
Answer

The cowplot library has 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