【问题标题】:ggplot2: move (reposition) the legend so as not to block the graph boxggplot2:移动(重新定位)图例以免阻塞图形框
【发布时间】:2020-09-12 02:45:44
【问题描述】:

如何将图例向左和底部移动几个点(图形框线的宽度)?

任务:我想让图例的背景半透明,但不与图形框重叠。

(红色边框 - 更好地显示问题)

使用代码:

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

【问题讨论】:

    标签: r ggplot2 themes legend legend-properties


    【解决方案1】:

    如果您希望图例框与绘图边框的外边缘对齐,您需要调整legend.box.margin,使顶部边缘与legend.background 中定义的线的宽度具有相同的值。

    没有样本数据,所以我创建了一些:

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

    reprex package (v0.3.0) 于 2020 年 5 月 25 日创建

    【讨论】:

      【解决方案2】:

      找到了!

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

      【讨论】:

        猜你喜欢
        • 2011-02-26
        • 2012-11-07
        • 1970-01-01
        • 1970-01-01
        • 2023-04-05
        • 2010-12-04
        • 2015-02-25
        • 1970-01-01
        相关资源
        最近更新 更多