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

Ale*_*ler 17 r ggplot2 tidyverse

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

我已经阅读了这个问题的答案,但是在包的repo页面上可以看到,该switch_axis_position()函数已从cowplot包中删除(作者在ggplot2中引用(即将推出?)本机功能).

我在ggplot2中看到了辅助轴上的参考页面,但是该文档中的所有示例都使用scale_y_continuous而不是scale_y_discrete.事实上,当我尝试使用离散函数时,我得到错误:

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

无论如何用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))
Run Code Online (Sandbox Code Playgroud)

Bri*_*ian 14

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

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))
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

  • 刚刚又发现了这个。难道还没有更好的办法吗?现在有人知道更简单的方法吗? (4认同)
  • 按照ggplot帮助“连续变量的默认值为c(0.05,0),离散变量的默认值为c(0,0.6)”。对我来说,expand = c(0,0.6)给出了非常不错的结果 (3认同)
  • Github 上实际上有一个未解决的问题,请在那里发表评论,让团队知道您仍然感兴趣:https://github.com/tidyverse/ggplot2/issues/3171 (2认同)