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?
