删除图例中的 space (ggplot)

Removing space in legend (ggplot)

我想删除下图(红色矩形)图例中的space。如何删除此 space?

代码

ggplot(C, aes(x = sigma, y = value, group=name)) +
    geom_line(aes(linetype=name)) +
    scale_linetype_manual(values=c("solid", "twodash", "dotted")) +
    theme_minimal() +
    theme_classic() +
    theme(legend.position = c(0.15, 0.85),
          legend.background = element_rect(fill="white", 
                                           size=0.5,
                                           linetype="solid",
                                           colour ="gray"),          
          text = element_text(size=20),
          legend.text = element_text(size=20),
          axis.title=element_text(size=20),
          legend.title = element_blank(),
          panel.grid.major.y = element_line(),
          panel.grid.minor.y = element_line()) 

您可以通过设置 legend.spacing.y = unit(0, "pt") 来移除图例条目和背景框之间的白色 space。如果那仍然是太多的白色 space 你可以尝试使用负值或通过 legend.margin:

减少上边距

使用 ggplot2::economics_long 作为示例数据:

library(ggplot2)

ggplot(subset(economics_long, variable != "pop"), aes(x = date, y = value)) +
  geom_line(aes(linetype=variable)) +
  scale_linetype_manual(values=c("solid", "twodash", "dotted", "solid", "twodash")) +
  theme_classic() +
  theme(legend.position = c(0.15, 0.85),
        legend.background = element_rect(fill="white",
                                         size=0.5,
                                         linetype="solid",
                                         colour ="gray"),
        legend.spacing.y = unit(0, "pt"),
        text = element_text(size=20),
        legend.text = element_text(size=20),
        axis.title=element_text(size=20),
        legend.title = element_blank(),
        panel.grid.major.y = element_line(),
        panel.grid.minor.y = element_line())