---
title: "Case study"
output: html_notebook
---

```{r}
library(tidyverse)
library(viridis)
```

```{r}
path <- "death_rates/Mx_1x1/ITA.Mx_1x1.txt"
rates <- read_table(path,
                    skip = 2,
                    col_types = "iiddd") %>%
  filter(Age <= 90) %>%
  drop_na() %>%
  select(-Total) %>%
  pivot_longer(Female:Male, names_to="Sex", values_to="Rate") %>%
  mutate(Percentile = ntile(Rate, 100))

rates
```


```{r}
ggplot(rates, aes(x = Year,
                  y = Age,
                  fill = Percentile)) +
  geom_tile() +
  scale_fill_viridis(option = "B",
                     discrete = F,
                     direction = -1) +
                     #breaks = c(1, 50 , 99),
                     #labels = c("Lowest 1%", "Median", "Top 1%")) +
  facet_wrap(vars(Sex), ncol = 1) +
  theme_classic() +
  theme(rect = element_rect(fill="gray2"),
        text = element_text(color="gray80"),
        panel.background = element_rect(fill="gray2"),
        strip.background = element_blank(),
        strip.text = element_text(color="gray80", hjust=0),
        axis.text = element_text(color="gray80"))
```
















```{r}
mortality <- read_table("death_rates/Mx_1x1/ITA.Mx_1x1.txt", 
                        skip=2, 
                        na=".", 
                        col_types = "iiddd") %>%
  filter(Age <= 90) %>%
  drop_na() %>%
  select(-Total) %>%
  pivot_longer(Female:Male, names_to="Gender", values_to="DeathRate") %>%
  mutate(Percentile = ntile(DeathRate, 100))
mortality
```

```{r}
ggplot(mortality, aes(x=Year, y=Age, fill=Percentile)) +
  geom_tile() +
  scale_fill_viridis(option = "B", direction=-1,
                     breaks = c(1, 50, 100),
                     labels = c("Lowest 1%", "median", "Highest 1%")) +
  facet_wrap(vars(Gender), ncol = 1) +
  theme_classic() +
  theme(rect = element_rect(fill="gray2"),
        text = element_text(color="gray80"),
        panel.background = element_rect(fill="gray2"),
        strip.background = element_blank(),
        strip.text = element_text(color="gray80", hjust=0),
        axis.text = element_text(color="gray80"))
```










