theforestecologist
theforestecologist

Reputation: 4937

How to make ggplot legend add objects horizontally (vs vertically)

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:

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))

enter image description here

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.

How do I make my legend add objects horizontally vs vertically?

Like so:

enter image description here

Upvotes: 5

Views: 1181

Answers (1)

joran
joran

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))

enter image description here

Upvotes: 8

Related Questions