ggplot2:移动(重新定位)图例以免阻塞图形框

Posted

技术标签:

【中文标题】ggplot2:移动(重新定位)图例以免阻塞图形框【英文标题】:ggplot2: move (reposition) the legend so as not to block the graph box 【发布时间】: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),
)

【问题讨论】:

【参考方案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),

【讨论】:

以上是关于ggplot2:移动(重新定位)图例以免阻塞图形框的主要内容,如果未能解决你的问题,请参考以下文章

ggplot2中具有不同x尺度和不同几何图形的两个数据框的图例控制

在 ggplot2 中,使用两种图形类型时如何缩放图例?

在 matplotlib 和 pandas 中组合和重新定位两个图表的图例的困难

如何使用ggplot2编辑图例的位置

ggplot2:从列表和常见图例中在多个页面上绘制图形

使用 ggplot2 在 R 中保持一致的图形大小(图例和轴改变大小)