在图例ggplot2

时间:2017-12-01 00:18:24

标签: r ggplot2 legend legend-properties

我使用ggplot2中的自定义图例创建了一个情节。我试图在图例中的所有项目周围绘制一个框,但是我只能在每个单独的项目周围绘制一个框。如何围绕所有项目只创建一个框?

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(panel.border = element_rect(colour = "black", fill=NA),
        aspect.ratio = 1, axis.text = element_text(colour = 1, size = 12),
        legend.background = element_rect(linetype = 2, size = 0.5, colour = 1))

enter image description here

1 个答案:

答案 0 :(得分:12)

似乎legend.background矩形与legend.box.background矩形重叠。一个简单的解决方法是设置legend.background = element_blank()

但是,在我看来,传说中的间距很难看。即使没有标题设置,图例标题也会占用太多空间。修复此设置legend.title = element_blank()。两个图例之间的间距也太大。通过将空格设置为零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"))

enter image description here