Pacotes usados nesses exercícios

library(ggplot2)
library(dplyr)
library(knitr)
library(rmarkdown)
library(janitor)
library(kableExtra)
library(gridExtra)
library(corrplot)
library(readxl)
library(ggthemes)
library(maps)
library(viridis)

\[ \star \]

Exercício 1 - Visualizando os dados

data("USArrests")

Informações sobre o conjunto de dados clicando aqui.

Conhecendo o dataset

kable(head(USArrests, 10), col.names = c("Assasinato*","Assalto*","Pop. Urbana(%)","Estupro*")) %>% 
    kable_styling(full_width = FALSE,bootstrap_options = c("striped", "hover", "condensed", "responsive"))
Assasinato* Assalto* Pop. Urbana(%) Estupro*
Alabama 13.2 236 58 21.2
Alaska 10.0 263 48 44.5
Arizona 8.1 294 80 31.0
Arkansas 8.8 190 50 19.5
California 9.0 276 91 40.6
Colorado 7.9 204 78 38.7
Connecticut 3.3 110 77 11.1
Delaware 5.9 238 72 15.8
Florida 15.4 335 80 31.9
Georgia 17.4 211 60 25.8
(*): por 100mil habitantes.

\[ \cdot\cdot\cdot \]

Medidas resumo

kable(summary(USArrests),col.names = c("Assasinato","Assalto","Pop Urbana","Estupro")) %>% 
    kable_styling(full_width = FALSE,bootstrap_options = c("striped", "hover", "condensed", "responsive"))
Assasinato Assalto Pop Urbana Estupro
Min. : 0.800 Min. : 45.0 Min. :32.00 Min. : 7.30
1st Qu.: 4.075 1st Qu.:109.0 1st Qu.:54.50 1st Qu.:15.07
Median : 7.250 Median :159.0 Median :66.00 Median :20.10
Mean : 7.788 Mean :170.8 Mean :65.54 Mean :21.23
3rd Qu.:11.250 3rd Qu.:249.0 3rd Qu.:77.75 3rd Qu.:26.18
Max. :17.400 Max. :337.0 Max. :91.00 Max. :46.00

\[ \cdot\cdot\cdot \]

Tipo de Variáveis

glimpse(USArrests)
## Rows: 50
## Columns: 4
## $ Murder   <dbl> 13.2, 10.0, 8.1, 8.8, 9.0, 7.9, 3.3, 5.9, 15.4, 17.4, 5.3,...
## $ Assault  <int> 236, 263, 294, 190, 276, 204, 110, 238, 335, 211, 46, 120,...
## $ UrbanPop <int> 58, 48, 80, 50, 91, 78, 77, 72, 80, 60, 83, 54, 83, 65, 57...
## $ Rape     <dbl> 21.2, 44.5, 31.0, 19.5, 40.6, 38.7, 11.1, 15.8, 31.9, 25.8...

\[ \cdot\cdot\cdot \]

Medidas de Dispersão

Variáveis Amplitude Mín/Máx CV(%) Desv. Padrão IQR
Assasinato 16.6 0.8, 17.4 55.9259086 4.3555098 7.175
Estupro 38.7 7.3, 46 44.1144712 9.3663845 11.1
Assalto 292 45, 337 48.803971 83.3376608 140
Pop. Urb. 59 32, 91 22.0853882 14.4747634 23.25

O IQR é a medida entre o 3° e 1° quartil dos dados.

\[ \cdot\cdot\cdot \]

Exercício 1 - (a)

  • Histogramas

Histogramas das variáveis do conjunto de dados, com a respectiva densidade da distribuiçao, além de cortes horizontais, onde o pontilhado é a média e linha preta a mediana.

Assasinato

g1 <- ggplot(USArrests) +
    geom_histogram(aes(x = Murder,
                       y = ..density..),
                   bins = 9,
                   fill = "pink",
                   color = "red",
                   alpha = 0.65) +
        labs(x = "Cada 100 mil habitantes",
             y = "f(x)",
             title = "Assasinato EUA - 1973") +
    geom_density(aes(x = Murder),
                 linetype = "dashed",
                 color = "red") +
    geom_vline(aes(xintercept = mean(Murder)),
               color = "red",
               linetype = "dashed",
               size = 1.25) +
    geom_vline(aes(xintercept = median(Murder)),
               color = "black",
               size = 1.0)
g1

\[ \cdot\cdot\cdot \]

Assalto

g2 <- ggplot(USArrests) +
    geom_histogram(aes(x = Assault,
                       y = ..density..),
                   bins = 9,
                   fill = "Sky Blue",
                   color = "blue",
                   alpha = 0.65) +
        labs(x = "Cada 100 mil habitantes",
             y = "f(x)",
             title = "Assalto EUA - 1973") +
    geom_density(aes(x = Assault),
                 linetype = "dashed",
                 color = "blue") +
    geom_vline(aes(xintercept = mean(Assault)),
               color = "blue",
               linetype = "dashed",
               size = 1.25) +
    geom_vline(aes(xintercept = median(Assault)),
               color = "black",
               size = 1.0)  
g2

\[ \cdot\cdot\cdot \]

Estupro

g3 <- ggplot(USArrests) +
    geom_histogram(aes(x = Rape,
                       y = ..density..),
                   bins = 9,
                   fill = "light Green",
                   color = "dark green",
                   alpha = 0.65) +
        labs(x = "Cada 100 mil habitantes",
             y = "f(x)",
             title = "Estupro EUA - 1973") +
    geom_density(aes(x = Rape),
                 linetype = "dashed",
                 color = "dark green") +
    geom_vline(aes(xintercept = mean(Rape)),
               color = "dark green",
               linetype = "dashed",
               size = 1.25) +
    geom_vline(aes(xintercept = median(Rape)),
               color = "black",
               size = 1.0)
g3

\[ \cdot\cdot\cdot \]

População urbana

g4 <- ggplot(USArrests) +
    geom_histogram(aes(x = UrbanPop,
                       y = ..density..),
                   bins = 9,
                   fill = "orange",
                   color = "dark orange",
                   alpha = 0.35) +
        labs(x = "Porcentagem (%)",
             y = "f(x)",
             title = "População Urbana EUA - 1973") +
    geom_density(aes(x = UrbanPop),
                 linetype = "dashed",
                 color = "dark orange") +
    geom_vline(aes(xintercept = mean(UrbanPop)),
               color = "dark orange",
               linetype = "dashed",
               size = 1.25) +
    geom_vline(aes(xintercept = median(UrbanPop)),
               color = "black",
               size = 1.0)
g4

\[ \cdot\cdot\cdot \]

Visão geral

grid.arrange(g1, g2, g3, g4, ncol=2)

\[ \cdot\cdot\cdot \]

Exercício 1 - (b)

  • Box-plots

A interpretação de um box-plot aqui.

Assasinato

b1 <- ggplot(USArrests) +
    geom_boxplot(aes(x = Murder),
                   fill = "pink",
                   color = "red",
                   alpha = 0.35) +
        labs(title = "Assasinato EUA - 1973",
             x = "Por 100 mil habitantes") +
        scale_y_discrete()
b1

\[ \cdot\cdot\cdot \]

Assalto

b2 <- ggplot(USArrests) +
    geom_boxplot(aes(x = Assault),
                   fill = "Sky Blue",
                   color = "BLUE",
                   alpha = 0.35) +
        labs(title = "Assalto EUA - 1973",
             x = "Por 100 mil habitantes") +
        scale_y_discrete()
b2

\[ \cdot\cdot\cdot \]

Estupro

b3 <- ggplot(USArrests) +
    geom_boxplot(aes(x = Rape),
                   fill = "light green",
                   color = "dark green",
                   alpha = 0.35,
                 outlier.size = 2.1,
                 outlier.colour = "dark green",
                 outlier.alpha = 0.8,
                 outlier.shape = 19) +
        labs(title = "Estupro EUA - 1973",
             x = "Por 100 mil habitantes") +
    scale_y_discrete()
b3

Nevada e Alaska são os outliers do conjunto de dados.

dt_mdf <- arrange(USArrests, desc(Rape))
head(select(dt_mdf, Rape), 2)
##        Rape
## Nevada 46.0
## Alaska 44.5

\[ \cdot\cdot\cdot \]

População urbana

b4 <- ggplot(USArrests) +
    geom_boxplot(aes(x = UrbanPop),
                   fill = "orange",
                   color = "dark orange",
                   alpha = 0.35) +
        labs(title = "População urbana EUA - 1973",
             x = "Em porcentagem (%)") +
        scale_y_discrete()
b4

\[ \cdot\cdot\cdot \]

Visão geral

grid.arrange(b1, b2, b3, b4, ncol=2)

\[ \cdot\cdot\cdot \]

Exercício 2

Matriz Correlação

Vamos plotar uma matriz de correlação de Pearson entre as variáveis do banco de dados, e escolher a maior correlação para realizarmos o gráfico de dispersão.

col1 <- colorRampPalette(c("#FC4E07", "yellow", "gray", "#00AFBB", "purple"))

corrplot(cor(USArrests), method = "number", type = "lower", tl.pos = "d", tl.col = "black", col = col1(100))

O coeficiente de determinação R² é o resultado da correlação entre as variáveis elevado ao quadrado.

r2_usa <- (cor(USArrests$Murder, USArrests$Assault)^2) * 100
r2_usa
## [1] 64.30008

Obtemos como resultado de , o valor de 64.3000808%.

\[ \cdot\cdot\cdot \]

Gráfico de Dispersão

As variáveis que apresentaram maior correlação entre si, foram Assalto e Assasinato. Vamos ver o gráfico de dispersão entre elas.

d1 <- ggplot(USArrests, aes(x = Assault,
                            y = Murder)) + 
        geom_point(color = "#00AFBB") +
        geom_smooth(method = "lm",
                color = "#FC4E07",
                alpha = 0.08,
                fill = "#FC4E07") +
    labs(title = "Gráfico de dispersão entre Assalto e Assasinato no ano de 1973 nos EUA",
         x = "Assalto",
         y = "Assasinato")
d1


O coeficiente de correlação de Pearson, também chamado de correlação linear, é um grau de relação entre duas variáveis quantitativas e exprime o grau de correlação através de valores situados entre -1 e 1.
Quando o coeficiente de correlação se aproxima de 1, nota-se um aumento no valor de uma variável quando a outra também aumenta, ou seja, há uma relação linear positiva.

\[ \cdot\cdot\cdot \]

Mapas

  • Bônus - Uma visão com mapas
arrests <- USArrests 
arrests$region <- tolower(rownames(USArrests))

states_map <- map_data("state")
arrests_map <- left_join(states_map, arrests, by = "region")

z1 <- ggplot(arrests_map, aes(long, lat, group = group))+
  geom_polygon(aes(fill = Assault), color = "light gray")+
  scale_fill_viridis_c(option = "magma")

z2 <- ggplot(arrests_map, aes(long, lat, group = group))+
  geom_polygon(aes(fill = Rape), color = "light gray")+
  scale_fill_viridis_c(option = "magma")

z3 <- ggplot(arrests_map, aes(long, lat, group = group))+
  geom_polygon(aes(fill = Murder), color = "light gray")+
  scale_fill_viridis_c(option = "magma")

z4 <- ggplot(arrests_map, aes(long, lat, group = group))+
  geom_polygon(aes(fill = UrbanPop), color = "light gray")+
  scale_fill_viridis_c(option = "magma")

grid.arrange(z1, z2, z3, z4, ncol=2)

\[ \cdot\cdot\cdot \]

Exercício 3

data("iris")

Informações sobre o conjunto de dados clicando aqui.

Dados

kable(head(iris, 5), col.names = c("Comp. Sépala","Larg. Sépala","Comp. Pétala","Larg. Pétala", "Espécies")) %>% 
    kable_styling(full_width = FALSE,bootstrap_options = c("striped", "hover", "condensed", "responsive"))
Comp. Sépala Larg. Sépala Comp. Pétala Larg. Pétala Espécies
5.1 3.5 1.4 0.2 setosa
4.9 3.0 1.4 0.2 setosa
4.7 3.2 1.3 0.2 setosa
4.6 3.1 1.5 0.2 setosa
5.0 3.6 1.4 0.2 setosa
Comprimento e Largura medidos em centímetros.

\[ \cdot\cdot\cdot \]

G-1

i4 <- ggplot(iris) +
    geom_histogram(aes(x = Sepal.Length,
                       y = ..density..),
                   bins = 15,
                   fill = "orange",
                   color = "dark orange",
                   alpha = 0.35) +
        labs(x = "Comprimento da Sépala",
             y = "f(x)",
             title = "Flor Iris") +
    geom_density(aes(x = Sepal.Length),
                 linetype = "dashed",
                 color = "dark orange") +
    geom_vline(aes(xintercept = mean(Sepal.Length)),
               color = "dark orange",
               linetype = "dashed",
               size = 1.25) +
    geom_vline(aes(xintercept = median(Sepal.Length)),
               color = "black",
               size = 1.0)    
i4

\[ \cdot\cdot\cdot \]

G-2

i3 <- ggplot(iris) +
    geom_histogram(aes(x = Sepal.Width,
                       y = ..density..),
                   bins = 15,
                   fill = "light green",
                   color = "dark green",
                   alpha = 0.35) +
        labs(x = "Largura da Sépala",
             y = "f(x)",
             title = "Flor Iris") +
    geom_density(aes(x = Sepal.Width),
                 linetype = "dashed",
                 color = "dark green") +
    geom_vline(aes(xintercept = mean(Sepal.Width)),
               color = "dark green",
               linetype = "dashed",
               size = 1.25) +
    geom_vline(aes(xintercept = median(Sepal.Width)),
               color = "black",
               size = 1.0)    
i3

\[ \cdot\cdot\cdot \]

G-3

i2 <- ggplot(iris) +
    geom_histogram(aes(x = Petal.Length,
                       y = ..density..),
                   bins = 15,
                   fill = "pink",
                   color = "red",
                   alpha = 0.35) +
        labs(x = "Comprimento da Pétala",
             y = "f(x)",
             title = "Flor Iris") +
    geom_density(aes(x = Petal.Length),
                 linetype = "dashed",
                 color = "red") +
    geom_vline(aes(xintercept = mean(Petal.Length)),
               color = "red",
               linetype = "dashed",
               size = 1.25) +
    geom_vline(aes(xintercept = median(Petal.Length)),
               color = "black",
               size = 1.0)    
i2

\[ \cdot\cdot\cdot \]

G-4

i1 <- ggplot(iris) +
    geom_histogram(aes(x = Petal.Width,
                       y = ..density..),
                   bins = 15,
                   fill = "Sky Blue",
                   color = "blue",
                   alpha = 0.35) +
        labs(x = "Largura da Pétala",
             y = "f(x)",
             title = "Flor Iris") +
    geom_density(aes(x = Petal.Width),
                 linetype = "dashed",
                 color = "blue") +
    geom_vline(aes(xintercept = mean(Petal.Width)),
               color = "blue",
               linetype = "dashed",
               size = 1.25) +
    geom_vline(aes(xintercept = median(Petal.Width)),
               color = "black",
               size = 1.0)    
i1

\[ \cdot\cdot\cdot \]

Visão Geral Boxplot

Para uma melhor visão deixei o código desabilitado, pois o código é análogo ao exercício 1.

\[ \cdot\cdot\cdot \]

Visão Geral Hist.

grid.arrange(i1, i2, i3, i4, ncol=2)

Visão Geral Acumulada

  • FDA - Função de Distribuição Acumulada

Nesse caso um olhar na Função de Distribuição Acumulada, pode descrever melhor os dados do que apenas olhar para a Distribuição Empírica das Amostras através do Histograma1.

\[ \cdot\cdot\cdot \]

Exercício 4

Matriz Correlação

Vamos plotar uma matriz de correlação de Pearson entre as variáveis do banco de dados, e escolher a maior correlação para realizarmos o gráfico de dispersão, assim como fizemos anteriormente.

iris_mdf <- select(iris, Sepal.Length, Sepal.Width, Petal.Length, Petal.Width)
var(iris_mdf) %>%
    kbl() %>%
        kable_classic_2(full_width = F)
Sepal.Length Sepal.Width Petal.Length Petal.Width
Sepal.Length 0.6856935 -0.0424340 1.2743154 0.5162707
Sepal.Width -0.0424340 0.1899794 -0.3296564 -0.1216394
Petal.Length 1.2743154 -0.3296564 3.1162779 1.2956094
Petal.Width 0.5162707 -0.1216394 1.2956094 0.5810063

A matriz apresentada acima é chamada de matriz de variâncias e co-variâncias. Na diagonal da matriz temos as variâncias de cada uma das variáveis. A variância de comprimento da sépala é 0,6857 cm², da largura é 0,1899cm².

col1 <- colorRampPalette(c("#FC4E07", "orange", "gray", "#00AFBB", "purple"))

corrplot(cor(iris_mdf), method = "number", type = "lower", tl.col = "black", tl.srt = 45, diag = F, col = col1(100))

O coeficiente de determinação R² é o resultado da correlação entre as variáveis elevado ao quadrado.

r2_iris <- (cor(iris$Petal.Length, iris$Petal.Width)^2) * 100
r2_iris
## [1] 92.71098

Obtemos como resultado de , o valor de 92.7109839%.

\[ \cdot\cdot\cdot \]

Gráfico de Dispersão

As variáveis que apresentaram maior correlação entre si, foram Comprimento da Pétala e Largura da Pétala. Vamos ver o gráfico de dispersão entre elas.

di1 <- ggplot(iris, aes(x = Petal.Width,
                        y = Petal.Length,
                        color = Species)) + 
        geom_point() +
        stat_ellipse(level = 0.95) +
        geom_smooth(method = "lm",
                color = "black",
                alpha = 0.55,
                fill = "light gray") +
    labs(title = "Gráfico de dispersão entre Comprimento e Largura da Pétala",
         x = "Largura da Pétala",
         y = "Comprimento da Pétala")
di1

cor.test(iris$Petal.Length, iris$Petal.Width)
## 
##  Pearson's product-moment correlation
## 
## data:  iris$Petal.Length and iris$Petal.Width
## t = 43.387, df = 148, p-value < 2.2e-16
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  0.9490525 0.9729853
## sample estimates:
##       cor 
## 0.9628654

Observe que o Coeficiente de Correlação de Pearson retornou o valor 0.9628654 o que evidencia uma forte relação linear entre as variáveis em estudo. Para avaliar se esse resultado é significativo, pode-se realizar um Teste de Hipóteses para a o Coeficiente de Correlação (supondo que as suposições do teste sejam satisfeitas):
Como o Valor P do teste (p-value < 2.2e-16) é bem pequeno, conclui-se que o valor do Coeficiente de Correlação Linear de Pearson tem significância Estatística.

Além disso podemos ver que as amostras para cada espécie da flor são iguais.

iris %>% 
    tabyl(Species) %>% 
    adorn_pct_formatting() %>% 
    knitr::kable(col.names = c("Espécies","Observações","Porcentagem")) %>% 
    kable_styling(full_width = FALSE,bootstrap_options = c("striped", "hover", "condensed", "responsive"))
Espécies Observações Porcentagem
setosa 50 33.3%
versicolor 50 33.3%
virginica 50 33.3%

\[ \cdot\cdot\cdot \]

Exercício 5

data("mpg")

Informações sobre o conjunto de dados clicando aqui.

kable(head(mpg, 10), col.names = c("Marca","Modelo","Cilindradas","Ano", "N Cil.", "Transm.", "Tração", "Cidade*", "Estrada*", "Combustível", "Tipo")) %>% 
    kable_styling(full_width = FALSE,bootstrap_options = c("striped", "hover", "condensed", "responsive"))
Marca Modelo Cilindradas Ano N Cil. Transm. Tração Cidade* Estrada* Combustível Tipo
audi a4 1.8 1999 4 auto(l5) f 18 29 p compact
audi a4 1.8 1999 4 manual(m5) f 21 29 p compact
audi a4 2.0 2008 4 manual(m6) f 20 31 p compact
audi a4 2.0 2008 4 auto(av) f 21 30 p compact
audi a4 2.8 1999 6 auto(l5) f 16 26 p compact
audi a4 2.8 1999 6 manual(m5) f 18 26 p compact
audi a4 3.1 2008 6 auto(av) f 18 27 p compact
audi a4 quattro 1.8 1999 4 manual(m5) 4 18 26 p compact
audi a4 quattro 1.8 1999 4 auto(l5) 4 16 25 p compact
audi a4 quattro 2.0 2008 4 manual(m6) 4 20 28 p compact
(*): Milhas por Galão


glimpse(mpg)
## Rows: 234
## Columns: 11
## $ manufacturer <chr> "audi", "audi", "audi", "audi", "audi", "audi", "audi"...
## $ model        <chr> "a4", "a4", "a4", "a4", "a4", "a4", "a4", "a4 quattro"...
## $ displ        <dbl> 1.8, 1.8, 2.0, 2.0, 2.8, 2.8, 3.1, 1.8, 1.8, 2.0, 2.0,...
## $ year         <int> 1999, 1999, 2008, 2008, 1999, 1999, 2008, 1999, 1999, ...
## $ cyl          <int> 4, 4, 4, 4, 6, 6, 6, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 8, ...
## $ trans        <chr> "auto(l5)", "manual(m5)", "manual(m6)", "auto(av)", "a...
## $ drv          <chr> "f", "f", "f", "f", "f", "f", "f", "4", "4", "4", "4",...
## $ cty          <int> 18, 21, 20, 21, 16, 18, 18, 18, 16, 20, 19, 15, 17, 17...
## $ hwy          <int> 29, 29, 31, 30, 26, 26, 27, 26, 25, 28, 27, 25, 25, 25...
## $ fl           <chr> "p", "p", "p", "p", "p", "p", "p", "p", "p", "p", "p",...
## $ class        <chr> "compact", "compact", "compact", "compact", "compact",...

\[ \cdot\cdot\cdot \]

Exercício 6

e1 <- ggplot(mpg, aes(x = cyl,
                      y = hwy,
                      color = drv)) + 
        geom_point() +
        geom_smooth(method = "lm",
                color = "black",
                alpha = 0.55,
                fill = "light gray") +
        labs(title = "Gráfico de dispersão",
            x = "N° de Clíndros",
            y = "Milhas/Galão na Estrada",
            color = "Tração")
e1

tração: f=frontal, r=traseira, 4=4x4


Há um decréscimo no valor médio de milhas percorridas na estrada à medida que cresce o número de cilíndros no motor. Portanto, em média, carros com maior número de cilíndros no motor tendem a ser menos econômicos, apesar de existirem muitos carros com performance similar, independentemente do número de cilíndros no motor. Quando separamos os dados por tração, podemos perceber uma tendência de maior economia em carros de tração dianteira/frontal.

cor.test(mpg$cyl, mpg$hwy)
## 
##  Pearson's product-moment correlation
## 
## data:  mpg$cyl and mpg$hwy
## t = -17.918, df = 232, p-value < 2.2e-16
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  -0.8109214 -0.7022885
## sample estimates:
##        cor 
## -0.7619124

\[ \cdot\cdot\cdot \]

Exercício 7

Gráficos

\[ \cdot\cdot\cdot \]

Código

hist_cty <- ggplot(mpg) +
    geom_histogram(aes(x = cty,
                       y = ..density..),
                   bins = 9,
                   fill = "pink",
                   color = "red",
                   alpha = 0.35) +
        labs(x = "Milhas por Galão na Cidade",
             y = "f(x)",
             title = "Consumo") +
    geom_density(aes(x = cty),
                 linetype = "dashed",
                 color = "red") +
    geom_vline(aes(xintercept = mean(cty)),
               color = "red",
               linetype = "dashed",
               size = 1.25) +
    geom_vline(aes(xintercept = median(cty)),
               color = "black",
               size = 1.0)

bp_cty <- ggplot(mpg) +
    geom_boxplot(aes(x = cty),
                   fill = "pink",
                   color = "red",
                   alpha = 0.35) +
        labs(title = "Consumo",
             x = "Milhas por Galão na Cidade") +
        scale_y_discrete()

hist_hwy <- ggplot(mpg) +
    geom_histogram(aes(x = hwy,
                       y = ..density..),
                   bins = 9,
                   fill = "light green",
                   color = "dark green",
                   alpha = 0.35) +
        labs(x = "Milhas por Galão na Estrada",
             y = "f(x)",
             title = "Consumo") +
    geom_density(aes(x = hwy),
                 linetype = "dashed",
                 color = "dark green") +
    geom_vline(aes(xintercept = mean(hwy)),
               color = "dark green",
               linetype = "dashed",
               size = 1.25) +
    geom_vline(aes(xintercept = median(hwy)),
               color = "black",
               size = 1.0)

bp_hwy <- ggplot(mpg) +
    geom_boxplot(aes(x = hwy),
                   fill = "light green",
                   color = "dark green",
                   alpha = 0.35) +
        labs(title = "Consumo",
             x = "Milhas por Galão na Estrada") +
        scale_y_discrete()

grid.arrange(hist_cty, bp_cty, hist_hwy, bp_hwy, ncol=2)

\[ \cdot\cdot\cdot \]

Exercício 8

8.1

d_mpg1 <- ggplot(mpg, aes(x = displ,
                      y = hwy,
                      color = class)) + 
        geom_point() +
        labs(title = "Gráficos de dispersão Separados por Tipo de Carro",
            x = "Cilindradas",
            y = "Milhas/Galão na Estrada",
            color = "Tipo de Carro") +
        facet_wrap(~ class, nrow = 2)
d_mpg1

\[ \cdot\cdot\cdot \]

8.2

d_mpg2 <- ggplot(mpg, aes(x = displ,
                      y = hwy,
                      color = class)) + 
        geom_point() +
        labs(title = "Gráficos de dispersão Separados por Tipo de Carro, Tração, n° de Cilindros",
            x = "Cilindradas",
            y = "Milhas/Galão na Estrada",
            color = "Tipo de Carro") +
        facet_grid(drv ~ cyl)
d_mpg2

\[ \cdot\cdot\cdot \]

8.3

d_mpg3 <- ggplot(mpg, aes(x = displ,
                      y = hwy,
                      color = as.factor(cyl))) + 
        geom_point() +
        labs(title = "Gráficos de dispersão Separados por n° de Cilindros",
            x = "Cilindradas",
            y = "Milhas/Galão na Estrada",
            color = "nº de Cilindros") +
        facet_grid(. ~ cyl)
d_mpg3

\[ \cdot\cdot\cdot \]

Exercício 9 - Desafio

homework2 <- read_excel("homework2.xlsx")
hw2_c <- homework2 %>% 
    mutate_at(c("HDI", "CPI"), as.numeric)
hw2_c$Region <- factor(hw2_c$Region,
                     levels = c("EU W. Europe",
                                "Americas",
                                "Asia Pacific",
                                "East EU Cemt Asia",
                                "MENA",
                                "SSA"),
                     labels = c("OECD",
                                "Americas",
                                "Asia &\nOceania",
                                "Central &\nEastern Europe",
                                "Middle East &\nnorth Africa",
                                "Sub-Saharan\nAfrica"))

Podemos extrair de informação dos dados que há uma predominância dos países africanos nas últimas posições do ranking de IDH, sendo o último o Congo.

dt_hw2_mdf <- arrange(hw2_c, desc(HDI_Rank))
head(dt_hw2_mdf, 10)
## # A tibble: 10 x 5
##    Country                  HDI_Rank   HDI   CPI Region               
##    <chr>                       <dbl> <dbl> <dbl> <fct>                
##  1 Congo                         187 0.286   2   "Sub-Saharan\nAfrica"
##  2 Niger                         186 0.295   2.5 "Sub-Saharan\nAfrica"
##  3 Burundi                       185 0.316   1.9 "Sub-Saharan\nAfrica"
##  4 Mozambique                    184 0.322   2.7 "Sub-Saharan\nAfrica"
##  5 Chad                          183 0.328   2   "Sub-Saharan\nAfrica"
##  6 Liberia                       182 0.329   3.2 "Sub-Saharan\nAfrica"
##  7 Burkina Faso                  181 0.331   3   "Sub-Saharan\nAfrica"
##  8 Sierra Leone                  180 0.336   2.5 "Sub-Saharan\nAfrica"
##  9 Central African Republic      179 0.343   2.2 "Sub-Saharan\nAfrica"
## 10 Guinea                        178 0.344   2.1 "Sub-Saharan\nAfrica"

Enquanto na liderança do ranking está a Noruega.

tail(dt_hw2_mdf, 10)
## # A tibble: 10 x 5
##    Country       HDI_Rank   HDI   CPI Region           
##    <chr>            <dbl> <dbl> <dbl> <fct>            
##  1 Switzerland         11 0.903   8.8 "OECD"           
##  2 Sweden              10 0.904   9.3 "OECD"           
##  3 Germany              9 0.905   8   "OECD"           
##  4 Ireland              7 0.908   7.5 "OECD"           
##  5 Canada               6 0.908   8.7 "Americas"       
##  6 New Zealand          5 0.908   9.5 "Asia &\nOceania"
##  7 United States        4 0.91    7.1 "Americas"       
##  8 Netherlands          3 0.91    8.9 "OECD"           
##  9 Australia            2 0.929   8.8 "Asia &\nOceania"
## 10 Norway               1 0.943   9   "OECD"
disp_hw <- ggplot(hw2_c, aes(x = CPI,
                      y = HDI,
                      color = Region,
                      size = HDI)) + 
        geom_point(shape = 1, stroke = 1.25) +
        labs(title = "Scatter Plot",
            x = "CPI (escala log 10)",
            y = "HDI") +
        scale_x_log10()
disp_hw

  • Tentando deixar o gráfico o mais próximo possível da revista
h1 <- ggplot(hw2_c, aes(x = CPI, y = HDI, color = Region)) +
    geom_point(shape = 1, size = 2.75, stroke = 1.25) +
    geom_smooth(aes(fill = "red"),
                se = F, method ="lm", formula = (y ~ log(x)), color = "red") +
            labs(title = "Corruption and human development") +
    scale_x_continuous(expand = c(0, 0),
                        limits=c(1,10.2),
                        breaks=seq(1,10,1), 
                        name = "Corruption Perception Index (10=Least corrupt)") +
    scale_y_continuous(expand = c(0, 0),
                     limits=c(0.2,1),
                     breaks=seq(0.2,1,0.1), 
                     name = "Human Development Index,2011 (1=best)") +
    theme_economist_white(base_size = 9, base_family = "Verdana", gray_bg = F) +
    scale_colour_economist() +
    scale_fill_manual(name='', values=c("red"),labels=c("R² = 56%")) +
    guides(col = guide_legend(nrow = 2))
h1

Coeficiente de correlação de Pearson:

cor(hw2_c$HDI, hw2_c$CPI)
## [1] 0.7048705
cor.test(hw2_c$HDI, hw2_c$CPI)
## 
##  Pearson's product-moment correlation
## 
## data:  hw2_c$HDI and hw2_c$CPI
## t = 12.994, df = 171, p-value < 2.2e-16
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  0.6209764 0.7727980
## sample estimates:
##       cor 
## 0.7048705

Porém, podemos notar pelo gráfico que não existe uma relação linear entre as variáveis estudadas. Talvez seja melhor utilizarmos um outro método estatístico para estudar a correlação entre as variáveis.

  • Coeficiente de correlação de Spearman
cor(hw2_c$HDI, hw2_c$CPI, method = "spearman")
## [1] 0.7460613

Enquanto a correlação de Pearson avalia relações lineares, a correlação de Spearman avalia relações monótonas, sejam elas lineares ou não. Mais informações aqui.

cor(hw2_c$HDI, hw2_c$CPI, method = "spearman")^2
## [1] 0.5566074

Provavelmente esse foi o valor (arredondado para 56%) utilizado pela matéria do The Economist.

\[ \star \]




  1. Post no Blog ANDATA sobre Empirical Cumulative Distribution Function (CDF).↩︎