更改ggplot图例中的关键字母

change key letter in legend of ggplot

我生成的散点图如下:

library(ggplot2)
library(ggrepel)

DF <- data.frame(x=runif(20,0,1), y=runif(20,0,1),group=c(rep('x',15),rep('y',5)))

for (i in 1:20)
  DF$item[i]<-paste(sample(c(letters,LETTERS),4),collapse="")

print(ggplot(DF, aes(x, y, label = item, color=group)) +
        geom_text(size = 5) +
        scale_color_manual(values=rainbow(2)) +
        theme_bw())

给出这张图:

在图例中,字母 'a' 以红色和蓝色给出。但是,我想在一个小圆圈或 'x' 中更改 'a'。

如何更改其他内容中的 'a'?

使用网格图形对象 (grobs) 的解决方案:

p <- ggplot(DF, aes(x, y, label = item, color=group)) +
        geom_text(size = 5) +
        scale_color_manual(values=rainbow(2)) +
        theme_bw()
g <- ggplotGrob(p)
g$grobs[[15]][[1]][[1]]$grobs[[4]]$label <- "O"
g$grobs[[15]][[1]][[1]]$grobs[[6]]$label <- "X"

library(grid)
grid.draw(g)

编辑
要将任意数量的组的所有标签更改为 'O':

text_grobs <- which(sapply(g$grobs[[15]][[1]][[1]]$grobs, function(x) class(x)[1])=="text")

for (k in text_grobs) {
   g$grobs[[15]][[1]][[1]]$grobs[[k]]$label <- "O"
}