Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Color different countries with R based on ggplot and map_data

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading