library(gapminder) 
# criado por jenny Bryan, conjunto de dados
library(dplyr) 
# criado por Hadley Wickham, que fornece ferramentas passo a passo para transformar esses dados, como filtrar, classificar e resumir.  
gapminder
## # A tibble: 1,704 x 6
##    country     continent  year lifeExp      pop gdpPercap
##    <fct>       <fct>     <int>   <dbl>    <int>     <dbl>
##  1 Afghanistan Asia       1952    28.8  8425333      779.
##  2 Afghanistan Asia       1957    30.3  9240934      821.
##  3 Afghanistan Asia       1962    32.0 10267083      853.
##  4 Afghanistan Asia       1967    34.0 11537966      836.
##  5 Afghanistan Asia       1972    36.1 13079460      740.
##  6 Afghanistan Asia       1977    38.4 14880372      786.
##  7 Afghanistan Asia       1982    39.9 12881816      978.
##  8 Afghanistan Asia       1987    40.8 13867957      852.
##  9 Afghanistan Asia       1992    41.7 16317921      649.
## 10 Afghanistan Asia       1997    41.8 22227415      635.
## # ... with 1,694 more rows

FILTER

# O verbo FILTER permite selecionar uma parte especifica dos dados para realizar sua analise. Deve ser precedido do *%>%* que significa (pegue o que estiver a frente e alimente-o na proxima etapa).

gapminder %>%
  filter (year == 2007)
## # A tibble: 142 x 6
##    country     continent  year lifeExp       pop gdpPercap
##    <fct>       <fct>     <int>   <dbl>     <int>     <dbl>
##  1 Afghanistan Asia       2007    43.8  31889923      975.
##  2 Albania     Europe     2007    76.4   3600523     5937.
##  3 Algeria     Africa     2007    72.3  33333216     6223.
##  4 Angola      Africa     2007    42.7  12420476     4797.
##  5 Argentina   Americas   2007    75.3  40301927    12779.
##  6 Australia   Oceania    2007    81.2  20434176    34435.
##  7 Austria     Europe     2007    79.8   8199783    36126.
##  8 Bahrain     Asia       2007    75.6    708573    29796.
##  9 Bangladesh  Asia       2007    64.1 150448339     1391.
## 10 Belgium     Europe     2007    79.4  10392226    33693.
## # ... with 132 more rows

Você poderia mudar o filtro para outra coisa

gapminder %>%
  filter(country == "United States")
## # A tibble: 12 x 6
##    country       continent  year lifeExp       pop gdpPercap
##    <fct>         <fct>     <int>   <dbl>     <int>     <dbl>
##  1 United States Americas   1952    68.4 157553000    13990.
##  2 United States Americas   1957    69.5 171984000    14847.
##  3 United States Americas   1962    70.2 186538000    16173.
##  4 United States Americas   1967    70.8 198712000    19530.
##  5 United States Americas   1972    71.3 209896000    21806.
##  6 United States Americas   1977    73.4 220239000    24073.
##  7 United States Americas   1982    74.6 232187835    25010.
##  8 United States Americas   1987    75.0 242803533    29884.
##  9 United States Americas   1992    76.1 256894189    32004.
## 10 United States Americas   1997    76.8 272911760    35767.
## 11 United States Americas   2002    77.3 287675526    39097.
## 12 United States Americas   2007    78.2 301139947    42952.

Podemos ter multiplas condições para o filtro, basta separá-las por “,” virgula.

gapminder %>%
  filter(year == 2007, country == "United States")
## # A tibble: 1 x 6
##   country       continent  year lifeExp       pop gdpPercap
##   <fct>         <fct>     <int>   <dbl>     <int>     <dbl>
## 1 United States Americas   2007    78.2 301139947    42952.

ARRANGE

# O verbo "arrange" classifica uma tabela baseado em uma variavel (crescente ou decrescente). É muito util quando voce deseja conhecer os valores mais extremos do conjunto do banco de dados.

gapminder %>%
  arrange(gdpPercap)
## # A tibble: 1,704 x 6
##    country          continent  year lifeExp      pop gdpPercap
##    <fct>            <fct>     <int>   <dbl>    <int>     <dbl>
##  1 Congo, Dem. Rep. Africa     2002    45.0 55379852      241.
##  2 Congo, Dem. Rep. Africa     2007    46.5 64606759      278.
##  3 Lesotho          Africa     1952    42.1   748747      299.
##  4 Guinea-Bissau    Africa     1952    32.5   580653      300.
##  5 Congo, Dem. Rep. Africa     1997    42.6 47798986      312.
##  6 Eritrea          Africa     1952    35.9  1438760      329.
##  7 Myanmar          Asia       1952    36.3 20092996      331 
##  8 Lesotho          Africa     1957    45.0   813338      336.
##  9 Burundi          Africa     1952    39.0  2445618      339.
## 10 Eritrea          Africa     1957    38.0  1542611      344.
## # ... with 1,694 more rows
# Dentro do verbo arrange voce coloca a variavel que orientará a classificacao  

Podemos organizar por ordem decrescente via arrange(desc())

gapminder %>%
  arrange(desc(gdpPercap))
## # A tibble: 1,704 x 6
##    country   continent  year lifeExp     pop gdpPercap
##    <fct>     <fct>     <int>   <dbl>   <int>     <dbl>
##  1 Kuwait    Asia       1957    58.0  212846   113523.
##  2 Kuwait    Asia       1972    67.7  841934   109348.
##  3 Kuwait    Asia       1952    55.6  160000   108382.
##  4 Kuwait    Asia       1962    60.5  358266    95458.
##  5 Kuwait    Asia       1967    64.6  575003    80895.
##  6 Kuwait    Asia       1977    69.3 1140357    59265.
##  7 Norway    Europe     2007    80.2 4627926    49357.
##  8 Kuwait    Asia       2007    77.6 2505559    47307.
##  9 Singapore Asia       2007    80.0 4553009    47143.
## 10 Norway    Europe     2002    79.0 4535591    44684.
## # ... with 1,694 more rows

Suponha que voce deseja encontrar (paises com maior gdp em apenas um ano)

gapminder %>%
  filter(year==2007) %>%
  arrange(desc(gdpPercap))
## # A tibble: 142 x 6
##    country          continent  year lifeExp       pop gdpPercap
##    <fct>            <fct>     <int>   <dbl>     <int>     <dbl>
##  1 Norway           Europe     2007    80.2   4627926    49357.
##  2 Kuwait           Asia       2007    77.6   2505559    47307.
##  3 Singapore        Asia       2007    80.0   4553009    47143.
##  4 United States    Americas   2007    78.2 301139947    42952.
##  5 Ireland          Europe     2007    78.9   4109086    40676.
##  6 Hong Kong, China Asia       2007    82.2   6980412    39725.
##  7 Switzerland      Europe     2007    81.7   7554661    37506.
##  8 Netherlands      Europe     2007    79.8  16570613    36798.
##  9 Canada           Americas   2007    80.7  33390141    36319.
## 10 Iceland          Europe     2007    81.8    301931    36181.
## # ... with 132 more rows

MUTATE verbo

# Serve para mudanças nas variaveis ou adicionar variaveis

gapminder %>%
      mutate(pop = pop / 1000000)
## # A tibble: 1,704 x 6
##    country     continent  year lifeExp   pop gdpPercap
##    <fct>       <fct>     <int>   <dbl> <dbl>     <dbl>
##  1 Afghanistan Asia       1952    28.8  8.43      779.
##  2 Afghanistan Asia       1957    30.3  9.24      821.
##  3 Afghanistan Asia       1962    32.0 10.3       853.
##  4 Afghanistan Asia       1967    34.0 11.5       836.
##  5 Afghanistan Asia       1972    36.1 13.1       740.
##  6 Afghanistan Asia       1977    38.4 14.9       786.
##  7 Afghanistan Asia       1982    39.9 12.9       978.
##  8 Afghanistan Asia       1987    40.8 13.9       852.
##  9 Afghanistan Asia       1992    41.7 16.3       649.
## 10 Afghanistan Asia       1997    41.8 22.2       635.
## # ... with 1,694 more rows

Suponha que eu deseje CRIAR uma nova variavel, por exemplo, o PIB total dos paises.

# aqui devemos usar "=" 

gapminder %>%
      mutate(gdp = gdpPercap * pop)
## # A tibble: 1,704 x 7
##    country     continent  year lifeExp      pop gdpPercap          gdp
##    <fct>       <fct>     <int>   <dbl>    <int>     <dbl>        <dbl>
##  1 Afghanistan Asia       1952    28.8  8425333      779.  6567086330.
##  2 Afghanistan Asia       1957    30.3  9240934      821.  7585448670.
##  3 Afghanistan Asia       1962    32.0 10267083      853.  8758855797.
##  4 Afghanistan Asia       1967    34.0 11537966      836.  9648014150.
##  5 Afghanistan Asia       1972    36.1 13079460      740.  9678553274.
##  6 Afghanistan Asia       1977    38.4 14880372      786. 11697659231.
##  7 Afghanistan Asia       1982    39.9 12881816      978. 12598563401.
##  8 Afghanistan Asia       1987    40.8 13867957      852. 11820990309.
##  9 Afghanistan Asia       1992    41.7 16317921      649. 10595901589.
## 10 Afghanistan Asia       1997    41.8 22227415      635. 14121995875.
## # ... with 1,694 more rows

Combinando os verbos (filter, arrange, mutate) para descobrir: quais os paises com maior PIB no ano de 2007.

# Precisamos: 1) criar a nova variavel, 2) filtrar pelo ano, 3) organizar por valores decrescentes
gapminder %>%
  mutate(gdp = gdpPercap * pop) %>%
  filter(year == 2007) %>%
  arrange(desc(gdp)) 
## # A tibble: 142 x 7
##    country        continent  year lifeExp        pop gdpPercap     gdp
##    <fct>          <fct>     <int>   <dbl>      <int>     <dbl>   <dbl>
##  1 United States  Americas   2007    78.2  301139947    42952. 1.29e13
##  2 China          Asia       2007    73.0 1318683096     4959. 6.54e12
##  3 Japan          Asia       2007    82.6  127467972    31656. 4.04e12
##  4 India          Asia       2007    64.7 1110396331     2452. 2.72e12
##  5 Germany        Europe     2007    79.4   82400996    32170. 2.65e12
##  6 United Kingdom Europe     2007    79.4   60776238    33203. 2.02e12
##  7 France         Europe     2007    80.7   61083916    30470. 1.86e12
##  8 Brazil         Americas   2007    72.4  190010647     9066. 1.72e12
##  9 Italy          Europe     2007    80.5   58147733    28570. 1.66e12
## 10 Mexico         Americas   2007    76.2  108700891    11978. 1.30e12
## # ... with 132 more rows

PLOTANDO seus dados I

library(ggplot2)
ggplot(gapminder, aes(x = gdpPercap, y = lifeExp)) + 
  geom_point()

Aquivamos vamos usar o pacote ggplot2. Uma explicação importante adicional: algumas vezes quando voce trabalha continuamente com os dados filtrados por uma variavel (subjconjunto), algumas vezes é útil salvar os dados filtrados, como um novo conjunto de dados.

gapminder_2007 <- gapminder %>%
                    filter(year == 2007)

gapminder_2007
## # A tibble: 142 x 6
##    country     continent  year lifeExp       pop gdpPercap
##    <fct>       <fct>     <int>   <dbl>     <int>     <dbl>
##  1 Afghanistan Asia       2007    43.8  31889923      975.
##  2 Albania     Europe     2007    76.4   3600523     5937.
##  3 Algeria     Africa     2007    72.3  33333216     6223.
##  4 Angola      Africa     2007    42.7  12420476     4797.
##  5 Argentina   Americas   2007    75.3  40301927    12779.
##  6 Australia   Oceania    2007    81.2  20434176    34435.
##  7 Austria     Europe     2007    79.8   8199783    36126.
##  8 Bahrain     Asia       2007    75.6    708573    29796.
##  9 Bangladesh  Asia       2007    64.1 150448339     1391.
## 10 Belgium     Europe     2007    79.4  10392226    33693.
## # ... with 132 more rows

Suponha que voce queira examinar a relação entre a riqueza de um pais e sua expectativa de vida.

ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp)) + 
  geom_point()

AES, aesthetic é uma dimensao visual de um grafico que pode ser usada para comunicar informacoes. GEOM_POINT, voce está adicionando um objeto geometrico ao grafico, trata-se de especificar o tipo de grafico que voce está criando.

LOG SCALES

Fizemos o grafico acima, e percebemos que paises de renda mais alta, tem maior expectativa de vida. Um problema com esse grafico, no entanto, é que muitos paises ficam amontoados na parte mais à esquerda do eixo x.

Isso ocorreu porque a distribuicao do pib per capita abrange varias ordens de magnitude, com alguns paises na casa das dezenas de milhares de dolares e outros na casa das centenas.

Quando um de nossos eixos apresenta essa distribuição, é util trabalhar com uma escala logaritimica, ou seja, uma escala em que cada distância fixa representa uma multiplicacao do valor.

Criando o grafico usando o log scale

ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp)) +
  geom_point() + 
    scale_x_log10()

Esses sao os mesmo dados, mas agora cada unidade no eixo x representa uma mudança de 10 vezes o PIB.

Nesse novo grafico podemos ver os dados de uma maneira mais linear, e podemos distinguir mais facilmente os paises na extremidade inferior do espectro.

**Algumas vezes ambos os eixos devem ser convertidos para a escala de log.

# Criando o gapminder filtrado para o ano 1952 
gapminder_1952 <- gapminder %>% 
                  filter(year == 1952)

Plotando com ambos os eixos com escala de log

ggplot (gapminder_1952, aes(x = pop, y = gdpPercap)) +
        scale_x_log10() + 
        scale_y_log10() +
        geom_point()

ESTÉTICA ADICIONAL - additional aesthetics

Nós aprendemos como criar uma plotagem de duas variaveis e assim enxergar sua relacao. O nosso banco de dados “gapminder” possui outras variaveis que podem também ser utilizadas, de maneira a entendermos outros relacionamentos entre elas.

Ate aqui usamos populacao como eixo X, e pib per capita como eixo y. Agora vamos aprender a usar mais duas esteticas adicionais, COLOR and SIZEe e para isso vamos utilizar as variaveis continente e pais.

Observe que continente é uma variavel categórica, e por isso apresenta valores bem especificos. Uma boa maneira de apresentar variaveis categorias em um gráfico é através da dimensao COLOR.

ggplot (gapminder_2007, aes(x = gdpPercap, y =lifeExp, color = continent)) +
        scale_x_log10() + 
        geom_point()

Observe que populacao (pop) é uma variavel numérica, uma boa maneira de apresentar variaveis numericas um gráfico é através da dimensao SIZE, que significa “tamanho”.

ggplot (gapminder_2007, aes(x = gdpPercap, y =lifeExp, color = continent, size = pop)) +
        scale_x_log10() + 
        geom_point()

FACETING

Esse verbo serve para dividir nossa plotagem em subtramas para uma obter uma melhor visualizacao em um grafico menor para cada continente (por exemplo).

ggplot (gapminder_2007, aes(x = gdpPercap, y =lifeExp, color = continent)) +
       geom_point() + 
      scale_x_log10() + 
      facet_wrap(~ continent)

# ~ signica "por"

CALCULO

gapminder %>%
      summarize(sumPop = sum(as.numeric(pop)))
## # A tibble: 1 x 1
##        sumPop
##         <dbl>
## 1 50440465801
gapminder_1952_2007 <- gapminder %>%
                        filter(year == 1952|2007)

# aqui eu estou pedindo os anos entre 1952 a 2007
ggplot(gapminder_1952_2007, aes(x = gdpPercap, y = lifeExp, 
                    color = continent, size = pop)) + 
          geom_point()+
          scale_x_log10()+
          facet_wrap(~year)

SUMMARIZE verbo

Agora voce aprendera a resumir muitas observacoes em um unico ponto de dados .

gapminder %>%
     summarize(meanLifeExp = mean(lifeExp))
## # A tibble: 1 x 1
##   meanLifeExp
##         <dbl>
## 1        59.5

Faz mais sentido analisar a media da expectativa de vida para um ano em especifico, por exemplo.

gapminder %>%
      filter(year == 2007) %>%
     summarize(meanLifeExp = mean(lifeExp))
## # A tibble: 1 x 1
##   meanLifeExp
##         <dbl>
## 1        67.0

Podemos acrescentar mais detalhes a nossa funcao summarize

gapminder %>%
      filter(year == 2007) %>%
      summarize(meanLifeExp = mean(lifeExp), 
          totalPop = sum(as.numeric(pop)))
## # A tibble: 1 x 2
##   meanLifeExp   totalPop
##         <dbl>      <dbl>
## 1        67.0 6251013179

Podemos ainda summarizar via “mediana - median”, “minimo - min” e “maximo - max”

gapminder %>%
        filter(year == 2007) %>%
        summarize(medianLifeExp = median(lifeExp), maxGdpPercap = max(gdpPercap)) 
## # A tibble: 1 x 2
##   medianLifeExp maxGdpPercap
##           <dbl>        <dbl>
## 1          71.9       49357.

Verbo GROUP_by

Em um dos exemplos acima, nós encontramos a media da expectativa de vida e o total da populacao para o ano de 2007. Mas e se nao quisemos apenas para 2007? Mas em cada ano do conjunto.

group_by() antes do summarize() transforma em grupos dentro de uma

gapminder %>%
      group_by(year) %>%
      summarize(meanLifeExp = mean(lifeExp), sumPop = sum(as.numeric(pop)))
## # A tibble: 12 x 3
##     year meanLifeExp     sumPop
##    <int>       <dbl>      <dbl>
##  1  1952        49.1 2406957150
##  2  1957        51.5 2664404580
##  3  1962        53.6 2899782974
##  4  1967        55.7 3217478384
##  5  1972        57.6 3576977158
##  6  1977        59.6 3930045807
##  7  1982        61.5 4289436840
##  8  1987        63.2 4691477418
##  9  1992        64.2 5110710260
## 10  1997        65.0 5515204472
## 11  2002        65.7 5886977579
## 12  2007        67.0 6251013179

Sumarizando pelo continente

gapminder %>%
      filter(year == 2002) %>%
      group_by(continent) %>%
      summarize(meanLifeExp = mean(lifeExp), sum(as.numeric(pop)))
## # A tibble: 5 x 3
##   continent meanLifeExp `sum(as.numeric(pop))`
##   <fct>           <dbl>                  <dbl>
## 1 Africa           53.3              833723916
## 2 Americas         72.4              849772762
## 3 Asia             69.2             3601802203
## 4 Europe           76.7              578223869
## 5 Oceania          79.7               23454829
# observe que temos um problema no continente ASIA. Há dados missing NA 

Agora que calculamos essas estatisticas para 2002, voce pode estar interessado em como elas mudaram para cada continente ao longo do tempo.

gapminder %>%
      group_by(year, continent) %>%
      summarize(meanLifeExp = mean(lifeExp), sum(as.numeric(pop)))
## # A tibble: 60 x 4
## # Groups:   year [12]
##     year continent meanLifeExp `sum(as.numeric(pop))`
##    <int> <fct>           <dbl>                  <dbl>
##  1  1952 Africa           39.1              237640501
##  2  1952 Americas         53.3              345152446
##  3  1952 Asia             46.3             1395357351
##  4  1952 Europe           64.4              418120846
##  5  1952 Oceania          69.3               10686006
##  6  1957 Africa           41.3              264837738
##  7  1957 Americas         56.0              386953916
##  8  1957 Asia             49.3             1562780599
##  9  1957 Europe           66.7              437890351
## 10  1957 Oceania          70.3               11941976
## # ... with 50 more rows
# devo lembrar porque estou usando as.numeric()
# observe que temos um problema no continente ASIA. Há dados missing NA 

Exercicio I

# Find median life expectancy and maximum GDP per capita in each continent in 1957

# Resposta

gapminder %>%
          filter(year == 1957) %>%
          group_by(continent) %>%
          summarize(medianLifeExp = median(lifeExp), 
                  maxGdpPercap = max(gdpPercap))
## # A tibble: 5 x 3
##   continent medianLifeExp maxGdpPercap
##   <fct>             <dbl>        <dbl>
## 1 Africa             40.6        5487.
## 2 Americas           56.1       14847.
## 3 Asia               48.3      113523.
## 4 Europe             67.6       17909.
## 5 Oceania            70.3       12247.

Exercicio II

# Find median life expectancy and maximum GDP per capita in each continent/year combination

# Resposta

gapminder %>%
         group_by(continent, year) %>%
          summarize(medianLifeExp = median(lifeExp), 
                  maxGdpPercap = max(gdpPercap))
## `summarise()` has grouped output by 'continent'. You can override using the `.groups` argument.
## # A tibble: 60 x 4
## # Groups:   continent [5]
##    continent  year medianLifeExp maxGdpPercap
##    <fct>     <int>         <dbl>        <dbl>
##  1 Africa     1952          38.8        4725.
##  2 Africa     1957          40.6        5487.
##  3 Africa     1962          42.6        6757.
##  4 Africa     1967          44.7       18773.
##  5 Africa     1972          47.0       21011.
##  6 Africa     1977          49.3       21951.
##  7 Africa     1982          50.8       17364.
##  8 Africa     1987          51.6       11864.
##  9 Africa     1992          52.4       13522.
## 10 Africa     1997          52.8       14723.
## # ... with 50 more rows

PLOTANDO seus dados sumarizados

vimos

by_year <-  gapminder %>%
              group_by(year) %>%
              summarize( medianLifExp = median(lifeExp), 
                  totalPop = sum(as.numeric(pop)))

by_year 
## # A tibble: 12 x 3
##     year medianLifExp   totalPop
##    <int>        <dbl>      <dbl>
##  1  1952         45.1 2406957150
##  2  1957         48.4 2664404580
##  3  1962         50.9 2899782974
##  4  1967         53.8 3217478384
##  5  1972         56.5 3576977158
##  6  1977         59.7 3930045807
##  7  1982         62.4 4289436840
##  8  1987         65.8 4691477418
##  9  1992         67.7 5110710260
## 10  1997         69.4 5515204472
## 11  2002         70.8 5886977579
## 12  2007         71.9 6251013179

Visualisacao da populacao no tempo

ggplot(by_year, aes(x = year, y = totalPop)) +
      geom_point()

Começando o eixo y do zero

ggplot(by_year, aes(x = year, y = totalPop)) +
      geom_point() +
      expand_limits(y=0)

ggplot(by_year, aes(x = year, y = medianLifExp)) +
      geom_point() +
      expand_limits(y=0)

Sumarizando por ano e continente

by_year_continent <- gapminder %>%
                  group_by(year, continent) %>%
                  summarize(totalPop = sum(as.numeric(pop)), 
                  meanLifeExp = mean(lifeExp))
## `summarise()` has grouped output by 'year'. You can override using the `.groups` argument.
by_year_continent
## # A tibble: 60 x 4
## # Groups:   year [12]
##     year continent   totalPop meanLifeExp
##    <int> <fct>          <dbl>       <dbl>
##  1  1952 Africa     237640501        39.1
##  2  1952 Americas   345152446        53.3
##  3  1952 Asia      1395357351        46.3
##  4  1952 Europe     418120846        64.4
##  5  1952 Oceania     10686006        69.3
##  6  1957 Africa     264837738        41.3
##  7  1957 Americas   386953916        56.0
##  8  1957 Asia      1562780599        49.3
##  9  1957 Europe     437890351        66.7
## 10  1957 Oceania     11941976        70.3
## # ... with 50 more rows

Vamos agora visualizar “by_year_continent” pela estetica de cores

ggplot(by_year_continent, aes(x = year, y = totalPop, color = continent)) +
      geom_point() +
      expand_limits(y=0)

Exercicio

# Summarize medianGdpPercap within each continent within each year: by_year_continent
by_year_continent <- gapminder %>%
                  group_by(year, continent) %>%
                  summarize(medianGdpPercap = median(gdpPercap))
## `summarise()` has grouped output by 'year'. You can override using the `.groups` argument.
# Plot the change in medianGdpPercap in each continent over time
ggplot(by_year_continent, aes(x = year, y = medianGdpPercap, color = continent)) +
geom_point() +
expand_limits(y=0)

Exercicio

# Summarize the median GDP and median life expectancy per continent in 2007
by_continent_2007 <- gapminder %>%
            filter(year == 2007) %>%
            group_by(continent) %>%
              summarize(medianGdpPercap = median(gdpPercap), 
              medianLifeExp = median(lifeExp))

# Use a scatter plot to compare the median GDP and median life expectancy
ggplot(by_continent_2007, aes(x = medianGdpPercap, y = medianLifeExp, color = continent)) + 
      geom_point() +
      expand_limits(y=0)

SCATER VS LINE PLOT

A line plot is useful for visualizing trends over time. In this exercise, you’ll examine how the median GDP per capita has changed over time.

Para criar o grafico de linhas, basta usar o comando geom_line().

by_year_continent <- gapminder %>%
                  group_by(year, continent) %>%
                  summarize(totalPop = sum(as.numeric(pop)), 
                  meanLifeExp = mean(lifeExp))
## `summarise()` has grouped output by 'year'. You can override using the `.groups` argument.
ggplot(by_year_continent, aes(x = year, y = meanLifeExp, color = continent)) + geom_line() +
  expand_limits(y = 0)

Exercicio

Use group_by() and summarize() to find the median GDP per capita within each year, calling the output column medianGdpPercap. Use the assignment operator <- to save it to a dataset called by_year.

Use the by_year dataset to create a line plot showing the change in median GDP per capita over time. Be sure to use expand_limits(y = 0) to include 0 on the y-axis.

# Summarize the median gdpPercap by year, then save it as by_year
by_year <- gapminder %>%
                group_by(year) %>%
                summarize(medianGdpPercap = median(gdpPercap))

# Create a line plot showing the change in medianGdpPercap over time
ggplot(by_year, aes(x = year, y = medianGdpPercap)) +
          geom_line() +
          expand_limits(y=0)

Exercicio

Now you’ll examine the change within each continent.

Use group_by() and summarize() to find the median GDP per capita within each year and continent, calling the output column medianGdpPercap. Use the assignment operator <- to save it to a dataset called by_year_continent.

Use the by_year_continent dataset to create a line plot showing the change in median GDP per capita over time, with color representing continent. Be sure to use expand_limits(y = 0) to include 0 on the y-axis.

# Summarize the median gdpPercap by year & continent, save as by_year_continent
by_year_continent <- gapminder %>% 
                      group_by(year, continent) %>%
                      summarize(medianGdpPercap = median(gdpPercap))
## `summarise()` has grouped output by 'year'. You can override using the `.groups` argument.
# Create a line plot showing the change in medianGdpPercap by continent over time
ggplot(by_year_continent, aes(x = year, y = medianGdpPercap, 
        color = continent)) + 
        geom_line() +
        expand_limits(y = 0)

BAR PLOTS - Grafico de barras

O graficos de barra sao uteis para voce comparar valores entre categorias distintas, como continentes.Por exemplo, vimos que para encontrar a expectativa de vida média em cada continente em 2007, precisamos do seguinte código. Ele criará uma tabela com uma observação para cada continente.

by_continent_2007 <- gapminder %>%
            filter(year == 2007) %>%
            group_by(continent) %>%
              summarize(meanLifeExp = mean(lifeExp))

by_continent_2007
## # A tibble: 5 x 2
##   continent meanLifeExp
##   <fct>           <dbl>
## 1 Africa           54.8
## 2 Americas         73.6
## 3 Asia             70.7
## 4 Europe           77.6
## 5 Oceania          80.7

Em vez de imprimir a tabela, podemos este resumo visualmente.

Exercicio

Use group_by() and summarize() to find the median GDP per capita within each continent in the year 1952, calling the output column medianGdpPercap. Use the assignment operator <- to save it to a dataset called by_continent.

Use the by_continent dataset to create a bar plot showing the median GDP per capita in each continent.

# Summarize the median gdpPercap by continent in 1952
by_continent <- gapminder %>%
                filter(year == 1952) %>%
                group_by(continent) %>%
                summarize(medianGdpPercap = median(gdpPercap))

# Create a bar plot showing medianGdp by continent
ggplot(by_continent, aes(x = continent, y = medianGdpPercap)) +
      geom_col()

Exercicio

Visualizing GDP per capita by country in Oceania

You’ve created a plot where each bar represents one continent, showing the median GDP per capita for each. But the x-axis of the bar plot doesn’t have to be the continent: you can instead create a bar plot where each bar represents a country.

In this exercise, you’ll create a bar plot comparing the GDP per capita between the two countries in the Oceania continent (Australia and New Zealand).

# *Instruções* 

# Filter for observations in the Oceania continent in the year 1952. Save this as oceania_1952.

# Use the oceania_1952 dataset to create a bar plot, with country on the x-axis and gdpPercap on the y-axis.
# Filter for observations in the Oceania continent in 1952
oceania_1952 <- gapminder %>%
                filter(year == 1952, continent == "Oceania") %>%
                group_by(country, continent)

# Create a bar plot of gdpPercap by country
ggplot(oceania_1952, aes(x = country, y = gdpPercap)) +
        geom_col()

HISTOGRAMAS

Ate agora haviamos investigados a relacao entre duas variaveis ao mesmo tempo. Aqui veremos como investigar uma dimensao dos dados por vez, usando um histograma.

ggplot(gapminder_2007, aes(x = lifeExp)) + 
  geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

No grafico acima, temos no eixo x a expectativa de vida em anos, enquanto que no eixo y (vertical), temos o numero de paises que apresentam essa expectativa. O que podemos ver com esses dados?

A largura de cada histograma é escolhida automaticamente, e isso tem um grande efeito sobre como o histograma comunica a distribuicao. Podemos alterar essa largura via opção _ binwidth_ que colocamos dentro da camada geom_histogram()

ggplot(gapminder_2007, aes(x = lifeExp)) + 
  geom_histogram(binwidth = 5)

# ao definirmos binwidth = 5 significa que cada uma das barras nos histogramas representa uma largura de 5 anos. 

# Ao fazermos isso convertemos o visual da distribuicao mais em bloco, e isso significa que estamos mais interessados na forma mais geral do que nos pequenos detalhes. 

Exercicio Visualizing population

A histogram is useful for examining the distribution of a numeric variable. In this exercise, you’ll create a histogram showing the distribution of country populations (by millions) in the year 1952.

Code for generating this dataset, gapminder_1952, is provided.

# Use the gapminder_1952 dataset to create a histogram of country population (pop_by_mil) in the year 1952. Inside the histogram geom, set the number of bins to 50.

gapminder_1952 <- gapminder %>%
  filter(year == 1952) %>%
  mutate(pop_by_mil = pop / 1000000)

# Create a histogram of population (pop_by_mil)
ggplot(gapminder_1952, aes(x = pop_by_mil)) + 
geom_histogram(bins = 50)

Exercicio Visualizing population with x-axis on a log scale

In the last exercise you created a histogram of populations across countries. You might have noticed that there were several countries with a much higher population than others, which causes the distribution to be very skewed, with most of the distribution crammed into a small part of the graph. (Consider that it’s hard to tell the median or the minimum population from that histogram).

To make the histogram more informative, you can try putting the x-axis on a log scale.

# Use the gapminder_1952 dataset (code is provided) to create a histogram of country population (pop) in the year 1952, putting the x-axis on a log scale with scale_x_log10().

gapminder_1952 <- gapminder %>%
  filter(year == 1952)

# Create a histogram of population (pop), with x on a log scale
ggplot(gapminder_1952, aes(x = pop)) + 
      geom_histogram(bins = 50) +
      scale_x_log10()

BOX PLOTS

Antes lembre-se que usamos o histograma quando queríamos examinar a distribuicao de uma variavel, da expectativa de vida, em todos os paises. O histograma combina todas as expectativas de vida em todos os continentes, sem distingui-las.

ggplot(gapminder_2007, aes(x = lifeExp)) + 
  geom_histogram(binwidth = 5)

Mas e se desejarmos comparar a distribuicao das expectativas de vida entre os continentes?

ggplot(gapminder_2007, aes(x = continent, y = lifeExp)) + 
  geom_boxplot()

# este é um gráfico que mostra a distribuicao das expectativas de vida dentro de cada continent, para que voce possa compara-la.

# observe: x = continentes (categoria)
#          y = os valores de expectativa de vida

Um grafico de caixa requer um pouco de pratica para interpretar. No exemplo acima temos:

Portanto, ha muita coisa que esse enredo nos fala sobre diferencas na expectativa de vida nos continentes. Podemos ver que a expectativa média de vida da Europa é uma das mais altas e que os paises da Oceania tem valores muito altos. E tambem podemos ver que a distribuicao para a Africa e extraordinariamente baixa, com cerca da metade de seus paises tendo uma expectativa media de vida entre 50 e 60 anos.

Exercicio Comparing GDP per capita across continents

A boxplot is useful for comparing a distribution of values across several groups. In this exercise, you’ll examine the distribution of GDP per capita by continent. Since GDP per capita varies across several orders of magnitude, you’ll need to put the y-axis on a log scale.

Use the gapminder_1952 dataset (code is provided) to create a boxplot comparing GDP per capita (gdpPercap) among continents. Put the y-axis on a log scale with scale_y_log10().

gapminder_1952 <- gapminder %>%
  filter(year == 1952)

# Create a boxplot comparing gdpPercap among continents
ggplot(gapminder_1952, aes(x = continent, y = gdpPercap)) +
      geom_boxplot() +
      scale_y_log10()

Exercicio Adding a title to your graph

There are many other options for customizing a ggplot2 graph, which you can learn about in other DataCamp courses. You can also learn about them from online resources, which is an important skill to develop.

As the final exercise in this course, you’ll practice looking up ggplot2 instructions by completing a task we haven’t shown you how to do.

Add a title to the graph: Comparing GDP per capita across continents. Use a search engine, such as Google or Bing, to learn how to do so.

# Add a title to this graph: "Comparing GDP per capita across continents"
p <- ggplot(gapminder_1952, aes(x = continent, y = gdpPercap)) +
  geom_boxplot() +
  scale_y_log10()
  
# Add titles
g <- p + labs(title = "Comparing GDP per capita across continents")
g  

# Observe que precisamos da camada labs()

DATA VISUALIZATION WITH GGPLOT2 - 5h

IMPORTING & CLEANING DATA - 14h

EXPLORATORY DATA ANALYSIS IN R: CASE STUDY