I want to duplicate the left-side Y-axis on a ggplot2 plot onto the right side, and then change the tick labels for a discrete (categorical) axis.
I've read the answer to this question, however as can be seen on the package's repo page, the switch_axis_position()
function has been removed from the cowplot
package (the author cited (forthcoming?) native functionality in ggplot2).
I've seen the reference page on secondary axes in ggplot2, however all the examples in that document use scale_y_continuous
rather than scale_y_discrete
. And, indeed, when I try to use the discrete function, I get the error:
Error in discrete_scale(c("y", "ymin", "ymax", "yend"), "position_d", :
unused argument (sec.axis = <environment>)
Is there anyway to do this with ggplot2? Even a completely hacked solution will suffice for me. Thanks in advance. (MREs below)
library(ggplot2)
# Working continuous plot with 2 axes
ggplot(mtcars, aes(cyl, mpg)) +
geom_point() +
scale_y_continuous(sec.axis = sec_axis(~.+10))
# Working discrete plot with 1 axis
ggplot(mtcars, aes(cyl, as.factor(mpg))) +
geom_point()
# Broken discrete plot with 2 axes
ggplot(mtcars, aes(cyl, as.factor(mpg))) +
geom_point() +
scale_y_discrete(sec.axis = sec_axis(~.+10))
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…