---
title: "Making Maps"
date: today
toc: true
format:
  html: 
    code-overflow: wrap
    toc: true
    toc-title: "Contents"
    theme: solar
    # hide code?

execute:
  warning: false
  message: false
---



Note: This is based off [Sarah's Notes](https://sarahpenir.github.io/r/making-maps/)

# Making Maps in R

Let's plot the **global human development index (HDI)**. The HDI metric from the United Nations Development Program (UNDP) is a summary measure of the average achievement of a country in key dimensions of human development: a long and healthy life, being knowledgeable, and a decent standard of living (value ranges from 0 to 1, higher = better).

# Load Libraries



```{r}
# install.packages("maps")
# install.packages("countrycode")
library(countrycode)
library(dplyr)
library(stringr)
library(ggplot2)
library(maps)
```





The maps package contains outlines of several continents, countries, and states (examples: world, usa, state) that have been with R for a long time. maps has its own plotting function, but we will use the map_data() function of ggplot2 to make a data frame that ggplot2 can operate on.

# Create a data frame from map outlines



```{r}
world <- map_data("world")
```



The new world data frame has the following variables: long for longitude, lat for latitude, group tells which adjacent points to connect, order refers to the sequence by which the points should be connected, and region and subregion annotate the area surrounded by a set of points.


# Make  a simple world map

`geom_polygon()` draws maps with gray fill by default and `coord_fixed()` specifies the aspect ratio of the plot (every `y` unit is 1.3 times longer than the `x` unit).



```{r}
world <- map_data("world")
worldplot <- ggplot() +
  geom_polygon(data = world, aes(x=long, y = lat, group = group)) + 
  coord_fixed(1.3)
worldplot
```



# Prepare to merge data



```{r}
library(tidyverse)
# add variable in world data that is commonly used for merging
world <- world |> mutate(cname = countrycode(
  region, 
  origin = 'country.name.en', 
  destination = 'genc3c'))

gce <- read_csv("~/g/teaching/dat309/week6/global_climate_events_economic_impact_2020_2025.csv")

gce <- gce |> mutate(cname = countrycode(
  country, 
  origin = 'country.name.en', 
  destination = 'genc3c'))



world_gce <- left_join(gce, world,by="cname")
```





# final plotting


```{r}
gce_plot <- ggplot(data = world_gce, mapping = aes(x = long, y = lat, group = group)) + 
  coord_fixed(1.3) +
  geom_polygon(aes(fill = impact_per_capita)) +
  scale_fill_distiller(palette ="RdBu", direction = -1) + # or direction=1
  ggtitle("Global Events") +
  theme_minimal()

gce_plot
```

