Zhihar
Zhihar

Reputation: 1428

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

Upvotes: 0

Views: 194

Answers (2)

Allan Cameron
Allan Cameron

Reputation: 173803

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)

Upvotes: 1

Zhihar
Zhihar

Reputation: 1428

found it!

legend.box.margin    = margin(t = 2, r = 2),

Upvotes: 0

Related Questions