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:
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.
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
ggplot
Shreyas Karnik 2013-04-10 23:17
+ theme(legend.position='bottom')
by0 2013-09-26 14:42
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)