简体   繁体   中英

Controlling position of Legend in GGplot

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 (ie 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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM