这是https://stackoverflow.com/questions/32275113
的后续行动问题是调整图例元素以增加图例键之间的空间,而无需同时扩展图例键本身。解决方案可能是调整正确的图例主题选项。
所需结果:图例键文字标签之间的垂直空间更大,但不会拉伸图例键行。
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
具有增加垂直线的不希望的副作用。
编辑根据PoGibas的巧妙解决方法,这里是所需结果的屏幕截图,包含在此处以确保目的明确:
在PoGibas之后,我在颜色指南中使用了shape = 73
,legend.key.height = unit(2, "cm")
和size = 6
。
答案 0 :(得分:5)
一种解决方案是用点替换线(需要额外的几何层):
使用不可见点创建绘图(size = 0
和矩形shape = 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