在 ggplot2 中复制(和修改)离散轴

Duplicating (and modifying) discrete axis in ggplot2

我想将 ggplot2 图上的左侧 Y 轴复制到右侧,然后更改离散(分类)轴的刻度标签。

我已阅读 , however as can be seen on the package's repo page 的答案,switch_axis_position() 函数已从 cowplot 包中删除(作者引用(即将发布?)ggplot2 中的本机功能)。

我在 ggplot2 的辅助轴上看到了 reference 页面,但是该文档中的所有示例都使用 scale_y_continuous 而不是 scale_y_discrete。而且,确实,当我尝试使用离散函数时,出现错误:

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

有没有办法用ggplot2做这个?即使是完全破解的解决方案对我来说也足够了。提前致谢。 (以下 MRE)

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))

取离散因子并用数字表示。然后你可以镜像它并将刻度重新标记为因子水平而不是数字。

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))

然后 fiddle 根据需要在比例中使用 expand = 参数以更接近地模仿默认的离散比例。