Draw a box around a legend ggplot2

后端 未结 1 655
遥遥无期
遥遥无期 2021-02-12 09:37

I created a plot with a custom legend in ggplot2. I tried to draw a box around all the items in the legend, however I could only draw a box around each individual i

1条回答
  •  滥情空心
    2021-02-12 10:08

    It seems that the legend.background rectangle overlaps the legend.box.background rectangle. An easy fix is to set legend.background = element_blank().

    But then, in my opinion, the spacing in the legend is ugly. The legend titles take up too much space even with no title set. Fix this be setting legend.title = element_blank(). Also the spacing between the two legends is too large. Fix this by setting the space to zero legend.spacing.y = unit(0, "mm")

    library(ggplot2)
    
    ggplot(mpg, aes(displ, cty)) + 
      geom_point(aes(shape = "Data")) +
      stat_smooth(aes(linetype = "Regression"), method = "lm", 
                  formula = y ~ x, se = FALSE, colour = 1, size = 0.5) +
      scale_shape_manual(values = 1) +
      labs(shape = "", linetype = "") +
      theme_classic() + 
      theme(legend.title = element_blank(),
            legend.spacing.y = unit(0, "mm"), 
            panel.border = element_rect(colour = "black", fill=NA),
            aspect.ratio = 1, axis.text = element_text(colour = 1, size = 12),
            legend.background = element_blank(),
            legend.box.background = element_rect(colour = "black"))
    

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