Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: force legend to have one row when guides does not appear to have an effect

Tags:

r

ggplot2

I have the following toy example:

library(ggplot2)
g <- ggplot(mpg, aes(class))
mpg$drv <- sample(as.character((-4:4)), size = length(mpg$drv), replace = T)
g + geom_bar(aes(fill = drv), position = "fill") + theme(legend.position = "bottom") + guides(colour = guide_legend(nrow = 1))

which for meenter image description here yields the following figure.

Try as I might, I am unable to get the legend at the bottom to be in one row. I looked around and the guide_legend appears to be having no effect. Is there a better way to do this, or is there another way to force the legend to be in one row?

like image 752
user3236841 Avatar asked Sep 10 '25 16:09

user3236841


1 Answers

You've specified colour instead of fill in guides. Try this instead:

library(ggplot2)
mpg$drv <- sample(as.character((-4:4)), size = length(mpg$drv), replace = T)
g <- ggplot(mpg, aes(class))
g + geom_bar(aes(fill = drv), position = "fill") + theme(legend.position = "bottom") + guides(fill = guide_legend(nrow = 1))
like image 125
Hallie Swan Avatar answered Sep 13 '25 05:09

Hallie Swan