且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-26 23:45:22

Maybe there is a straight solution but this is a hack/workaround that I can think of using 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))