簡體   English   中英

在不增加圖例鍵的情況下增加圖例鍵之間的空間

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM