这是对/sf/ask/2259257941/的跟进
问题是调整图例元素以增加图例键之间的空间,而无需同时扩展图例键本身.解决方案可能是调整正确的图例主题选项.
期望的结果:图例关键文本标签之间的垂直空间更大,但不延伸图例关键线.
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")
)
Run Code Online (Sandbox Code Playgroud)
增加legend.key.size,如在回答所述链接的问题建议(见上文),具有增加的垂直线以及的不期望的副作用.
编辑基于PoGibas的巧妙解决方法,这里是所需结果的屏幕截图,包含在此处以确保目的明确:
继PoGibas,我用:shape = 73,legend.key.height = unit(2, "cm")和size = 6彩色引导内.
一种解决方案是用点替换线(需要额外的几何层):
使用不可见点(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)
Run Code Online (Sandbox Code Playgroud)
将图例主题添加到:
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)))
Run Code Online (Sandbox Code Playgroud)
PS:
shape = 73