增加图例键之间的间距而不增加图例键

9
这是对https://dev59.com/E1wY5IYBdhLWcg3wup5c的跟进。
问题是调整图例元素,增加图例键之间的空间,而不同时延长图例键本身。解决方案可能在调整正确的图例主题选项中。
期望结果:图例键文本标签之间有更多的垂直空间,但不会拉伸图例键行。
d <- data.frame(x = mtcars$mpg, y = 0.10)
vlines <- rbind(aggregate(d[1], d[2], mean), 
                aggregate(d[1], d[2], median))
vlines$stat <- rep(c("mean", "median"), each = nrow(vlines)/2)
library("ggplot2")
ggplot(data = d, aes(x = x, y = ..density..)) + 
    geom_histogram(fill = "lightblue", color = "black") + 
    geom_vline(data = vlines, mapping = aes(xintercept = x, colour = stat), 
            show.legend = TRUE) +
    theme(legend.direction = "vertical", 
        legend.position = "right",
        #          legend.key = element_rect(size = 2),
        legend.key.size = unit(3, "cm"),
        #          legend.key.width = unit(2, "cm"),
        #          legend.key.height = unit(1, "cm")
        )

增加 legend.key.size,如链接问题的答案中建议的那样(请参见上文),会导致垂直线条也增加,这是不期望的副作用。

enter image description here

编辑 基于PoGibas的巧妙解决方法,这里提供所需结果的截图,以确保目的清晰:

enter image description here

在 PoGibas 的指导下,我使用了以下代码:shape = 73legend.key.height = unit(2, "cm")size = 6,放置在颜色指南内。


标签之间需要更多的垂直空间还是方框之间需要更多的垂直空间? - pogibas
@PoGibas:在图例标签“mean”和“median”之间增加更多的空白,缩短图例键行,就像我的截图一样。至于灰色框,我不介意,因为我会将它们清空。 (因此,要么减少灰色框及其内容,要么减少框内的垂直线)谢谢! - PatrickT
1
我在文档中没有看到这样的选项。通常,文本是通过对齐(左、右)来移动的。但是您需要将每个标签都对齐到不同的方向。 - Stephen Henderson
@StephenHenderson,我们俩一样!有时候我会错过显而易见的东西,但看起来PoGibas也不相信有内置选项可以解决这个问题。 - PatrickT
1个回答

6
一种解决方案是用点代替线(需要添加几何图层):
创建一个带有不可见点的绘图(大小为0,矩形形状为15)。
p <- ggplot(d, aes(x, ..density..)) + 
    geom_histogram(fill = "lightblue", color = "black") + 
    geom_vline(data = vlines, mapping = aes(xintercept = x, colour = stat)) +
    geom_point(data = vlines, aes(0, 0, colour = stat), size = 0, shape = 15)

为以下内容添加图例主题:

  • 在图例中掩盖背景颜色(legend.key = element_rect(fill = "white"))
  • 创建大型图例(legend.key.height = unit(3, "cm"))
  • 删除线条(linetype = 0)并使点变大(size = 5)

代码:

p + 
    theme(legend.direction = "vertical", 
          legend.position = "right",
          legend.key = element_rect(fill = "white"),
          legend.key.height = unit(3, "cm")) +
    guides(color = guide_legend(override.aes = list(linetype = 0, size = 5)))

图片描述在此输入

PS.:

  • 这不是完美的解决方案,因为图例标签和框之间存在间隙。
  • 如果您想要线条而不是矩形,请使用shape = 73

太好了,谢谢!我更喜欢有一个线键,而不是一个点键...我想这个看起来像正方形的点键可以通过调整宽度变成线段形状的线键(线图例不应该是正方形,应该看起来像一条线段)...我该相信没有内建的“ggplot”选项可以独立地控制盒子内部的线段长度吗? - PatrickT
1
使用形状73,即字母"I" :-) - pogibas
没错,shape = 73 就是它了! - PatrickT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接