【问题标题】:Removing space in legend (ggplot)删除图例中的空格(ggplot)
【发布时间】:2021-12-07 09:39:43
【问题描述】:

我想去掉下图(红色矩形)图例中的空格。如何删除这个空间?

代码

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()) 

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    您可以通过设置legend.spacing.y = unit(0, "pt") 删除图例条目和背景框之间的空白。如果仍然有太多空白,您可以尝试使用负值或通过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()) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-03
      • 2016-06-07
      • 1970-01-01
      • 2016-04-09
      • 2013-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多