我一直在忽略關于通過不同列制作地圖的問題。假設我有一個特定的資料集,其中每一行都是一個多邊形:
> crops <- data.frame(pol_num = c("1", "2", "3","4"),
wheat2020 = c("yes", "yeswater", "yes","no"),
wheat2030 = c("yeswater", "no", "no","no"))
> crops
pol_num wheat2020 wheat2030
1 1 yes yeswater
2 2 yeswater no
3 3 yes no
4 4 no no
如您所見,我有 4 個多邊形和 2 年內作物的適宜性。我想在 ggplot 中為每種可能性(“是”、“是水”和“否”)使用自定義顏色繪制這些多邊形。
我找到的唯一解決方案是以特定順序對每一列進行排序:
crops$wheat2020 <- factor(crops$wheat2020, levels = c("yes", "yeswater","no"))
并按照我需要的顏色順序創建一個自定義調色板:
palette <-c("#98E601", "#72DFFE", "#A80100")
然后申請scale_fill_manual。這變得非常棘手,因為每個場景都有不同的可能組合。在示例中,您可以看到wheat2020有 3 個不同的值,而wheat2030只有 2 個!
我的情節和某個場景的簡化代碼是:
ggplot()
geom_sf(data = crops, aes(fill = wheat2020), lwd = 0.001)
scale_fill_manual(labels=c("Yes", "Yes water","No"),
name="Suitability wheat: 2020",
values = palette)
有沒有辦法簡單地指示哪種顏色必須對應于列中的每個值,無論是否缺少一個或兩個可能的值?
謝謝!
uj5u.com熱心網友回復:
我創建了一些簡單的幾何圖形來更好地模擬您的資料框,但基本上您需要的只是將顏色值作為命名向量傳遞:
ggplot()
geom_sf(data = crops, aes(fill = wheat2020), lwd = 0.001)
scale_fill_manual(name = "Suitability wheat: 2020",
values = c(yes = "#98E601",
yeswater = "#72DFFE",
no = "#A80100"))

ggplot()
geom_sf(data = crops, aes(fill = wheat2030), lwd = 0.001)
scale_fill_manual(name = "Suitability wheat: 2030",
values = c(yes = "#98E601",
yeswater = "#72DFFE",
no = "#A80100"))

轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/453811.html
