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)
...using my MS paint skills to illustrate the desired plot.
You need to specify theme(legend.box = "horizontal")
Try this:
library("ggplot2") ggplot(diamonds, aes(x = carat, y=price, shape = cut, group=interaction(cut, color), color=color)) + geom_point() + theme(legend.direction = "horizontal", legend.position = "bottom", legend.box = "horizontal" )
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))
You could shift the titles to the center, as I suggested in the question, using title.hjust = 0.5
. However, upon inspection, doing so might confuse the reader as to which colours/points refers to which variable.
@gjbel - I think to make the legend title above the symbols you either need to change legend direction from horizontal to vertical or remove legend direction entirely as the default is vertical:
library("ggplot2")
ggplot(diamonds, aes(x = carat, y=price, shape = cut, group=interaction(cut, color), color=color)) +
geom_point() +
theme(legend.direction = "vertical",
legend.position = "bottom",
legend.box = "horizontal"
)
OR
library("ggplot2")
ggplot(diamonds, aes(x = carat, y=price, shape = cut, group=interaction(cut, color), color=color)) +
geom_point() +
theme(legend.position = "bottom",
legend.box = "horizontal"
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With