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

标签 r ggplot2 tidyverse

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

我已阅读 this question 的答案,但是可以看出on the package's repo pageswitch_axis_position() 函数已从 cowplot 包中删除(作者引用了(即将推出?)ggplot2 中的 native 功能)。

我已经看到了reference ggplot2 中辅助轴的页面,但是该文档中的所有示例都使用 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))

然后根据需要调整比例中的 expand = 参数,以更接近地模仿默认的离散比例。

enter image description here

关于r - 在 ggplot2 中复制(和修改)离散轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45361904/

相关文章:

r - 在 Caret 中使用 frbs 包中的 SBC 时出现错误 "Something is wrong; all the RMSE metric values are missing"

r - 使用 `glue` 将一列中的变量替换为另一列中的变量

r - ggplot2:具有阶乘 x 轴的 geom_area

r - 将透明 ggplots 从 Rstudio 导出到 PowerPoint 是否有更好的解决方法?

r - dplyr + ggplot2 : Plotting not working via piping

R:将 mutate 调用从处理三个二进制变量调整为处理 n 个二进制变量

r - 如何更改ggplot对象中所有文本相对于当前值的字体大小?

使用 Gather 函数进行 R 数据整理

r - 如何在 R 中的 Shiny 服务器中使 for 循环 react ?

r - Rmarkdown 中的水平滚动