R 增加图例键之间的间距,但不增加图例键
这是一项后续行动 问题是调整图例元素以增加图例键之间的空间,而不同时扩展图例键本身。解决方案可能是调整正确的图例主题选项 所需结果:图例键文本标签之间有更多的垂直空间,但不会拉伸图例键线。R 增加图例键之间的间距,但不增加图例键,r,ggplot2,R,Ggplot2,这是一项后续行动 问题是调整图例元素以增加图例键之间的空间,而不同时扩展图例键本身。解决方案可能是调整正确的图例主题选项 所需结果:图例键文本标签之间有更多的垂直空间,但不会拉伸图例键线。 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 &l
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")
)
d一种解决方案是用点替换线(需要额外的几何图层):
使用不可见点(size=0
和矩形形状shape=15
)创建绘图
附言:
- 这不是一个完美的解决方案,因为图例标签和方框之间存在差距
- 如果需要线条而不是矩形,请使用
shape=73
标签之间有更多的垂直空间还是框之间有更多的垂直空间?@PoGibas:图例标签“平均值”和“中间值”之间有更多的空白,图例的关键行如我的截图所示更短,至于灰色框,我不介意,因为我无论如何都会将它们清空。(因此,要么减少灰色框及其内容,要么减少框内的垂直线)谢谢!我在文档中没有看到这样的选项。文本通常通过证明(左、右)来移动。但你必须证明每个标签的方向不同。@StephenHenderson,这就是我们两个人!有时我会忽略一些显而易见的东西,但看起来PoGibas也不相信有一个内置的选项。这很好,谢谢!我更喜欢直线键,而不是点键。。。我猜,通过调整其宽度,可以将方形外观的点关键点变成线段外观的线条关键点(线条图例不应该是正方形,它应该看起来像线段)。。。我是否相信没有内置的ggplot
选项可以独立于框控制框内段的长度?使用73号形状,即字母“I”:-)是的,shape=73
做到了!
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)
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)))