r - 更改辅助线 Axis 颜色

标签 r ggplot2 plot axis

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

如下面的评论所示,对右 Axis 元素的完全控制现在包含在 ggplot2 theme( axis.line.y.right = element_line(color = "red"), axis.ticks.y.right = element_line(color = "red")) 的开发版本中。

最佳答案

更新:
感谢下面的 comment,这可以通过使用 的最新 dev.v 来完成(现在在 CRAN 版本中可用);

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

关于r - 更改辅助线 Axis 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45683358/

相关文章:

r - 如果行有相似的元素,则保留较短的行

R:拆分此样本的更好方法

R 在多个图之间交互识别来自同一数据集的点

python - 如何在 Python 中从离散数据集创建 3D 热图?

r - 使用 facet_wrap 和两个变量在 R 中排序条形图

R时间序列数据: removing values from column that are less than previous value

r - ggplot2:如何在 geom_text 标签中将字符变量(例如 x <- ".35")解析为字符而不是数字

r - 堆叠条形图显示 R 中的反向标签

r - 按类别绘制均值和标准差

r - 按日期绘制离散数据计数