Skip to content

Instantly share code, notes, and snippets.

@kleinlennart
Created January 9, 2025 21:30
Show Gist options
  • Save kleinlennart/ffe0269ddd306b581360bf38a7e376e1 to your computer and use it in GitHub Desktop.
Save kleinlennart/ffe0269ddd306b581360bf38a7e376e1 to your computer and use it in GitHub Desktop.
Data Visualization Snippets | World Map with Country Dots
library(tidyverse)
library(sf)
# Data --------------------------------------------------------------------
raw_survey <- read_csv(here::here("data", "input", "Survey", "Crisis+Data+Ecosystem+Survey_RAW.csv"))
# Wrangle -----------------------------------------------------------------
# remove the variable descriptions row, only useful for new colnames
raw_survey <- raw_survey |> slice(-1)
country_counts <- raw_survey |>
rename(country = QID1319370883) |>
count(country, sort = TRUE) |>
drop_na()
# geocoding
country_counts <- country_counts |>
mutate(
iso3 = country |> countrycode::countrycode("country.name", destination = "iso3c")
)
# Plot --------------------------------------------------------------------
# download shape file
world <- rnaturalearth::ne_countries(scale = "medium", returnclass = "sf")
# Drop Antarctica
world <- world |>
filter(!continent %in% c("Antarctica"))
# Extract centroids for countries
# NOTE: ne_countries(scale = "small") will lead to errors with centroids
country_centroids <- world |>
st_centroid() |>
select(name, adm0_a3, geometry) |>
mutate(
lat = st_coordinates(geometry)[, 2],
lon = st_coordinates(geometry)[, 1]
)
# join counts to centroids
country_centroids <- country_centroids |>
inner_join(country_counts, by = join_by("adm0_a3" == "iso3"))
# nrow(country_counts) == nrow(country_centroids)
world |>
ggplot() +
geom_sf(fill = "#F1B434", alpha = 0.3, color = "white") +
geom_point(
data = country_centroids, aes(x = lon, y = lat, size = n),
fill = "#F1B434", color = "black", shape = 21, stroke = 0.1, show.legend = FALSE
) +
theme_void() +
ggview::canvas(width = 10, height = 6.3, units = "in", bg = "white", scale = 1, dpi = DPI)
# Export ------------------------------------------------------------------
DPI <- 600
ggsave(here::here("plots", "survey", "ecoystem_map.png"), width = 10, height = 6.3, units = "in", dpi = DPI, scale = 1, bg = "white")
ggsave(here::here("plots", "survey", "ecoystem_map.svg"), width = 10, height = 6.3, units = "in", dpi = DPI, scale = 1, bg = "white")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment