ggplot2 legend to bottom and horizontal

后端 未结 2 1481
忘了有多久
忘了有多久 2021-01-30 09:51

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

Sample code:

library(reshape2) # for melt
df <- m         


        
相关标签:
2条回答
  • 2021-01-30 10:33

    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

    0 讨论(0)
  • 2021-01-30 10:43

    Here is how to create the desired outcome:

    library(reshape2); library(tidyverse)
    melt(outer(1:4, 1:4), varnames = c("X1", "X2")) %>%
    ggplot() + 
      geom_tile(aes(X1, X2, fill = value)) + 
      scale_fill_continuous(guide = guide_legend()) +
      theme(legend.position="bottom",
            legend.spacing.x = unit(0, 'cm'))+
      guides(fill = guide_legend(label.position = "bottom"))
    

    Created on 2019-12-07 by the reprex package (v0.3.0)


    Edit: no need for these imperfect options anymore, but I'm leaving them here for reference.

    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)

    0 讨论(0)
提交回复
热议问题