ggplot2 legend to bottom and horizontal

Go To StackoverFlow.com

89

How can I move a ggplot2 legend to the bottom of the plot and turn it horizontally?

Sample code:

library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend())

Desired (approximate) outcome: enter image description here

2012-04-05 16:38
by Tyler Rinker


115

If you want to move the position of the legend please use the following code:

library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
    theme(legend.position="bottom")

This should give you the desired result. Legend at bottom

2012-04-05 17:09
by Shreyas Karnik
do you know if it possible to draw a continuous legend bar on the bottom? (so not with the number in between but on top). thanks - Janvb 2012-08-23 08:29
With current ggplot, this gives me the warning 'opts' is deprecated. Use 'theme' instead. (Deprecated; last used in version 0.9.1). Replacing opts by theme works - krlmlr 2013-04-10 22:33
Yes I anticipate there is change in the internal workings of ggplotShreyas Karnik 2013-04-10 23:17
It is bad practice to use depreciated items. You can do it using theme the exact same way: + theme(legend.position='bottom')by0 2013-09-26 14:42


25

Two imperfect options that don't give you exactly what you were asking for, but pretty close (will at least put the colours together)

library(reshape2); library(tidyverse)
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
 theme(legend.position="bottom", legend.direction="vertical")

p1 + scale_fill_continuous(guide = "colorbar") + theme(legend.position="bottom")

Created on 2019-02-28 by the reprex package (v0.2.1)

2015-06-20 23:05
by Arthur Yip
Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference - Rohit Gupta 2015-06-20 23:23
I have now enhanced my answer to provide two imperfect solution - Arthur Yip 2019-02-28 07:02
Ads