gjabel gjabel - 3 months ago 19
R Question

Side by side horizontal legends in in ggplot2

I would like to get my ggplot legends to appear side by side, underneath the plot with the variable names above the symbols, as they are in this blog post (the second plot). The

opts
function is now defunct, and
theme
does not appear to replicate its behaviour...

library("ggplot2")
ggplot(diamonds, aes(x = carat, y=price, shape = cut, group=interaction(cut, color), color=color)) +
geom_point() +
#opts(legend.direction = "horizontal", legend.position = "bottom")
#potential options, not all seem have an effect...
theme(legend.direction = "horizontal") +
theme(legend.position = "bottom") +
theme(legend.box = "vertical") +
theme(legend.title.align = 0)


enter image description here

...using my MS paint skills to illustrate the desired plot.

Answer

Adapting from the previous suggestions with legend.box = "horizontal", I have found that you can get the legend titles on top using title.position = "top" in the guides for the scale_ functions. These have to be defined for each variable that makes up the legend else the title will be to the left.

ggplot(data = diamonds, 
       mapping = aes(x = carat, y = price, shape = cut,
                     group=interaction(cut, color), color=color)) +
  geom_point() +
  theme(legend.box = "horizontal",
        legend.position="bottom") +
  scale_shape(guide = guide_legend(title.position = "top")) +
  scale_colour_discrete(guide = guide_legend(title.position = "top", nrow = 1))

enter image description here

You could shift the titles to the center using title.hjust = 0.5 as I suggested in the question, but upon inspection, doing so might confuse the reader as to which colors/points refers to which variable.

Comments