Duplication (and change) of a discrete axis in ggplot2

I want to duplicate the left Y axis on the ggplot2 graph on the right side, and then change the label labels for the discrete (categorical) axis.

I read the answer to this question , however, as you can see on the packaging the repo page , the function switch_axis_position()was removed from the package cowplot(the author quoted (future?) Own functionality in ggplot2).

I saw the reference page on the secondary axes in ggplot2, however all the examples in this document use scale_y_continuous, not scale_y_discrete. And, indeed, when I try to use a discrete function, I get an error:

Error in discrete_scale(c("y", "ymin", "ymax", "yend"), "position_d",  : 
unused argument (sec.axis = <environment>)

Is there a way to do this with ggplot2? Even a hacked solution is enough for me. Thank you in advance. (MRE 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))
+6
source share
1 answer

Take your discrete factor and represent it numerically. You can then mirror it and re-mark ticks as factor levels instead of numbers.

library(ggplot2)

irislabs1 <- levels(iris$Species)
irislabs2 <- c("foo", "bar", "buzz")

ggplot(iris, aes(Sepal.Length, as.numeric(Species))) +
  geom_point() +
  scale_y_continuous(breaks = 1:length(irislabs1),
                     labels = irislabs1,
                     sec.axis = sec_axis(~.,
                                         breaks = 1:length(irislabs2),
                                         labels = irislabs2))

Then run the script expand =in the scale, if necessary, to more accurately simulate the default discrete scale.

enter image description here

+6
source

All Articles