[英]Adding subcategories to a legend in ggplot2
假設我們有以下關於構成我的幻想島的棲息地的分層數據(當然總是溫暖和陽光充足!)
set.seed(1)
hab_dat <- data.frame(
habitat_type = rep(c("sea", "coast", "land"), times = 1, each = 3),
habitat_name = c("rocky", "sandy", "seaweed",
"beach", "pebbles", "rockpools",
"fields", "hills", "forest"),
area_km2 = sample(10:40, size =9))
hab_dat
我想繪制每種棲息地類型的總面積,因此編寫以下代碼
hab_dat %>%
group_by(habitat_type) %>%
summarise(area_km2 = sum(area_km2)) %>%
ggplot(aes(x = habitat_type, y = area_km2, fill = habitat_type)) +
geom_bar(stat = "identity") +
scale_fill_manual(values = c("gold", "forestgreen", "blue"))
看起來不錯,但傳說不是很豐富。 我希望每個棲息地類型中包含的棲息地都包含在適當棲息地類型下的圖例中,就像定性信息一樣。 這是我在油漆中制作的一個例子。
在不影響繪圖外觀的情況下,我可以使用以下代碼更接近一點,但是,我缺少habitat_type 標題,並且還有多個相同顏色的圖塊。
hab_dat <- hab_dat %>% mutate(col = rep(c("blue", "gold", "forestgreen"), times = 1, each = 3))
pal <- setNames(as.character(hab_dat$col), as.character(hab_dat$habitat_name))
ggplot(hab_dat, aes(x = habitat_type, y = area_km2, fill = habitat_name)) +
geom_bar(position = "stack", stat = "identity") +
scale_fill_manual(values = pal)
我一直在尋找與此類似的解決方案,但我正在嘗試一種更自動化的解決方案,因為我的實際數據比這要大一些,而且根據我的繪圖,每組顯示一次彩色圖塊。
我認為沒有一個優雅的解決方案可以解決您的問題。 我會在這里建議您格式化標簽以暗示層次結構。
library(ggplot2)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
set.seed(1)
hab_dat <- data.frame(
habitat_type = rep(c("sea", "coast", "land"), times = 1, each = 3),
habitat_name = c("rocky", "sandy", "seaweed",
"beach", "pebbles", "rockpools",
"fields", "hills", "forest"),
area_km2 = sample(10:40, size =9))
# Format labels
labels <- split(hab_dat$habitat_name, hab_dat$habitat_type)
labels <- unlist(Map(function(top, bottom) {
paste0(top, "\n", paste("- ", bottom, collapse = "\n"))
}, top = names(labels), bottom = labels))
hab_dat %>%
group_by(habitat_type) %>%
summarise(area_km2 = sum(area_km2)) %>%
ggplot(aes(x = habitat_type, y = area_km2, fill = habitat_type)) +
geom_bar(stat = "identity") +
scale_fill_manual(
values = c("gold", "forestgreen", "blue"),
labels = function(i) {labels[i]} # Lookup label
)
由reprex 包於 2022-07-19 創建 (v2.0.1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.