簡體   English   中英

在GGplot中控制Legend的position

[英]Controlling position of Legend in GGplot

我有以下 plot 使用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")

為了控制圖例的 position,我使用legend.position 但是我觀察到,如果更改 plot 大小(即最大化 plot 窗口),則 position 會發生變化。

我希望圖例始終保持在左上角 position ,無論 plot 大小如何,邊距都很小。 而legend必須留在plot之內。

有什么辦法可以做到這一點?

您可以使用legend.box.margin主題設置以絕對單位控制邊距,即使圖例位於角落並對齊也是如此。

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`.

reprex package (v0.3.0) 創建於 2021-10-01

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM