8

This R code produces a ggplot2 graph in which the legend key contains the letter "a" repeated in red, blue and green.

x <- rnorm(9); y <- rnorm(9); s <- rep(c("F","G","K"), each = 3)
df <- data.frame(x, y, s)

require(ggplot2)
ggplot(df, aes(x = x, y = y, col = s, label = s)) + 
geom_text() +
scale_colour_discrete(name = "My name", breaks = c("F","K","G"), labels = c("Fbig","Kbig","Gbig")) 

I would like to replace the repeated "a" in the legend key with "F", "K" and "G".

Is this possible please? Thank you.

tonytonov
  • 25,060
  • 16
  • 82
  • 98
Julian Stander
  • 180
  • 1
  • 8

2 Answers2

10

Adapting code for this answer: The idea is to inhibit the geom_text legend, but to allow a legend for geom_point, but make the point size zero so the points are not visible in the plot, then set size and shape of the points in the legend in the guides statement

x <- rnorm(9); y <- rnorm(9); s <- rep(c("F","G","K"), each = 3)
df <- data.frame(x, y, s)
#
require(ggplot2)
#
ggplot(df, aes(x = x, y = y, colour = s, label = s)) +
   geom_point(size = 0, stroke = 0) +  # OR  geom_point(shape = "") +
   geom_text(show.legend = FALSE) +
   guides(colour = guide_legend(override.aes = list(size = 5, shape = c(utf8ToInt("F"), utf8ToInt("K"), utf8ToInt("G"))))) +
   scale_colour_discrete(name = "My name", breaks = c("F","K","G"), labels = c("Fbig","Kbig","Gbig")) 

enter image description here

Community
  • 1
  • 1
Sandy Muspratt
  • 31,719
  • 12
  • 116
  • 122
0

to manually rename the legend add

+ scale_x_continuous(breaks=c(x1,x2,x3), labels=c("F", "K", "G"))

where x1,x2,x3 are the point number

Samehmagd
  • 473
  • 1
  • 5
  • 13
  • Thank you very much. Unfortunately I couldn't get this to do the job. The symbols that define the legend key are small grey boxes with the letter "a" in them with each box having a different coloured "a". I want to be able to specify my own letter instead of the "a". – Julian Stander Feb 23 '15 at 11:43