Ivan Karamazov
Ivan Karamazov

Reputation: 13

How to plot worldmap in R

I'm working on a project and a small part of it consists of drawing a world map with 43 countries on my list. My dataset is as follows:

enter image description here

How do I put this on the world map with different colors for development status as follows?

enter image description here

Data is here :

https://wetransfer.com/downloads/0960ed96fba15e9591a2e9c14ac852fa20220301181615/dc25f41a87fc2ba165a72ab6712dd8d020220301181640/832b5e

Upvotes: 0

Views: 943

Answers (2)

Similar to @zephryl answer, but using tmap. The first step is joining your data with the World data by country name. The next step is drawing the map.

library(dplyr)
library(tmap)

# Get World data
data("World")

# Dummy data frame similar to your data
df <- data.frame(location = World$name,
                 devStat = rnorm(length(World$name), 5, 2.5))

# Join by country name
# Just need to make sure that country names are written exactly the same
# in the two datasets
df2 <- World |>
  left_join(df, by = c("name" = "location"))

# Create map
# Shape to add to the map
tm_shape(df2) +
  # Draw the previous shape as polygons
  # Set the attribute to which the polygons will be coloured
  tm_polygons("devStat", 
              # select palette
              palette = "-plasma",
              # Set palette categories as order
              style = "order",
              # Horizontal legend
              legend.is.portrait = FALSE) +
  # Remove frame from layout
  tm_layout(frame = FALSE,
            # Put legend outsize the frame
            legend.outside = T,
            legend.outside.position = "top")

map

Upvotes: 1

zephryl
zephryl

Reputation: 17069

A quick example using fake data:

library(dplyr)
library(ggplot2)

# simulate data for subset of countries
mydata <- map_data("world") %>% 
  distinct(region) %>% 
  mutate(fakedata = runif(n())) %>% 
  slice_sample(n = 200)

# add simulated values and remove Antarctica
worldmap <- map_data("world") %>% 
  filter(region != "Antarctica") %>% 
  left_join(mydata)

ggplot(worldmap) +
  geom_polygon(aes(long, lat, group = group, fill = fakedata)) +
  coord_quickmap() +
  scale_fill_viridis_c(option = "plasma", na.value = NA) +
  theme_void()

Also look into the {sf} package and geom_sf(), which among other things makes it easier to use different / less distorted / less biased map projections.

Upvotes: 2

Related Questions