Search code examples
rggplot2themeslegendlegend-properties

ggplot2: move (reposition) the legend so as not to block the graph box


enter image description here

How can I shift the legend by several points (the width of the graph box line) to the left and bottom?

Task: I want to make the background of the legend semi-transparent, but so it doesn't overlap the graph box.

(red border - for better visualization of the problem)

Use the code:

image + theme(
    panel.background     = element_rect(fill = "white", color = NA),
    panel.border         = element_rect(fill = NA, color = "black", size = 2),
    panel.grid.major     = element_line(color = "#00000040", linetype = 3),

    axis.text            = element_text(size = 10),
    axis.title           = element_text(size = 12),
    axis.title.x         = element_text(margin = margin(t = 10)),
    axis.title.y         = element_text(margin = margin(r = 10)),

    legend.key           = element_rect(fill = NA, color = NA),
    legend.background    = element_rect(fill = "#ffffff80", color = "red", size = 1),
    legend.justification = c(1, 1),
    legend.position      = c(1, 1),
    legend.title         = element_text(size = 10, color = "black"),

    plot.title           = element_text(hjust = 0.5),
)

Solution

  • If you want the legend box to align with the outside edge of the plot border, you need to adjust the legend.box.margin so that the top edge has the same value as the width of the line defined in legend.background.

    There was no sample data, so I created some:

    library(ggplot2)
    
    x  <- seq(0, 2 * pi, length.out = 100)
    df <- data.frame(x = c(x, x), y = c(-cos(x), sin(x)), 
                     group = rep(c("data1", "data2"), each = 100))
    
    image <- ggplot(df, aes(x, y)) + 
      geom_line(aes(colour = group)) + 
      scale_colour_manual(values = c("red", "black"))
    
    image + theme(
        panel.background     = element_rect(fill = "white", color = NA),
        panel.border         = element_rect(fill = NA, color = "black", size = 2),
        panel.grid.major     = element_line(color = "#00000040", linetype = 3),
    
        axis.text            = element_text(size = 10),
        axis.title           = element_text(size = 12),
        axis.title.x         = element_text(margin = margin(t = 10)),
        axis.title.y         = element_text(margin = margin(r = 10)),
    
        legend.key           = element_rect(fill = NA, color = NA),
        legend.background    = element_rect(fill = "#ffffff80", color = "red", size = 1),
        legend.justification = c(1, 1),
        legend.position      = c(1, 1),
        legend.title         = element_text(size = 10, color = "black"),
        legend.box.margin    = margin(1, 0, 0, 0),
    
        plot.title           = element_text(hjust = 0.5)
    )
    

    Created on 2020-05-25 by the reprex package (v0.3.0)