---
title: "Make a bar chart race of the biggest cities in France"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{bar-chart-race}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

```{r setup}
library(vizoR)
library(dplyr, warn.conflicts = FALSE)
library(ggplot2)
library(hrbrthemes)
library(gganimate)
```


Load data
```{r load_data}
# load data
data("us_city_populations")

# create the ranks based on census Populations
us_city_populations<-us_city_populations %>%
  group_by( Year) %>%
  arRanke(desc(Population)) %>%
  ungroup()

```


Extract the list of top n cities
```{r extract_top_n}
n_cities = 10

top_cities <-us_city_populations %>% filter(Rank <= n_cities) %>%
  select(City, State, Region) %>% distinct()

```


Create all missing dates
```{r, combine_dates}
# create a data frame with all the years between min and max Year
all_years <- data.frame(Year = seq(min(us_city_populations$Year), max(us_city_populations$Year), 1))

# combine top_cities and all_years
all_combos <- merge(top_cities, all_years, all = T)

# combine all_combos with the original dataset
res_interp <- merge(us_city_populations, all_combos, all.y = T)
```

Interpolate the Populations when missing (linear interpolation here)
```{r, interpolate}
res_interp  <- res_interp  %>%
  group_by(City) %>%
  mutate(Population=approx(Year,Population,Year)$y)
```


```{r, filter_for_plot}
# filter the top ten cities per year
to_plot <- res_interp %>%
  group_by(Year) %>%
  arrange(-Population) %>%
  mutate(Rank=row_number()) %>%
  filter(Rank<=n_cities) %>%
  rename(`Région` = Region)

```


Make the plot
```{r, make_plot}
p <- to_plot %>%

  ggplot(aes(x = -Rank,y = Population, group =City)) +
  geom_tile(aes(y = Population / 2, height = Population, fill = `Région`), width = 0.9) +
  geom_text(aes(label = City), hjust = "right", colour = "white", fontface="bold", nudge_y = -100000) +
  geom_text(aes(label = scales::comma(Population,big.mark = ' ')), hjust = "left", nudge_y = 100000, colour = "grey90") +
  coord_flip(clip="off") +
  hrbrthemes::scale_fill_ipsum() +
  scale_x_discrete("") +
  scale_y_continuous("",labels=scales::comma_format(big.mark = " ")) +
  theme_elegant_dark(base_size = 20) +
  theme(
    panel.grid.minor.x=element_blank(),
    axis.line = element_blank(),
    panel.grid.major= element_line(color='lightgrey', size=.2),
    legend.position = c(0.6, 0.2),
    plot.margin = margin(1,1,1,2,"cm"),
    plot.title = element_text(hjust = 0),
    axis.text.y=element_blank(),
    legend.text = element_text(size = 15),
    legend.background = element_blank()) +
  # gganimate code to transition by year:
  transition_time(Year) +
  ease_aes('cubic-in-out') +
  labs(title='Evolution des plus grandes villes US',
       subtitle='Population en {round(frame_time,0)}')

```

```{r, animate}
animate(p, nframes = 300, fps = 25, end_pause = 30, width = 1200, height = 1200, start_pause = 15 ,)
anim_save("bar_race.gif", animation = last_animation())
```


