簡體   English   中英

ggplot2:如何在圖例鍵中分離geom_polygon和geom_line?

[英]ggplot2: how to separate geom_polygon and geom_line in legend keys?

我想要:

  • 刪除geom_polygon圖例鍵中的行和
  • 刪除geom_line圖例鍵周圍的邊框。

期望的輸出將是

在此輸入圖像描述

到目前為止我失敗的嘗試。 預先感謝您的任何幫助!

library(ggplot2)

set.seed(1337)

dat <- structure(list(id = structure(c(2L, 2L, 2L, 2L), 
                                    .Label = c("1.1", "1.2", "1.3", "2.1", "2.2", "2.3"), 
                                    class = "factor"), 
                     value = c(3.1, 3.1, 3.1, 3.1),
                     x = c(2.2, 1.1, 1.2, 2.5), 
                     y = c(0.5, 1, 2.1, 1.7)), 
                class = "data.frame", 
                row.names = c(NA, -4L))

line <- data.frame(
  x = cumsum(runif(50, max = 0.1)),
  y = cumsum(runif(50, max = 0.1))
)

ggplot(dat, aes(x = x, y = y)) +
  geom_polygon(aes(color = "Border", group = id), fill = NA) +
  geom_line(data = line, aes(colour = "Line"), size = 1) +
  theme(legend.background = element_rect(fill = "transparent"), 
        legend.box.background = element_rect(fill = "transparent", colour = NA),
        legend.key = element_rect(fill = "transparent"))

這是一個很好的問題,我見過幾個黑客。 這很棘手,因為兩個geoms都映射到顏色,每個美學只能得到一個傳奇。 這是一種方式:實際上制作單獨的傳說,每個傳說具有不同的美學,並將它們偽裝成一個傳奇。

對於該行,我將“Line”映射到linetype並對顏色進行硬編碼,而不是映射到顏色。 然后我將線型比例設置為1,實線。 guides ,我拿出了linetype的標題並設置了順序,因此顏色首先出現,然后是linetype。 現在有兩個傳說,但最底層沒有標題。 要使它們看起來像一個連續的圖例,請在圖例之間設置負間距。 當然,如果你有另一個傳奇,這也行不通,在這種情況下你需要一些不同的技巧。

library(ggplot2)

ggplot(dat, aes(x = x, y = y)) +
  geom_polygon(aes(color = "Border", group = id), fill = NA) +
  geom_line(aes(linetype = "Line"), data = line, color = "blue") +
  scale_linetype_manual(values = 1) +
  guides(linetype = guide_legend(title = NULL, order = 2), color = guide_legend(order = 1)) +
  theme(legend.background = element_rect(fill = "transparent"), 
        legend.box.background = element_rect(fill = "transparent", colour = NA),
        legend.key = element_rect(fill = "transparent"), 
        legend.spacing = unit(-1, "lines") )

請注意,您可以使用幾種不同的美學組合,而不僅僅是顏色+線型。 您可以改為映射到多邊形的填充,然后將其alpha設置為0,以便創建填充圖例,但實際上並不顯示填充。

他們必須成為同一個傳奇的一部分嗎? 如果沒有,那么你可以使用多邊形的“填充”美學和線條的“顏色”美學:

ggplot(dat, aes(x = x, y = y)) +
    geom_polygon(aes(fill = "Border", group = id), colour="black") +
    geom_line(data = line, aes(colour = "Line"), size = 1) +
    scale_fill_manual(values=c(NA))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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