2017-07-27 40 views
6

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

我读过的答案this question,但是可以看出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)) 
+0

看的'源scale_y_discrete'有用于指定所述副轴没有选项/参数。所以任何解决方案可能都必须是黑客。 – SymbolixAU

回答

6

拿出离散因子并用数字表示。然后,您可以对其进行镜像并重新标记刻度以作为因子级别而不是数字。

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

+1

根据ggplot help“连续变量的默认值为c(0.05,0),离散变量的默认值为c(0,0.6)。”对我来说 expand = c(0,0.6)给出了非常好的结果 – TobiO