创建一个循环以在 ggplot 中写入注释

Dan*_* KS 2 loops r annotate user-defined-functions ggplot2

我正在创建图表,其中一条白线在条形前面打破了条形(抱歉无法发布图像)。我已经得到了一次执行此操作的代码,但我还不擅长循环。

library(ggplot2)

count <- c(61.8,18.8)
name <- c("A","B")
yes <- data.frame(count,name)

j <-   ggplot(yes, aes(x=name, y=count)) + 
geom_bar(stat="identity", position="dodge") 
Run Code Online (Sandbox Code Playgroud)

为了仅添加一行,我创建了这个函数......

b <- function (yx){
j + annotate("segment", x=-Inf, xend=Inf, y=yx, yend=yx,size=1, colour="white") 
}

b(8)
Run Code Online (Sandbox Code Playgroud)

这就是我陷入困境的地方,我想制作一个可以遍历向量的循环,例如......

yx <- c(8,10,20)
Run Code Online (Sandbox Code Playgroud)

并在 8、10 和 20 处创建一行。一个棘手的问题是,除了终端数据(最后一个)之外的所有数据都需要在末尾有一个“+”。有人试过这个吗?

谢谢

bap*_*ste 5

你的函数已经向量化了,所以你不需要改变任何东西,

add_lines <- function(yx){
  annotate("segment", x=-Inf, xend=Inf, y=yx, yend=yx,size=1, colour="white") 
}

j + add_lines(c(8,10,20))
Run Code Online (Sandbox Code Playgroud)

然而,从概念上讲,如果您想逐行添加行,您可以简单地使用一个列表:

add_oneline <- function(yx){
  annotate("segment", x=-Inf, xend=Inf, y=yx, yend=yx,size=1, colour="white") 
}

lines <- lapply(c(8,10,20), add_oneline)
j + lines
Run Code Online (Sandbox Code Playgroud)

但这比第一种选择效率较低且更复杂。