---
title: "Rosling Demo"
author: "kvlinden"
output: html_document
---

This R-Markdown file reproduces the code demoed in the class demo slideshow.

First, we load the libraries with the required programming tools and the raw data.

```{r warning=FALSE, message=FALSE}
library(tidyverse)
library(gapminder)
```

Here&rsquo;s the data (from the [gapminder library](https://www.rdocumentation.org/packages/gapminder)).

```{r}
gapminder
```

This computes the average life expectancy in the data over all countries and all times.

```{r}
gapminder %>% 
  summarize(AvgLifeExp = mean(lifeExp))
```

This groups the data by year and computes an average per group.

```{r}
gapminder %>% 
  group_by(year) %>%
  summarize(AvgLifeExp = mean(lifeExp))
```

This takes the same data, grouped by year, and plots the average over time using a line plot.

```{r}
gapminder %>% 
  group_by(year) %>%                      
  summarize(AvgLifeExp = mean(lifeExp)) %>%
  ggplot() + #<<
  aes(x=year, y=AvgLifeExp) +  #<<
  geom_line() #<<
```

Finally, this graph approximates one time-stop of Rosling&rsquo;s famous animated plot (see: [The Best Stats You&rsquo;ve Ever Seen](https://www.ted.com/talks/hans_rosling_the_best_stats_you_ve_ever_seen).

```{r}
library(scales)

gapminder %>% 
  filter(year == 2007) %>%
  ggplot() +
  aes(x = gdpPercap, y = lifeExp) +
  geom_point(alpha = .8) +
  aes(color = continent) +
  aes(size = pop) + 
  scale_x_continuous( 
    breaks = c(400, 4000, 40000),
    trans = "log10") +
  labs(x = "GDP per Capita") +
  labs(y = "Life Expectancy (years)") + 
  labs(color = "Continent") +
  labs(size = "Population") +
  scale_size_area(labels=label_comma()) + 
  theme_bw() +
  annotation_logticks(sides = "b")
```

**Question:** Could you do this in Excel?
