Prof. Walmes M. Zeviani
walmes@ufpr.br
11 de Abril de 2018
Justificativa
Objetivo
Uma imagem vale mais que mil palavras.
– Provérbio inglês
Os gráficos
Gráficos são usados para
Figura 1: Balança comercial da Inglaterra no período de 1700 a 1780 representada em um gráfico de linhas por William Playfair em 1786. FONTE.
Figura 2: Mortes por cólera em Londres em 1854 sinalizadas no mapa por John Snow para detecção da fonte de contaminação. FONTE.
Figura 3: Mapa de intensidade sobre as localização das mortes por cólera. FONTE.
Com relação tipo de valor das variáveis:
Com relação a quantidade de variáveis representadas:
| Análise exploratória | Análise explanatória |
|---|---|
| Explorar os dados, ganhar intimidade | Comunicar resultados das análises |
| Geram perguntas | Geram respostas |
| Permitem criar e refinar de hipóteses | Permitem confirmar hipóteses |
| É para consumo do cientista | É para consumo de interessados/apoiadores |
| É um processo exaustivo: muitos gráficos são criados | Apenas os gráficos principais são exibidos |
| Muitos gráficos: conteúdo redundante e conto prolixo | Gráficos essenciais: enxutos, claros e conto conciso |
| Sem preocupação com design e acabamento | Design e acabamento são importantíssimos |
| Selecionar variáveis, compreender tamanho de efeito, eliminar outliers | Orientar o desenvolvimento das pesquisas, novas hipóteses |
| Auxiliar a especificar o modelo, avaliar suposições, corrigir problemas | Estimular a compreensão e ação: tomada de decisão |
| Geralmente estáticos | Podem ser reativos |
Os dados estão diponíveis em http://leg.ufpr.br/~walmes/data/coberturas-venda-cwb-26Jan2018.txt.
imo# A tibble: 2,634 x 10
ID price condo area rooms suites bathroom garages lon lat
<int> <dbl> <int> <int> <int> <int> <int> <int> <dbl> <dbl>
1 90268387 850000. 700 168 3 1 3 2 -49.3 -25.5
2 90527117 700000. NA 211 3 1 3 2 NA NA
3 91838838 990000. 1070 160 3 1 3 2 -49.3 -25.5
4 89468394 640000. 650 160 3 1 3 2 -49.3 -25.5
5 90406373 492000. NA 90 3 2 3 2 -49.3 -25.5
6 85238799 500000. NA 128 3 1 2 2 -49.3 -25.5
7 88240205 790000. 730 177 3 1 NA 2 -49.3 -25.5
8 90752637 328000. 400 84 3 1 2 2 -49.4 -25.5
9 91606048 1090000. 700 192 3 2 5 2 -49.3 -25.4
10 75942786 790000. 460 202 3 1 3 2 NA NA
# ... with 2,624 more rows
Figura 1: Printscreen no navegador de internet em uma canção do Chico Buarque exibindo o código fonte da página. FONTE: o autor.
Figura 2: Printscreen no navegador de internet em um site de anúncio de imóveis para venda e locação exibindo o código fonte da página. FONTE.
O web scraping tém várias questões éticas. Algumas são:
* Derrumar um site com inúmeras requisições: sites governamentais.
* Extrair nomes de pessoas mencionadas em processos judiciais: *black
list*.
* Comercializar informações coletadas e mantidas por outros: preço
dos imóveis, de veículos.
A tabela de frequência para o número de banheiros é obtida a seguir.
tb <- imo %>% count(bathroom)
tb <- tb %>% mutate(freq_rel = 100 * n/sum(n))
tb <- tb %>% rename("freq_abs" = n)
tb# A tibble: 12 x 3
bathroom freq_abs freq_rel
<int> <int> <dbl>
1 1 145 5.50
2 2 522 19.8
3 3 725 27.5
4 4 461 17.5
5 5 311 11.8
6 6 158 6.00
7 7 47 1.78
8 8 16 0.607
9 9 1 0.0380
10 10 1 0.0380
11 11 1 0.0380
12 NA 246 9.34
Perguntas
ggplot(data = imo,
mapping = aes(x = bathroom,
fill = I(mycol[1]),
colour = I("black"))) +
geom_bar()mn <- mean(imo$bathroom, na.rm = TRUE)
md <- median(imo$bathroom, na.rm = TRUE)
p1 <- ggplot(data = imo,
mapping = aes(x = bathroom,
fill = I(mycol[1]),
colour = I("black"))) +
geom_bar() +
geom_vline(xintercept = mn, color = mycol[2]) +
geom_vline(xintercept = md, color = mycol[5])
p2 <- ggplot(data = imo,
mapping = aes(x = bathroom,
colour = I(mycol[1]))) +
geom_step(stat = "ecdf") +
geom_vline(xintercept = mn, color = mycol[2]) +
geom_vline(xintercept = md, color = mycol[5]) +
ylab("Frequência relativa acumulada")
gridExtra::grid.arrange(p1, p2, ncol = 1)ggplot(data = imo,
mapping = aes(x = garages,
fill = I(mycol[1]),
color = I("black"))) +
geom_bar()ggplot(data = imo,
mapping = aes(x = suites,
fill = I(mycol[1]),
color = I("black"))) +
geom_bar()ggplot(data = imo,
mapping = aes(x = rooms,
fill = I(mycol[1]),
color = I("black"))) +
geom_bar()Perguntas
p1 <- ggplot(data = imo,
mapping = aes(x = area,
fill = I(mycol[2]),
color = I(mycol[2]))) +
geom_histogram(mapping = aes(color = I("black"))) +
geom_rug()
p2 <- ggplot(data = imo,
mapping = aes(x = area,
colour = I(mycol[2]))) +
geom_step(stat = "ecdf") +
ylab("Frequência relativa acumulada") +
geom_rug()
gridExtra::grid.arrange(p1, p2, ncol = 1)p1 <- ggplot(data = imo,
mapping = aes(x = price/1000,
fill = I(mycol[4]),
color = I(mycol[4]))) +
geom_histogram(mapping = aes(color = I("black"))) +
geom_rug()
p2 <- ggplot(data = imo,
mapping = aes(x = price/1000,
color = I(mycol[4]))) +
geom_step(stat = "ecdf") +
geom_rug()
gridExtra::grid.arrange(p1, p2, ncol = 1)ggplot(data = imo,
mapping = aes(x = price/1000,
fill = I(mycol[5]),
color = I(mycol[5]))) +
geom_histogram(mapping = aes(color = I("black"))) +
scale_x_log10() +
geom_rug()p1 <- ggplot(data = imo,
mapping = aes(x = price/1000,
color = I(mycol[4]))) +
geom_histogram(mapping = aes(y = ..density..,
fill = I(mycol[4]))) +
geom_density(mapping = aes(color = I("black"))) +
scale_x_log10() +
geom_rug()
p2 <- ggplot(data = imo,
mapping = aes(x = price/1000,
color = I(mycol[4]))) +
geom_step(stat = "ecdf") +
scale_x_log10() +
geom_rug()
gridExtra::grid.arrange(p1, p2, ncol = 1)p1 <- ggplot(data = imo,
mapping = aes(x = price/1000,
color = I(mycol[4]))) +
geom_histogram(mapping = aes(y = ..density..,
fill = I(mycol[4]))) +
geom_density(mapping = aes(color = I("black"))) +
scale_x_log10() +
geom_rug()
p2 <- ggplot(data = imo,
mapping = aes(x = price/1000,
color = I(mycol[4]))) +
geom_step(stat = "ecdf") +
scale_x_log10() +
geom_rug()
gridExtra::grid.arrange(p1, p2, ncol = 1)ggplot(data = imo,
mapping = aes(x = area,
y = price/1000,
color = I(mycol[1]))) +
geom_point(alpha = 0.25)ggplot(data = imo,
mapping = aes(x = area,
y = price/1000)) +
geom_hex(alpha = 1, bins = 50) +
scale_fill_gradient(low = mycol[4], high = mycol[1])ggplot(data = imo,
mapping = aes(x = area,
y = price/1000,
color = I(mycol[1]))) +
geom_point() +
scale_x_log10() +
scale_y_log10()ggplot(data = imo,
mapping = aes(x = area,
y = price/1000,
color = I(mycol[1]))) +
geom_point(alpha = 0.5) +
geom_smooth(color = mycol[2]) +
geom_rug() +
scale_x_log10() +
scale_y_log10()Dados da prova de Triathlon Audencia La Baule extraidos do site http://www.ipitos.com/ em 15/09/2013 quando estavam disponíveis pelo link http://www.ipitos.com/de-resultats/course-295-page-1-orderby-sortCrit-ASC.
Os dados contém o nome, gênero e tempo para completar as etapas de natação, ciclismo e corrida dos atletas na maratona. O arquivo com os dados está acessível pelo link http://leg.ufpr.br/~walmes/data/triathlon.txt.
tri# A tibble: 9,358 x 9
nome categ sexo edicao ano tnadar tpedalar tcorrer ttotal
<chr> <chr> <chr> <chr> <int> <dbl> <dbl> <dbl> <dbl>
1 RIEDERER SVEN S2M M course-108 2009 10.6 18.7 37.7 32.8
2 GOMEZ NOYA JAVIER S2M M course-108 2009 24.8 67.2 72.7 83.0
3 BROWNLEE ALISTAIR U23 M course-108 2009 14.4 12.4 46.6 13.4
4 MOULAI TONY S3M M course-108 2009 50.8 36.1 157. 43.0
5 ZIPF JONATHAN U23 M course-108 2009 10.3 18.8 36.3 26.7
6 BROWNLEE JONATHAN U23 M course-108 2009 25.0 67.3 73.4 83.0
7 JUSTUS STEFFEN S2M M course-108 2009 14.4 12.7 47.3 14.5
8 BELAUBRE FREDERIC S2M M course-108 2009 50.8 36.8 157. 40.6
9 OSPALY FILIP S3M M course-108 2009 10.3 17.8 35.3 28.0
10 VIDAL LAURENT S2M M course-108 2009 25.2 67.3 75.3 83.1
# ... with 9,348 more rows
ggplot(data = tri,
mapping = aes(x = ano)) +
geom_bar(fill = mycol[3])
ggplot(data = tri,
mapping = aes(x = sexo)) +
geom_bar(fill = mycol[4])
ggplot(data = tri,
mapping = aes(x = categ)) +
geom_bar() +
coord_flip()Gráfico de barras empilhadas
ggplot(data = tri,
mapping = aes(x = ano, fill = sexo)) +
geom_bar(position = "stack", color = I("black")) +
scale_fill_manual(values = mycol[2:1])Gráfico de barras lado a lado
ggplot(data = tri,
mapping = aes(x = ano, fill = sexo)) +
geom_bar(position = "dodge", color = I("black")) +
scale_fill_manual(values = mycol[2:1])Gráfico de barras empilhadas relativa
ggplot(data = tri,
mapping = aes(x = ano, fill = sexo)) +
geom_bar(position = "fill", color = I("black")) +
scale_fill_manual(values = mycol[2:1])Gráfico de barras estilo mosaico
xt <- xtabs(~ano + sexo, data = tri)
mosaicplot(xt, col = mycol[2:1], main = NULL)ggplot(data = tri,
mapping = aes(x = ttotal, color = sexo, fill = sexo)) +
geom_density(alpha = 0.15) +
scale_fill_manual(values = mycol[2:1]) +
scale_colour_manual(values = mycol[2:1]) +
geom_rug()ggplot(data = tri,
mapping = aes(x = ttotal, color = sexo, fill = sexo)) +
geom_density(alpha = 0.15) +
scale_fill_manual(values = mycol[2:1]) +
scale_colour_manual(values = mycol[2:1]) +
geom_rug()p1 <- ggplot(data = tri,
mapping = aes(x = ttotal, color = sexo, fill = sexo)) +
geom_density(alpha = 0.15) +
scale_fill_manual(values = mycol[2:1]) +
scale_colour_manual(values = mycol[2:1]) +
scale_x_continuous(limits = c(0, 150)) +
geom_rug()
p2 <- ggplot(data = tri,
mapping = aes(x = ttotal, color = sexo, fill = sexo)) +
geom_step(stat = "ecdf") +
scale_colour_manual(values = mycol[2:1]) +
scale_x_continuous(limits = c(0, 150)) +
geom_rug()
gridExtra::grid.arrange(p1, p2, ncol = 1)tril <-
tri %>%
filter(ttotal < 150) %>%
gather(key = "atividade",
value = "tempo",
tnadar,
tcorrer,
tpedalar)
# str(tril)
p1 <- ggplot(data = tril,
mapping = aes(x = tempo, color = atividade)) +
geom_density(alpha = 0.15) +
scale_x_continuous(limits = c(0, 250)) +
geom_rug()
p2 <- ggplot(data = tril,
mapping = aes(x = tempo, color = atividade)) +
geom_step(stat = "ecdf") +
scale_x_continuous(limits = c(0, 250)) +
geom_rug()
gridExtra::grid.arrange(p1, p2, ncol = 1)tri <-
tri %>%
mutate(ttotal = tnadar + tpedalar + tcorrer,
pnadar = tnadar/ttotal,
ppedalar = tpedalar/ttotal,
pcorrer = tcorrer/ttotal)
library(plotrix)
par(mfrow = c(1, 2))
triax.plot(x = with(subset(tri, sexo == "F"),
na.omit(cbind(pnadar, ppedalar, pcorrer))),
main = "F",
col.symbols = mycol[2])
triax.plot(x = with(subset(tri, sexo == "M"),
na.omit(cbind(pnadar, ppedalar, pcorrer))),
main = "M",
col.symbols = mycol[1])layout(1)pla# A tibble: 1,528 x 17
country team name pos age cm kg apps goal ass yel red spg ps
<chr> <chr> <chr> <chr> <int> <int> <int> <chr> <int> <int> <int> <int> <dbl> <dbl>
1 Austria Salzb… Sadi… M(L) 21 175 69 9 4 3 1 1 2.00 77.0
2 Austria Salzb… Kevi… M(R) 23 180 63 9 2 4 2 NA 2.00 83.9
3 Austria Salzb… Alan FW 24 182 73 8(1) 4 2 NA 1 4.20 60.8
4 Austria Salzb… Andr… D(C) 22 182 77 9 1 NA 4 NA 0.900 72.3
5 Austria Salzb… Stef… M 23 180 71 1(1) NA NA NA NA 0.500 86.3
6 Austria Salzb… Chri… M(C) 28 172 69 7(1) NA 1 3 NA 1.60 79.4
7 Austria Salzb… Jona… FW 28 180 71 7 8 1 1 NA 4.10 72.8
8 Austria Salzb… Stef… M(C) 24 186 74 8(1) NA NA 1 NA 0.800 74.7
9 Austria Salzb… Mart… D(C) 21 184 78 8(1) NA NA 3 NA 1.10 69.1
10 Austria Salzb… Andr… D(L) 28 175 69 8 NA NA NA NA 0.900 64.5
# ... with 1,518 more rows, and 3 more variables: aw <dbl>, mom <int>, rt <dbl>
ggplot(data = pla,
mapping = aes(x = country)) +
geom_bar() +
coord_flip()ggplot(data = pla,
mapping = aes(x = reorder(country, country, length))) +
geom_bar() +
coord_flip()ggplot(data = pla,
mapping = aes(x = age)) +
geom_bar(fill = mycol[1])
ggplot(data = pla,
mapping = aes(x = cm)) +
geom_density(color = mycol[2], fill = mycol[2], alpha = 0.25)
ggplot(data = pla,
mapping = aes(x = kg)) +
geom_density(color = mycol[4], fill = mycol[4], alpha = 0.25)
ggplot(data = pla,
mapping = aes(x = cm,
y = kg)) +
geom_point(alpha = 0.15) +
geom_smooth(color = mycol[2])
ggplot(data = pla,
mapping = aes(x = cm,
y = kg)) +
geom_jitter() +
geom_smooth(color = mycol[2])
ggplot(data = pla,
mapping = aes(x = cm,
y = kg)) +
geom_hex(alpha = 1, bins = 40) +
scale_fill_gradient(low = mycol[2], high = "black")
ggplot(data = pla,
mapping = aes(x = age,
y = cm)) +
geom_point() +
geom_jitter() +
geom_smooth(color = mycol[2])ggplot(data = pla,
mapping = aes(x = country, y = cm)) +
geom_boxplot()ggplot(data = pla,
mapping = aes(x = reorder(country,
cm,
median,
na.rm = TRUE),
y = cm)) +
geom_boxplot() +
coord_flip()pla <- pla %>%
mutate(posit = gsub("^([A-Z]+).*$", "\\1", pos))
# table(pla$posit)
p1 <- ggplot(data = pla,
mapping = aes(x = reorder(posit, cm, median, na.rm = TRUE),
y = cm)) +
geom_boxplot()
p2 <- ggplot(data = pla,
mapping = aes(x = reorder(posit, kg, median, na.rm = TRUE),
y = kg)) +
geom_boxplot()
gridExtra::grid.arrange(p1, p2, ncol = 1)ggplot(data = pla,
mapping = aes(x = cm,
y = kg,
color = posit)) +
geom_point() +
geom_jitter()ggplot(data = pla,
mapping = aes(x = cm,
y = kg)) +
geom_point() +
geom_smooth() +
facet_wrap(facets = ~posit)Figura 1: Printscreen no navegador de internet no site http://www.carrosnaweb.com.br/ destacando os tipos de dados contidos em cada avaliação.
not# A tibble: 124,980 x 4
carro dono item nota
<chr> <int> <chr> <int>
1 gol 1 Estilo 8
2 gol 1 Acabamento 7
3 gol 1 Posição de dirigir 9
4 gol 1 Instrumentos 8
5 gol 1 Interior 7
6 gol 1 Porta-malas 7
7 gol 1 Desempenho 9
8 gol 1 Motor 9
9 gol 1 Câmbio 10
10 gol 1 Freios 7
# ... with 124,970 more rows
ggplot(not,
mapping = aes(x = item, y = nota, colour = item)) +
geom_point(alpha = 0.05) +
geom_jitter() +
stat_summary(aes(group = 1),
fun.y = mean,
colour = "black",
geom = "line",
group = 1) +
facet_wrap(facets = ~carro) +
coord_flip()notm <-
not %>%
group_by(carro, item) %>%
summarize(nota = mean(nota))
notm# A tibble: 510 x 3
# Groups: carro [?]
carro item nota
<chr> <chr> <dbl>
1 agile Acabamento 6.36
2 agile Câmbio 6.56
3 agile Consumo 6.42
4 agile Custo-Benefício 6.34
5 agile Desempenho 6.70
6 agile Estabilidade 7.25
7 agile Estilo 8.42
8 agile Freios 6.59
9 agile Instrumentos 8.33
10 agile Interior 8.39
# ... with 500 more rows
ggplot(filter(not, item == "Recomendação"),
mapping = aes(x = nota)) +
geom_bar() +
geom_vline(data = filter(notm, item == "Recomendação"),
mapping = aes(xintercept = nota, group = carro),
colour = mycol[2]) +
facet_wrap(facets = ~carro,
scales = "free_y")ggplot(notm,
mapping = aes(x = carro, y = nota, color = item)) +
geom_point()ggplot(notm,
mapping = aes(x = carro, y = nota, color = item, group = item)) +
geom_line()ggplot(notm,
mapping = aes(x = carro, y = nota)) +
geom_line(mapping = aes(group = 1)) +
facet_wrap(facets = ~item)ggplot(notm,
mapping = aes(x = item, y = nota)) +
geom_line(mapping = aes(group = 1)) +
facet_wrap(facets = ~carro)dts <- filter(notm,
carro %in% c("crossfox", "ecosport"))
dts# A tibble: 30 x 3
# Groups: carro [2]
carro item nota
<chr> <chr> <dbl>
1 crossfox Acabamento 6.80
2 crossfox Câmbio 8.70
3 crossfox Consumo 6.44
4 crossfox Custo-Benefício 7.02
5 crossfox Desempenho 8.52
6 crossfox Estabilidade 7.79
7 crossfox Estilo 8.96
8 crossfox Freios 7.92
9 crossfox Instrumentos 7.77
10 crossfox Interior 8.05
# ... with 20 more rows
ggplot(dts,
mapping = aes(x = item, y = nota)) +
geom_line(mapping = aes(color = carro, group = carro))aux <- dts %>%
spread(key = "item", value = "nota")
aux# A tibble: 2 x 16
# Groups: carro [2]
carro Acabamento Câmbio Consumo `Custo-Benefíci… Desempenho Estabilidade Estilo Freios
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 cross… 6.80 8.70 6.44 7.02 8.52 7.79 8.96 7.92
2 ecosp… 6.12 8.30 7.42 7.31 7.85 8.63 9.48 8.69
# ... with 7 more variables: Instrumentos <dbl>, Interior <dbl>, Motor <dbl>,
# `Porta-malas` <dbl>, `Posição de dirigir` <dbl>, Recomendação <dbl>, Suspensão <dbl>
m <- as.data.frame(aux[, -1])
m <- rbind(matrix(c(10, 0),
nrow = 2,
ncol = ncol(m),
dimnames = list(NULL, names(m))),
m)
library(fmsb)
radarchart(m)
legend("topright",
legend = aux$carro,
col = 1:2,
lty = 1:2,
bty = "n")ggplot(dts,
mapping = aes(x = carro,
y = nota,
group = item,
color = item)) +
geom_point() +
geom_line() +
geom_text(data = filter(dts,
carro == "ecosport"),
mapping = aes(x = 2,
y = nota,
label = item),
color = "black",
hjust = 0,
nudge_x = 0.02,
size = 3.5) +
coord_cartesian(xlim = c(1.25, 1.75)) +
guides(colour = FALSE)aux <- dts %>%
spread(key = "carro", value = "nota") %>%
mutate(diff = crossfox - ecosport) %>%
arrange(diff)
dts$item <- factor(dts$item, levels = aux$item)
dts <- dts %>% arrange(item)
ggplot(dts,
mapping = aes(x = reorder(item,
nota,
mean),
y = nota,
fill = carro)) +
geom_bar(stat = "identity",
position = "dodge",
color = I("black")) +
coord_flip()ggplot(dts,
mapping = aes(x = item,
y = nota,
fill = carro)) +
geom_bar(stat = "identity",
position = "dodge",
color = I("black")) +
coord_flip()ggplot::geom_violin().Figura 2: Exemplo de um gráfico de violino. FONTE.
beeswarm.Figura 3: Número de capulhos produzídos em função no nível de desfolha e fase de desenvolvimento de plantas de algodão. FONTE.
library(plotly)
set.seed(1234)
dat <- data.frame(cond = factor(rep(c("A", "B"), each = 200)),
rating = c(rnorm(200), rnorm(200, mean = 0.8)))
p <- ggplot(dat, aes(x = cond, y = rating)) + geom_boxplot()
p <- ggplotly(p)
popts_chunk$set(echo = FALSE)Obrigado!