更改辅助线轴颜色 [英] Change secondary line axis color
问题描述
在ggplot2
中,如何仅在sec.axis
上修改axis.line.y
(如果可能)?
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"))
如下面的注释所示, ggplot2 theme( axis.line.y.right = element_line(color = "red"), axis.ticks.y.right = element_line(color = "red"))
As shown in comments below, 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"))
推荐答案
更新:
Update:
Thanks to the comment below, this can be done by using latest dev.v of ggplot2;
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
的一种hack/解决方法:
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))
这篇关于更改辅助线轴颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!