如何在ggplot2中更改辅助线轴颜色

时间:2017-08-14 21:31:34

标签: r plot ggplot2

ggplot2中,如何仅在axis.line.y上修改sec.axis(如果可能)?

    p <- ggplot(mtcars, aes(cyl, mpg)) +
      geom_point()

    # Create a simple secondary axis
    p + scale_y_continuous(sec.axis = sec_axis(~.+10)) +
      theme(axis.line.y = element_line(color = "red"),
            # I can modify text color but not sure about line?
            axis.text.y.right = element_text(color = "red"))

enter image description here

更新:如评论beloew所示,对右轴元素的完全控制现在包含在 ggplot2 theme( axis.line.y.right = element_line(color = "red"), axis.ticks.y.right = element_line(color = "red"))

的开发版本中

1 个答案:

答案 0 :(得分:7)

更新

感谢下面的comment,可以使用的最新dev.v来完成此操作;

install.packages("devtools")
devtools::install_github("tidyverse/ggplot2")
library(ggplot2)

p + theme( axis.line.y.right = element_line(color = "red"), 
       axis.ticks.y.right = element_line(color = "red"))

也许有一个直接的解决方案,但这是我可以考虑使用geom_segment的黑客/解决方法:

p <- ggplot(mtcars, aes(cyl, mpg)) +
     geom_point()

#get the ylim and xlim
xmin <- min(ggplot_build(p)$layout$panel_ranges[[1]]$x.range) 
xmax <- max(ggplot_build(p)$layout$panel_ranges[[1]]$x.range)
ymin <- min(ggplot_build(p)$layout$panel_ranges[[1]]$y.range)
ymax <- max(ggplot_build(p)$layout$panel_ranges[[1]]$y.range)

# Create a simple secondary axis
p + scale_y_continuous(sec.axis = sec_axis(~.+10)) +
    theme(axis.text.y.right = element_text(color = "red"))+
    geom_segment(aes(x=xmax+0.2,xend=xmax+0.2,
                     y=ymin-2,yend=ymax+2), color = "red") +
    coord_cartesian(xlim=c(xmin, xmax), ylim=c(ymin, ymax))

enter image description here