Reputation: 339
Ok, I'm having a hard time with mapping some data by country. Here's a trimmed-down version of the data set I'm working with, in an object called 'smaller':
COUNTRY ARRIVALS
Algeria 16
American Samoa 2
Angola 9
Antigua Barbuda 2
Argentina 18
Aruba 4
Australia 82
Bahamas 12
Bahrain 7
Bangladesh 19
And here is the code I've tried thus far that I found online:
library(tidyverse)
world_map <- map_data("world")
allmap <- left_join(smaller, world_map, by = c("COUNTRY" = "region"))
ggplot(allmap, aes(long, lat, group = group))+
geom_polygon(aes(fill = ARRIVALS), color = "white")+
scale_fill_viridis_c(option = "C")
But this outputs the following map, which is not right at all.
Let me know what I'm doing wrong. I appreciate the help.
Upvotes: 1
Views: 661
Reputation: 174468
A left join works, provided you also plot world_map
as a separate layer:
library(tidyverse)
world_map <- map_data("world")
smaller <- structure(list(COUNTRY = c("Algeria", "American Samoa", "Angola",
"Antigua Barbuda", "Argentina", "Aruba", "Australia", "Bahamas",
"Bahrain", "Bangladesh"), ARRIVALS = c(16, 2, 9, 2, 18, 4, 82,
12, 7, 19)), class = "data.frame", row.names = c(NA, -10L))
allmap <- left_join(smaller, world_map, by = c("COUNTRY" = "region"))
ggplot(allmap, aes(long, lat, group = group))+
geom_polygon(data = world_map, fill = "#306020", colour = "#00000010") +
geom_polygon(aes(fill = ARRIVALS), colour = "white") +
scale_fill_viridis_c(option = "C") +
theme_classic() +
theme(panel.background = element_rect(fill = "#101045")) +
coord_equal()
Upvotes: 0
Reputation: 714
You should be using full_join()
. From the documentation:
The mutating joins add columns from y to x, matching rows based on the keys:
inner_join()
: includes all rows in x and y.
left_join()
: includes all rows in x.
right_join()
: includes all rows in y.
full_join()
: includes all rows in x or y.
Like so:
library(tidyverse)
smaller <-
tibble::tribble(
~COUNTRY, ~ARRIVALS,
"Algeria", 16L,
"American Samoa", 2L,
"Angola", 9L,
"Antigua Barbuda", 2L,
"Argentina", 18L,
"Aruba", 4L,
"Australia", 82L,
"Bahamas", 12L,
"Bahrain", 7L,
"Bangladesh", 19L
)
world_map <- map_data("world")
allmap <- full_join(smaller, world_map, by = c("COUNTRY" = "region"))
ggplot(allmap, aes(long, lat, group = group))+
geom_polygon(aes(fill = ARRIVALS), color = "white")+
scale_fill_viridis_c(option = "C")
Created on 2020-07-02 by the reprex package (v0.3.0)
Upvotes: 1