如何更改ggplot2中的辅助线轴颜色 [英] How to change secondary line axis color in ggplot2

查看:1291
本文介绍了如何更改ggplot2中的辅助线轴颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

#创建一个简单的辅助轴
p + scale_y_continuous(sec.axis = sec_axis(〜。+ 10))+
主题(axis.line.y = element_line(color =red),
#我可以修改文字颜色但不确定是否有行?
axis.text.y.right = element_text(color =红色))



更新:如评论beloew所示,完全控制右轴元素现在包含在开发版本的ggplot2主题中。 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 ylim和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)

#创建一个简单的辅助轴
p + scale_y_continuous(sec.axis = sec_axis( 〜+ 10))+
主题(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))


In ggplot2, how can I modify axis.line.y only on the sec.axis (if possible)?

    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"))

UPDATE: As shown in comments beloew, full control over right axis elements is now comprised in the development version of ggplot2 theme( axis.line.y.right = element_line(color = "red"), axis.ticks.y.right = element_line(color = "red"))

解决方案

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))

这篇关于如何更改ggplot2中的辅助线轴颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆