如何为ggplot geom_线密度添加ggrepel文字

如何为ggplot geom_线密度添加ggrepel文字,r,ggplot2,ggrepel,R,Ggplot2,Ggrepel,我有以下代码: set.seed(10) foo <- data.frame( v2=sample(c(1,2,3),size=10,rep=T), v3=as.factor(sample(c('cat','dog'),10,rep=T)) ) library(ggplot2) library(ggrepel) ggplot(foo, aes(x=v2, colour=v3, group=v3)) + geom_line(aes(group=v3), stat='densit

我有以下代码:

set.seed(10)
foo <- data.frame(
  v2=sample(c(1,2,3),size=10,rep=T),
  v3=as.factor(sample(c('cat','dog'),10,rep=T))
)

library(ggplot2)
library(ggrepel)
ggplot(foo, aes(x=v2, colour=v3, group=v3)) +
  geom_line(aes(group=v3), stat='density', alpha=0.3)
但它给出了:

Error: geom_text_repel requires the following missing aesthetics: y
我的问题是如何使用ggrepel显示上图中所示的标签?

您可以这样做

set.seed(10)
foo <- data.frame(
  v2=sample(c(1,2,3),size=10,rep=T),
  v3=as.factor(sample(c('cat','dog'),10,rep=T))
)
library(ggplot2)
ggplot(foo, aes(x=v2, colour=v3, group=v3)) +
  geom_line(aes(group=v3), stat='density', alpha=0.3) -> p
pdat <- ggplot_build(p)$data[[1]]
idx <- sample(seq_len(nrow(pdat)), 20)
p + ggrepel::geom_text_repel(
  aes(x,y,label=txt), 
  cbind(pdat[idx,], txt=paste0("txt", seq_along(idx))), 
  inherit.aes=F, 
  show.legend = F, 
  color="red", 
  segment.colour = "black", 
  min.segment.length = unit(0, "lines")
)
set.seed(10)
福普
pdat你能做什么

set.seed(10)
foo <- data.frame(
  v2=sample(c(1,2,3),size=10,rep=T),
  v3=as.factor(sample(c('cat','dog'),10,rep=T))
)
library(ggplot2)
ggplot(foo, aes(x=v2, colour=v3, group=v3)) +
  geom_line(aes(group=v3), stat='density', alpha=0.3) -> p
pdat <- ggplot_build(p)$data[[1]]
idx <- sample(seq_len(nrow(pdat)), 20)
p + ggrepel::geom_text_repel(
  aes(x,y,label=txt), 
  cbind(pdat[idx,], txt=paste0("txt", seq_along(idx))), 
  inherit.aes=F, 
  show.legend = F, 
  color="red", 
  segment.colour = "black", 
  min.segment.length = unit(0, "lines")
)
set.seed(10)
福普
pdat