[英]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.