[英]Increase space between legend keys without increasing legend keys
这是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
,增加legend.key.size
(请参见上文)也具有增加垂直线的不良副作用。
编辑基于对PoGibas的聪明的解决方法,这里是理想的结果的截图,包括在这里以确保目的很明确:
在PoGibas之后,我在颜色指南中使用了: shape = 73
, legend.key.height = unit(2, "cm")
和size = 6
。
一种解决方案是用点替换线(需要附加的geom层):
创建具有不可见点的图形( 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.