Home > other >  Controlling position of Legend in GGplot
Controlling position of Legend in GGplot

Time:10-01

I have the below plot using ggplot2

library(ggplot2)
library(dplyr)
set.seed(1)
Dat = rbind(data.frame(var1 = 'x1', var2 = rnorm(1000, 10, 3)), 
            data.frame(var1 = 'x2', var2 = rnorm(1000, -10, 5)))

Dat %>% 
ggplot()  
    theme(
        legend.position = c(.15, .85)
    )  

    geom_histogram(data = Dat, aes(x = var2, y = ..density.., fill = var1), position = "identity")

To control the legend's position, I used legend.position. However I observed that if change the plot size (i.e maximise the plot window), that position is getting changed.

I want legend should always stay in top-left position with a small margin irrespective of plot size. And legend must stay within the plot.

Is there any way to achieve this?

CodePudding user response:

You can use the legend.box.margin theme setting to control the margins in absolute units, even if the legend is positioned and justified in a corner.

library(ggplot2)
set.seed(1)
Dat = rbind(data.frame(var1 = 'x1', var2 = rnorm(1000, 10, 3)), 
            data.frame(var1 = 'x2', var2 = rnorm(1000, -10, 5)))

ggplot(Dat)  
  geom_histogram(data = Dat, 
                 aes(x = var2, y = ..density.., fill = var1), 
                 position = "identity")  
  theme(
    legend.position = c(0,1), # top left position
    legend.justification = c(0, 1), # top left justification
    legend.box.margin = margin(5, l = 5, unit = "mm") # small margin
  )
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Created on 2021-10-01 by the reprex package (v0.3.0)

  • Related