2

I am trying to use R ggplot2 package to make a boxplot.

However I can only get legend like this. Is there anyway I can change those legend key to just a solid square, instead of using those small box with central line?

The code I used is:

print(ggplot(mydata,aes(x=factor(sp),fill=factor(CommunityType),y=Abundance*100))+geom_boxplot(show_guide=FALSE)
      +theme(axis.text = element_text(colour = "black",size=10))
      +scale_y_continuous(" RA (%) ")+scale_x_discrete(limits=taxalist[1:5]," ")
      +scale_fill_manual(name = "MY type", values = mycol[1:nmc])
      +theme_bw() + guides(fill=guide_legend(title=NULL))+theme(legend.position=c(1,1),legend.justification=c(1,1)) 
      +theme(legend.key = element_blank(),legend.key.size = unit(1.5, "lines"))
      +theme( panel.grid.major = element_blank(),  panel.grid.minor = element_blank(),  panel.background = element_blank())  )

Sorry I cannot image here to describe my question.

RyPeck
  • 7,830
  • 3
  • 38
  • 58
Tao Ding
  • 33
  • 1
  • 3

1 Answers1

6

Here's the legend shown as simple squares, using a variant of a hack that I have seen Winston Change use here. (I am using the diamonds dataset.)

enter image description here

The idea is to plot geom_points (whose legend you can control, and to suppress the boxplot's legend altogether)

library(ggplot2)
p <- ggplot() + geom_point(data=diamonds, aes(x=cut, y=mean(depth), color=clarity), shape=15, size=5)
p <- p + guides(color=guide_legend(title=NULL)) 
p <- p + theme(legend.key = element_blank())
p <- p  + geom_boxplot(data=diamonds,aes(x=cut,fill=factor(clarity),y=depth)) + guides(fill=FALSE)
p

Also check out Hadley's Legend-Attributes page on github

Ram Narasimhan
  • 22,341
  • 5
  • 49
  • 55
  • Thanks @Ram Narasimhan! I tried your code, but always report Error: ggplot2 doesn't know how to deal with data of class uneval. You know how to solve that problem? – Tao Ding Aug 02 '13 at 20:55
  • If you are getting that error message, make sure that you are explicitly stating the `data =` argument. See this question, for example: http://stackoverflow.com/questions/16486819/how-to-deal-with-data-of-class-uneval-in-ggplot The code above works for me. – Ram Narasimhan Aug 02 '13 at 22:45
  • Hey @Ram Narasimhan. There is one problem you may noticed that in the the plot you uploaded, the first column there is a small square there which is unexpected. I suppose in all five cuts there are also a same square but in different color there. I had the same problem now. How can we get rid of that? Thanks! – Tao Ding Aug 05 '13 at 15:13
  • Yes I see that. Ways to get around that is to move the y axis value (instead of `y=mean(depth)` ) or to make the size smaller, so that the square gets smaller. – Ram Narasimhan Aug 05 '13 at 17:48