1

I generated a scatter plot as follows:

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())

which gives this graph:

enter image description here

In the legend the letter 'a' is given in red and blue. However, I would like to change the 'a' in either a small circle or a 'x'.

How can I change the 'a' in something else?

WJH
  • 539
  • 5
  • 14

1 Answers1

3

A solution using grid graphical objects (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)

enter image description here

EDIT
To change all labels to 'O' for any number of groups:

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"
}
Marco Sandri
  • 23,289
  • 7
  • 54
  • 58
  • Thanks! If I would like to change either all labels to 'X' or all labels to 'O' (for any number of groups), what would the code be then? – WJH Feb 21 '18 at 10:10