首页 文章

底部和水平的ggplot2图例

提问于
浏览
90

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

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

2 回答

  • 117

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

    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

  • 27

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

    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包创建于2019-02-28(v0.2.1)

相关问题