Home > Software engineering >  Removing space in legend (ggplot)
Removing space in legend (ggplot)

Time:10-21

I want to remove space in the legend of the following figure (red-colored rectangle). How do I remove this space?

Figure Figure 1

Code

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

CodePudding user response:

You could remove the white space between the legend entries and background box by setting legend.spacing.y = unit(0, "pt"). If that is still too much white space you could try with a negative value or reduce the top margin via legend.margin:

Making use of ggplot2::economics_long as example data:

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

  • Related