Discrete legend at bottom of ggplot - how to change the number of rows it spans?

I'm creating a plot visualising proportions of an ordered categorical variable with approximately 30 levels. The legend is displayed at the bottom of the plot. I'd like to control the number of rows the legend spans - i.e., be able to control how many horizontal lines the legend categories are plotted over, to make it appear as wide as the main plot.
I'd like to control the number of lines they span, so I can make the legend as wide as the main plot (which would probably be two lines or so here). The default settings puts them on 7 rows, using legend.direction = "horizontal" in theme() doesn't solve it, and I have'nt been able to find another setting that works.

A working, simplified reprex is inserted below. Any help would be appreciated. Thanks in advance!

library(ggplot2)
df <- data.frame(a = 1, val = factor(sample(0:30, 1000, TRUE)))
ggplot(df, aes(y = a, fill = val)) +
  geom_bar(position = "fill") +
  theme(legend.position = "bottom")

Hi, I added a line where you can specify the number of rows (here I chose 2 rows).

library(ggplot2)
df <- data.frame(a = 1, val = factor(sample(0:30, 1000, TRUE)))
ggplot(df, aes(y = a, fill = val)) +
  geom_bar(position = "fill") +
  theme(legend.position = "bottom")+
  guides(fill=guide_legend(nrow=2))
1 Like

Excellent, that was exactly what I was looking for. Thanks for your help!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.