11

Is there a way to make ggplot place the legend on top but below the title?

As an example...

enter image description here

..produced with the following code:

carrots<-list(Yield=c(345,226,74,559,288,194), 
              Field=c("A","B","C","D","E","F"), 
              Breed=rep(c("Long","Short"),each=3)) 
carrots<-data.frame(carrots) 

ggplot(carrots,aes(y=Yield,x=Field,fill=Breed)) + 
  geom_bar() + 
  opts(title="Title",
       legend.direction = "horizontal", 
       legend.position = "top") + 
         labs(fill="") 

Any suggestions would be greatly appreciated?

MikeTP
  • 7,716
  • 16
  • 44
  • 57
  • 4
    This has been fixed for the next version. – kohske Apr 23 '12 at 17:17
  • For now, if you have access to Adobe Illustrator, save the plot as eps e.g. `ggsave("plot.eps")` and then move the legend to the top in AI. – Maiasaura Apr 23 '12 at 17:21
  • You can fine tune the elements of the grid arrangement using gridExtra package and saving the different elements (plot, legend, title in different objects). – Etienne Low-Décarie Apr 23 '12 at 17:51
  • 1
    This seems to be fixed in the dev version of ggplot2 : http://stackoverflow.com/questions/9656016/how-to-install-development-version-of-r-packages-github-repository install.packages("devtools") library(devtools) dev_mode(on=T) install_github("ggplot2") # use dev ggplot2 now # when finished do: dev_mode(on=F) #and you are back to having stable ggplot2 – Etienne Low-Décarie Apr 23 '12 at 18:16
  • 1
    @EtienneLow-Décarie with grid I would simply not use a title in ggplot2 but add it manually above the plot (e.g with `grid.arrange(plot, main = "title")`) – baptiste Apr 23 '12 at 23:53

1 Answers1

4

Edit Ignore this. The issue is not longer a problem. But the code has been updated so that it no longer throws an error.

While waiting for the next version, you can fine tune within ggplot2. For instance:

ggplot(carrots, aes(y = Yield, x = Field, fill = Breed)) + 
  geom_bar(stat = "identity") + 
  theme(
     plot.margin = unit(c(2, 1, 1, 1), "cm"), 
     plot.title = element_text(size = 30, face = "bold", colour = "blue", vjust = 7), 
     legend.direction = "horizontal",
     legend.position = c(0.1, 1.05)) + 
   ggtitle("Title") +
  labs(fill = "") 
Sandy Muspratt
  • 31,719
  • 12
  • 116
  • 122