Home > Enterprise >  Color different countries with R based on ggplot and map_data
Color different countries with R based on ggplot and map_data

Time:05-31

So I am trying to create a distribution map of the different subspecies of an animal. I wanted to color each country differently, according to the subspecies that can be found there. But when I try to color a new country, the first one in the code will get erased by the new one. For example here the red color of China goes away and instead of that I can only see the blue of Korea. I think that the problem is that I am just replacing my previous command, I already tried to merge them into one line, but I get different errors.

How can I solve this? Thanks a lot!

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()

CodePudding user response:

As you already guessed you are overwriting the color assignment by the second ifelse. To fix that I would suggest to use 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()

  • Related