底部和水平的ggplot2图例

时间:2012-04-05 16:38:08

标签: r ggplot2

如何将ggplot2图例移动到图的底部并水平转动?

示例代码:

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

期望(近似)结果: enter image description here

2 个答案:

答案 0 :(得分:123)

如果您想移动图例的位置,请使用以下代码:

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

这应该会给你想要的结果。 Legend at bottom

答案 1 :(得分:28)

两个不完美的选项并不能完全满足您的要求,但非常接近(至少会将颜色组合在一起)

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

reprex package创建于2019-02-28(v0.2.1)