所以我試圖創建一個動物不同亞種的分布圖。我想根據那里可以找到的亞種給每個國家涂上不同的顏色。但是當我嘗試為一個新國家著色時,代碼中的第一個會被新的國家抹去。例如,這里中國的紅色消失了,而我只能看到韓國的藍色。我認為問題在于我只是替換了我以前的命令,我已經嘗試將它們合并到一行中,但是我得到了不同的錯誤。
我該如何解決這個問題?非常感謝!
library(maps)
library(mapdata)
library(ggplot2)
library(dplyr)
world <- map_data('world')
world <- mutate(world, fill = ifelse(region %in% c("China"), "red", "white"))
world <- mutate(world, fill = ifelse(region %in% c("North Korea", "South Korea"), "blue",
"white"))
ggplot(world, aes(long, lat, fill = fill, group = group))
xlim(-10,150) ylim (-7,100)
theme_void()
geom_map(map = world, aes(map_id = region), fill="white", color="grey")
geom_polygon(colour="gray")
scale_fill_identity()
uj5u.com熱心網友回復:
正如您已經猜到的那樣,您正在用 second 覆寫顏色分配ifelse。為了解決這個問題,我建議使用dplyr::case_when:
library(ggplot2)
library(dplyr)
world <- map_data('world')
world <- mutate(world, fill = case_when(
region %in% c("China") ~ "red",
region %in% c("North Korea", "South Korea") ~ "blue",
TRUE ~ "white"))
ggplot(world, aes(long, lat, fill = fill, group = group))
xlim(-10,150) ylim (-7,100)
theme_void()
geom_map(map = world, aes(map_id = region), fill="white", color="grey")
geom_polygon(colour="gray")
scale_fill_identity()

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