Reputation: 4937
The legend in ggplot
can be moved to the bottom of the graphic as a horizontal legend by adding the following arguments to the theme
function:
legend.position="bottom"
moves the legend below the graphlegend.direction="horizontal"
orients the legend to be horizontal.However, not really...
The legend.direction="horizontal"
simply seems to decrease the number of rows in the legend and the number of legend objects in each row.
This can be done manually using guides(color=guide_legend(nrow=x)
dat <- data.frame(plot = rep(letters,2), val = rep(1:length(letters),2))
library(ggplot2)
ggplot(dat, aes(x = val, y = val, color = plot)) +
geom_point() +
theme(legend.position="bottom") +
guides(color=guide_legend(nrow=2))
Regardless....
If you notice in the graphic output of the above code, even though I can control the "dimensions" of my legend (i.e., the number of rows), I can't figure out how to change the ordering of the legend from vertical to horizontal.
a
being above b
etc. ("vertically" sorted) as above, I want b
to be added next to a
("horizontally
" sorted). How do I make my legend add objects horizontally vs vertically?
Like so:
Upvotes: 5
Views: 1181
Reputation: 173627
Try adding byrow = TRUE
to guide_legend
:
ggplot(dat, aes(x = val, y = val, color = plot)) +
geom_point() +
theme(legend.position="bottom") +
guides(color=guide_legend(nrow=2, byrow = TRUE))
Upvotes: 8