2

I would like to modify the legend in ggplot2 using the text geom. Example is shown below. I want to change the a's to points (circles) and instead of 1, 2, 3 use custom names such as low, medium, high. Any suggestions would be greatly appreciated.

Example Data:

   x  y Freq colors
1 -2 32    2      1
2 -2 36    1      1
3 -2 37    1      1
4 -2 40    2      1
5 -1 32    2      1
6  0 29    2      1

Code:

  fit=ggplot(a1,aes(x,y,color=factor(colors)),col=colors)+
    geom_text(aes(label=Freq),size=5)+
    theme_bw()+
    opts(legend.position='top',
         legend.title=theme_blank(),
         legend.key=theme_rect(fill="white",colour="white"))
  print(fit)

enter image description here

Glen
  • 1,722
  • 3
  • 18
  • 25
  • This page [(R Cookbook)](http://wiki.stdout.org/rcookbook/Graphs/Legends%20(ggplot2)/) talks a great deal about custom legen stuff. combined with this post: http://stackoverflow.com/questions/10405823/changing-the-symbol-in-the-legend-key-in-ggplot2 should give you the pieces. – Tyler Rinker Aug 26 '12 at 17:53

1 Answers1

2

Thanks to Tyler's comments I found a solution (note the grid library needs to be loaded):

  fit=ggplot(a1,aes(x,y,color=factor(colors)),col=colors)+
    geom_text(aes(label=Freq),size=5)+
    theme_bw()+
    scale_color_hue(breaks=c("1", "2", "3"),
                      labels=c("Low", "Medium", "High"))+
    opts(legend.position='top',
         legend.title=theme_blank(),
         legend.key=theme_rect(fill="white",colour="white"))
  print(fit)
  grid.gedit("^key-[-0-9]+$", label = "*")

I wish I could make the "*" bigger in the legend, I understand the next version of ggplot2 will have more legend controls.

Glen
  • 1,722
  • 3
  • 18
  • 25