### AULA, JAN 2019: GRÁFICO EM R.
### RONALDO FS ALVES
#### PARTE 1 (BÁSICO) ####
### Preliminares
x = c(2,6,8,3,10,4,1,9,6,3,9,5)
plot(x)
lines(x)
title(main = "Meu primeiro gráfico")
plot(x,
type = "p", # tipo: p pontos; l linha; b pontos e linha; etc
col = "blue", # cor do grá???co: "black" preto; "blue" azul; "red" vermelho; etc
bg = "red", # cor do fundo: mesmo que "col" [colours()]
lwd = 1, # expessura da linha: um valor numérico
pch = 21, # tipo de ponto: 19 bolinha; 20 bolinha menor; 21 círculo; 22 quadrado; 23 losango; 24 triângulo para cima; 25 triângulo para baixo
cex = 1 # fator de expansão dos símbolos: um valor numérico
) ## mais infos: help(par)
y = c(3,7,8,4,11,5,2,9,6,4,10,6)
plot(y,
type = "l",
col = "red",
lwd = 2,
main = "Título",
sub = "Subtítulo",
xlab = "eixo x",
ylab = "eixo y",
xlim = c(0,13), # dimensão o eixo x
ylim = c(0,11) # dimensão o eixo y
)
text(y)
points(x,
pch = 15,
col = "blue")
lines(x,
lwd = 2,
col = "blue")
rm(list = ls())
# Carregar bibliotecas
library(tidyverse) # ggplot2 included
## -- Attaching packages ------------------------------------------------------------------- tidyverse 1.2.1 --
## v ggplot2 3.1.0 v purrr 0.2.5
## v tibble 1.4.2 v dplyr 0.7.8
## v tidyr 0.8.2 v stringr 1.3.1
## v readr 1.3.1 v forcats 0.3.0
## -- Conflicts ---------------------------------------------------------------------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
library(corrplot)
## corrplot 0.84 loaded
library(bibliometrix)
## To cite bibliometrix in publications, please use:
##
## Aria, M. & Cuccurullo, C. (2017) bibliometrix: An R-tool for comprehensive science mapping analysis, Journal of Informetrics, 11(4), pp 959-975, Elsevier.
##
##
## http:\\www.bibliometrix.org
##
##
## To start with the shiny web-interface, please digit:
## biblioshiny()
# Importar banco de dados
df_pns = read.table(file.choose(), header = TRUE, sep = ";", dec = ".") # dim: 7936 x 29
names(df_pns)
## [1] "uf" "sexo" "idade" "raca"
## [5] "compa" "plano" "srh1" "incapacidade"
## [9] "srh2" "ex_colo" "ex_mamo" "relacao_sexual"
## [13] "gravidez" "aborto" "n_aborto" "paridade"
## [17] "nasc_vivo" "pre_natal" "t_pre_natal1" "t_pre_natal2"
## [21] "peso_pregest" "gpg_tot" "tipo_parto" "peso_af"
## [25] "esta_af" "cc_af" "pas" "pad"
## [29] "educ"
head(df_pns, 10)
## uf sexo idade raca compa plano srh1 incapacidade
## 1 Rondonia Mulheres 32 Pretos Sim Sim Bom Sim
## 2 Rondonia Mulheres 25 Pardos Sim Sim Bom Nao
## 3 Rondonia Mulheres 32 Pardos Sim Nao Bom Nao
## 4 Rondonia Mulheres 28 Pardos Sim Nao Regular Nao
## 5 Rondonia Mulheres 24 Pardos Sim Nao Muito bom Nao
## 6 Rondonia Mulheres 35 Brancos Sim Nao Bom Nao
## 7 Rondonia Mulheres 33 Pardos Sim Sim Bom Nao
## 8 Rondonia Mulheres 35 Brancos Sim Sim Muito bom Nao
## 9 Rondonia Mulheres 35 Pardos Sim Nao Bom Nao
## 10 Rondonia Mulheres 31 Pardos Sim Nao Regular Nao
## srh2 ex_colo ex_mamo
## 1 Boa De 1 ano a menos de 2 anos <NA>
## 2 Boa Menos de 1 ano atras <NA>
## 3 Boa De 1 ano a menos de 2 anos 3 anos ou mais atras
## 4 Regular De 1 ano a menos de 2 anos <NA>
## 5 Muito boa nunca <NA>
## 6 Boa Menos de 1 ano atras <NA>
## 7 Boa 3 anos ou mais atras <NA>
## 8 Muito boa De 2 anos a menos de 3 anos <NA>
## 9 Boa Menos de 1 ano atras Menos de 1 ano atras
## 10 Regular De 1 ano a menos de 2 anos <NA>
## relacao_sexual gravidez aborto n_aborto paridade nasc_vivo pre_natal
## 1 Sim Sim Nao NA 1 1 Sim
## 2 Sim Sim Nao NA 2 2 Nao
## 3 Sim Sim Nao NA 3 3 <NA>
## 4 Sim Sim Nao NA 1 1 <NA>
## 5 Sim Sim Nao NA 4 4 Nao
## 6 Sim Sim Nao NA 2 2 <NA>
## 7 Nao Sim Nao NA 0 NA <NA>
## 8 Sim Sim Sim 1 2 2 <NA>
## 9 Sim Sim Nao NA 2 2 <NA>
## 10 Sim Sim Sim 1 3 3 <NA>
## t_pre_natal1 t_pre_natal2 peso_pregest gpg_tot tipo_parto peso_af
## 1 Mais de 30 dias 39 52 12 Vaginal 55.0
## 2 <NA> NA 0 0 Vaginal 91.2
## 3 <NA> NA NA NA <NA> 92.6
## 4 <NA> NA NA NA <NA> 110.5
## 5 <NA> NA 70 0 Cesaria 66.0
## 6 <NA> NA NA NA <NA> 66.2
## 7 <NA> NA NA NA <NA> 67.0
## 8 <NA> NA NA NA <NA> 78.2
## 9 <NA> NA NA NA <NA> 77.0
## 10 <NA> NA NA NA <NA> 58.2
## esta_af cc_af pas pad educ
## 1 170 82.0 105.5 63.0 Secundario
## 2 157 107.5 88.0 66.0 Terciario
## 3 156 109.0 101.0 75.0 Secundario
## 4 155 124.5 102.5 74.0 Primario
## 5 157 80.0 117.0 66.5 Pre-primario
## 6 153 89.0 111.5 75.0 Pre-primario
## 7 146 94.0 108.5 76.5 Secundario
## 8 161 98.0 114.5 69.0 Primario
## 9 159 90.0 118.5 74.5 Secundario
## 10 158 76.0 98.5 70.5 Secundario
df_pns$t_pre_natal2[df_pns$t_pre_natal2 == 88] = NA
df_pns$gpg_tot[df_pns$gpg_tot == 888 | df_pns$gpg_tot == 0] = NA
# Observar a estrutura do banco de dados
glimpse(df_pns)
## Observations: 7,936
## Variables: 29
## $ uf <fct> Rondonia, Rondonia, Rondonia, Rondonia, Rondoni...
## $ sexo <fct> Mulheres, Mulheres, Mulheres, Mulheres, Mulhere...
## $ idade <int> 32, 25, 32, 28, 24, 35, 33, 35, 35, 31, 26, 25,...
## $ raca <fct> Pretos, Pardos, Pardos, Pardos, Pardos, Brancos...
## $ compa <fct> Sim, Sim, Sim, Sim, Sim, Sim, Sim, Sim, Sim, Si...
## $ plano <fct> Sim, Sim, Nao, Nao, Nao, Nao, Sim, Sim, Nao, Na...
## $ srh1 <fct> Bom, Bom, Bom, Regular, Muito bom, Bom, Bom, Mu...
## $ incapacidade <fct> Sim, Nao, Nao, Nao, Nao, Nao, Nao, Nao, Nao, Na...
## $ srh2 <fct> Boa, Boa, Boa, Regular, Muito boa, Boa, Boa, Mu...
## $ ex_colo <fct> De 1 ano a menos de 2 anos, Menos de 1 ano atra...
## $ ex_mamo <fct> NA, NA, 3 anos ou mais atras, NA, NA, NA, NA, N...
## $ relacao_sexual <fct> Sim, Sim, Sim, Sim, Sim, Sim, Nao, Sim, Sim, Si...
## $ gravidez <fct> Sim, Sim, Sim, Sim, Sim, Sim, Sim, Sim, Sim, Si...
## $ aborto <fct> Nao, Nao, Nao, Nao, Nao, Nao, Nao, Sim, Nao, Si...
## $ n_aborto <int> NA, NA, NA, NA, NA, NA, NA, 1, NA, 1, 1, NA, 1,...
## $ paridade <int> 1, 2, 3, 1, 4, 2, 0, 2, 2, 3, 2, 2, 1, 4, 2, 4,...
## $ nasc_vivo <int> 1, 2, 3, 1, 4, 2, NA, 2, 2, 3, 2, 2, 1, 4, 2, 4...
## $ pre_natal <fct> Sim, Nao, NA, NA, Nao, NA, NA, NA, NA, NA, NA, ...
## $ t_pre_natal1 <fct> Mais de 30 dias, NA, NA, NA, NA, NA, NA, NA, NA...
## $ t_pre_natal2 <int> 39, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 39,...
## $ peso_pregest <int> 52, 0, NA, NA, 70, NA, NA, NA, NA, NA, NA, 55, ...
## $ gpg_tot <int> 12, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 14,...
## $ tipo_parto <fct> Vaginal, Vaginal, NA, NA, Cesaria, NA, NA, NA, ...
## $ peso_af <dbl> 55.0, 91.2, 92.6, 110.5, 66.0, 66.2, 67.0, 78.2...
## $ esta_af <dbl> 170.0, 157.0, 156.0, 155.0, 157.0, 153.0, 146.0...
## $ cc_af <dbl> 82.0, 107.5, 109.0, 124.5, 80.0, 89.0, 94.0, 98...
## $ pas <dbl> 105.5, 88.0, 101.0, 102.5, 117.0, 111.5, 108.5,...
## $ pad <dbl> 63.0, 66.0, 75.0, 74.0, 66.5, 75.0, 76.5, 69.0,...
## $ educ <fct> Secundario, Terciario, Secundario, Primario, Pr...
# Descrição sumária das variáveis
summary(df_pns)
## uf sexo idade raca
## Sao Paulo : 551 Mulheres:7936 Min. :18.00 Brancos:2524
## Amazonas : 421 1st Qu.:25.00 Pardos :4645
## Minas Gerais: 386 Median :29.00 Pretos : 767
## Parana : 357 Mean :28.67
## Pernambuco : 354 3rd Qu.:33.00
## Ceara : 348 Max. :35.00
## (Other) :5519
## compa plano srh1 incapacidade srh2
## Nao:2249 Nao:6391 Bom :4880 Nao:7345 Boa :4791
## Sim:5687 Sim:1545 Muito bom :1015 Sim: 591 Muito boa :1014
## Muito ruim: 42 Muito ruim: 48
## Regular :1770 Regular :1852
## Ruim : 229 Ruim : 231
##
##
## ex_colo ex_mamo
## 3 anos ou mais atras : 637 3 anos ou mais atras : 153
## De 1 ano a menos de 2 anos :2056 De 1 ano a menos de 2 anos : 176
## De 2 anos a menos de 3 anos: 648 De 2 anos a menos de 3 anos: 58
## Menos de 1 ano atras :3438 Menos de 1 ano atras : 341
## nunca :1157 NA's :7208
##
##
## relacao_sexual gravidez aborto n_aborto paridade
## Nao : 524 Sim:7936 Nao:6291 Min. :1.000 Min. : 0.000
## Sim :7277 Sim:1645 1st Qu.:1.000 1st Qu.: 1.000
## NA's: 135 Median :1.000 Median : 2.000
## Mean :1.212 Mean : 1.993
## 3rd Qu.:1.000 3rd Qu.: 3.000
## Max. :7.000 Max. :13.000
## NA's :6291
## nasc_vivo pre_natal t_pre_natal1 t_pre_natal2
## Min. : 0.000 Nao : 59 De 15 a 30 dias : 289 Min. : 2.00
## 1st Qu.: 1.000 Sim :1541 De 7 a 14 dias : 460 1st Qu.:35.00
## Median : 2.000 NA's:6336 Mais de 30 dias : 67 Median :37.00
## Mean : 1.989 Menos de 7 dias: 647 Mean :36.03
## 3rd Qu.: 3.000 NA's :6473 3rd Qu.:39.00
## Max. :14.000 Max. :45.00
## NA's :202 NA's :6662
## peso_pregest gpg_tot tipo_parto peso_af
## Min. : 0.00 Min. : 1.00 Cesaria: 816 Min. : 31.90
## 1st Qu.: 49.00 1st Qu.: 8.00 Vaginal: 784 1st Qu.: 56.00
## Median : 56.00 Median :11.00 NA's :6336 Median : 63.90
## Mean : 53.69 Mean :12.56 Mean : 65.93
## 3rd Qu.: 64.00 3rd Qu.:16.00 3rd Qu.: 73.20
## Max. :125.00 Max. :60.00 Max. :160.00
## NA's :6336 NA's :6636
## esta_af cc_af pas pad
## Min. :131.0 Min. : 54.00 Min. : 76.5 Min. : 48.00
## 1st Qu.:154.5 1st Qu.: 77.00 1st Qu.:104.5 1st Qu.: 67.00
## Median :159.0 Median : 84.50 Median :112.0 Median : 73.00
## Mean :159.0 Mean : 85.93 Mean :113.5 Mean : 73.71
## 3rd Qu.:163.3 3rd Qu.: 93.30 3rd Qu.:121.0 3rd Qu.: 80.00
## Max. :186.9 Max. :152.90 Max. :238.0 Max. :145.50
##
## educ
## Pre-primario:2165
## Primario :1725
## Secundario :3306
## Terciario : 740
##
##
##
print(
summarytools::dfSummary(
df_pns, graph.magnif = 0.75),
method = "render") # "render" para gerar html
| No | Variable | Stats / Values | Freqs (% of Valid) | Graph | Valid | Missing |
|---|---|---|---|---|---|---|
| 1 | uf [factor] | 1. Acre 2. Alagoas 3. Amapa 4. Amazonas 5. Bahia 6. Ceara 7. Distrito Federal 8. Espirito Santo 9. Goias 10. Maranhao [ 17 others ] | 309 (3.9%) 252 (3.2%) 251 (3.2%) 421 (5.3%) 316 (4.0%) 348 (4.4%) 217 (2.7%) 202 (2.5%) 322 (4.1%) 314 (4.0%) 4984 (62.8%) | 7936 (100%) | 0 (0%) | |
| 2 | sexo [factor] | 1. Mulheres | 7936 (100.0%) | 7936 (100%) | 0 (0%) | |
| 3 | idade [integer] | mean (sd) : 28.67 (4.6) min < med < max : 18 < 29 < 35 IQR (CV) : 8 (0.16) | 18 distinct values | 7936 (100%) | 0 (0%) | |
| 4 | raca [factor] | 1. Brancos 2. Pardos 3. Pretos | 2524 (31.8%) 4645 (58.5%) 767 (9.7%) | 7936 (100%) | 0 (0%) | |
| 5 | compa [factor] | 1. Nao 2. Sim | 2249 (28.3%) 5687 (71.7%) | 7936 (100%) | 0 (0%) | |
| 6 | plano [factor] | 1. Nao 2. Sim | 6391 (80.5%) 1545 (19.5%) | 7936 (100%) | 0 (0%) | |
| 7 | srh1 [factor] | 1. Bom 2. Muito bom 3. Muito ruim 4. Regular 5. Ruim | 4880 (61.5%) 1015 (12.8%) 42 (0.5%) 1770 (22.3%) 229 (2.9%) | 7936 (100%) | 0 (0%) | |
| 8 | incapacidade [factor] | 1. Nao 2. Sim | 7345 (92.5%) 591 (7.4%) | 7936 (100%) | 0 (0%) | |
| 9 | srh2 [factor] | 1. Boa 2. Muito boa 3. Muito ruim 4. Regular 5. Ruim | 4791 (60.4%) 1014 (12.8%) 48 (0.6%) 1852 (23.3%) 231 (2.9%) | 7936 (100%) | 0 (0%) | |
| 10 | ex_colo [factor] | 1. 3 anos ou mais atras 2. De 1 ano a menos de 2 ano 3. De 2 anos a menos de 3 an 4. Menos de 1 ano atras 5. nunca | 637 (8.0%) 2056 (25.9%) 648 (8.2%) 3438 (43.3%) 1157 (14.6%) | 7936 (100%) | 0 (0%) | |
| 11 | ex_mamo [factor] | 1. 3 anos ou mais atras 2. De 1 ano a menos de 2 ano 3. De 2 anos a menos de 3 an 4. Menos de 1 ano atras | 153 (21.0%) 176 (24.2%) 58 (8.0%) 341 (46.8%) | 728 (9.17%) | 7208 (90.83%) | |
| 12 | relacao_sexual [factor] | 1. Nao 2. Sim | 524 (6.7%) 7277 (93.3%) | 7801 (98.3%) | 135 (1.7%) | |
| 13 | gravidez [factor] | 1. Sim | 7936 (100.0%) | 7936 (100%) | 0 (0%) | |
| 14 | aborto [factor] | 1. Nao 2. Sim | 6291 (79.3%) 1645 (20.7%) | 7936 (100%) | 0 (0%) | |
| 15 | n_aborto [integer] | mean (sd) : 1.21 (0.57) min < med < max : 1 < 1 < 7 IQR (CV) : 0 (0.47) | 1 : 1382 (84.0%) 2 : 210 (12.8%) 3 : 33 (2.0%) 4 : 11 (0.7%) 5 : 7 (0.4%) 6 : 1 (0.1%) 7 : 1 (0.1%) | 1645 (20.73%) | 6291 (79.27%) | |
| 16 | paridade [integer] | mean (sd) : 1.99 (1.28) min < med < max : 0 < 2 < 13 IQR (CV) : 2 (0.64) | 14 distinct values | 7936 (100%) | 0 (0%) | |
| 17 | nasc_vivo [integer] | mean (sd) : 1.99 (1.24) min < med < max : 0 < 2 < 14 IQR (CV) : 2 (0.62) | 15 distinct values | 7734 (97.45%) | 202 (2.55%) | |
| 18 | pre_natal [factor] | 1. Nao 2. Sim | 59 (3.7%) 1541 (96.3%) | 1600 (20.16%) | 6336 (79.84%) | |
| 19 | t_pre_natal1 [factor] | 1. De 15 a 30 dias 2. De 7 a 14 dias 3. Mais de 30 dias 4. Menos de 7 dias | 289 (19.8%) 460 (31.4%) 67 (4.6%) 647 (44.2%) | 1463 (18.43%) | 6473 (81.57%) | |
| 20 | t_pre_natal2 [integer] | mean (sd) : 36.03 (5.09) min < med < max : 2 < 37 < 45 IQR (CV) : 4 (0.14) | 35 distinct values | 1274 (16.05%) | 6662 (83.95%) | |
| 21 | peso_pregest [integer] | mean (sd) : 53.69 (21.31) min < med < max : 0 < 56 < 125 IQR (CV) : 15 (0.4) | 77 distinct values | 1600 (20.16%) | 6336 (79.84%) | |
| 22 | gpg_tot [integer] | mean (sd) : 12.56 (6.99) min < med < max : 1 < 11 < 60 IQR (CV) : 8 (0.56) | 41 distinct values | 1300 (16.38%) | 6636 (83.62%) | |
| 23 | tipo_parto [factor] | 1. Cesaria 2. Vaginal | 816 (51.0%) 784 (49.0%) | 1600 (20.16%) | 6336 (79.84%) | |
| 24 | peso_af [numeric] | mean (sd) : 65.93 (14.16) min < med < max : 31.9 < 63.9 < 160 IQR (CV) : 17.2 (0.21) | 742 distinct values | 7936 (100%) | 0 (0%) | |
| 25 | esta_af [numeric] | mean (sd) : 158.99 (6.7) min < med < max : 131 < 159 < 186.9 IQR (CV) : 8.8 (0.04) | 378 distinct values | 7936 (100%) | 0 (0%) | |
| 26 | cc_af [numeric] | mean (sd) : 85.93 (12.33) min < med < max : 54 < 84.5 < 152.9 IQR (CV) : 16.3 (0.14) | 590 distinct values | 7936 (100%) | 0 (0%) | |
| 27 | pas [numeric] | mean (sd) : 113.46 (13.15) min < med < max : 76.5 < 112 < 238 IQR (CV) : 16.5 (0.12) | 298 distinct values | 7936 (100%) | 0 (0%) | |
| 28 | pad [numeric] | mean (sd) : 73.71 (9.81) min < med < max : 48 < 73 < 145.5 IQR (CV) : 13 (0.13) | 248 distinct values | 7936 (100%) | 0 (0%) | |
| 29 | educ [factor] | 1. Pre-primario 2. Primario 3. Secundario 4. Terciario | 2165 (27.3%) 1725 (21.7%) 3306 (41.7%) 740 (9.3%) | 7936 (100%) | 0 (0%) |
Generated by summarytools 0.8.8 (R version 3.5.2)
2019-01-18
### Gráficos (funções básicas)
#attach(df_pns)
plot(df_pns$plano,
las = 2 # estilo: rótulo do eixos (0 [default], 1 horizontal, 2 perpendicular, 3 vertical)
)
title("Frequência absoluta \n de consumidores de plano de saúde")
freq1 = table(df_pns$plano, df_pns$raca)
freq1
##
## Brancos Pardos Pretos
## Nao 1764 3993 634
## Sim 760 652 133
bp1 = barplot(freq1,
beside = TRUE, # [TRUE] justaposto ou [FALSE] empilhado
names.arg = c("White", "Brown", "Black"),
las = 1,
ylim = c(0,5000),
main = "Plano de saúde vs. Cor da pele",
col = c("blue", "red"))
text(bp1, freq1, pos = 3, # posição: 1 abaixo, 2 esquerda, 3 acima, 4 direita
labels = c(1764,760,3993,652,634,133))
legend("topright", # opções: "bottomright", "bottom", "bottomleft", "left", "topleft", "top", "right", "center"
pch = c(15, 15),
bty = "o", # opção: "n" não criar box na legenda
cex = 1,
legend = c("Não", "Sim"),
col = c("blue", "red"),
y.intersp = 0.5, # interspacing factor for vertical (y) spacing
x.intersp = 0.5 # interspacing factor for horizontal (x) spacing
)
rm(bp1, freq1)
freq2 = table(df_pns$srh2)
freq2
##
## Boa Muito boa Muito ruim Regular Ruim
## 4791 1014 48 1852 231
#df_pns$srh2 = factor(df_pns$srh2, levels = c("Muito boa","Boa","Regular","Ruim","Muito ruim"))
pie(freq2,
labels = c("Very good", "Good", "Regular", "Bad", "Very bad"),
col = rainbow(5) # As cores tbm podem ser de???nidas com a função rainbow(n)
)
title(main="Saúde auto-referida", sub="PNS, 2013")
rm(freq2)
hist(df_pns$esta_af, # útil para verificar assimetria e sua forma. É um gráfico de barras em que a alturas das barras representam a frequência (absoluta/relativa) da variável para intervalos marcados no eixo horizontal.
breaks = 15,
col="blue",
freq = FALSE,
xlab = "",
main = "Estatura aferida")
title(sub = "PNS, 2013")
curve(dnorm(x, # adicionando uma curva normal
mean = mean(df_pns$esta_af),
sd = sd(df_pns$esta_af)),
col = 2,
lty = 2,
lwd = 2,
add = TRUE)
boxplot(df_pns$esta_af) # útil para verificar a distribuição de uma variável e para detectar outliers.
boxplot(df_pns$esta_af ~ df_pns$educ,
xlab = "Escolaridade",
ylab = "Estatura (cm)",
main = "Estatura vs. Escolaridade",
col = "green",
horizontal = FALSE,
notch = TRUE # entalhar a caixa do gráfico
)
plot(df_pns$cc ~ df_pns$peso_af, # gráfico de dispersão: avaliação visual de associação Y~X
xlab = "Peso (Kg)", ylab = "Circunferência de cintura (cm)",
main = "Título",
sub = "Subtítulo",
pch = 19,
col = rgb(0,0,0,0.15))
abline( # para adicionar 1+ linhas
lm(df_pns$cc ~ df_pns$peso_af),
col = "red")
# df_pns$gpg_tot[df_pns$gpg_tot == 888 | df_pns$gpg_tot == 0] = NA
tb3 = aggregate(df_pns$gpg_tot, by = list(df_pns$idade), mean, na.rm = TRUE)
colnames(tb3) = c("idade", "gpg_tot")
tb3
## idade gpg_tot
## 1 18 13.87755
## 2 19 12.00000
## 3 20 13.17500
## 4 21 11.50000
## 5 22 12.63235
## 6 23 13.36364
## 7 24 12.39241
## 8 25 12.69231
## 9 26 12.18000
## 10 27 12.76812
## 11 28 13.01429
## 12 29 11.74074
## 13 30 12.83871
## 14 31 11.43678
## 15 32 13.37879
## 16 33 11.10448
## 17 34 13.94231
## 18 35 13.17778
plot(tb3$gpg_tot ~ tb3$idade,
type = "l",
ylab = "Ganho de peso gestacional (Kg)",
xlab = "idade (anos)",
main = "GPG vs. idade")
rm(tb3)
w = df_pns[, c(3,24:28)]
w = sample_n(w, size = 200, replace = TRUE)
head(w)
## idade peso_af esta_af cc_af pas pad
## 1728 19 57.3 155.0 76.5 100.5 75.0
## 1420 33 61.9 156.5 85.0 100.0 63.0
## 3324 23 39.9 154.6 64.5 104.0 71.0
## 821 24 67.1 154.8 89.2 113.0 69.5
## 4284 21 68.3 163.5 97.5 101.0 67.0
## 423 29 55.3 143.2 88.3 116.5 81.0
pairs(w)
lattice::splom(w, col = "red", main = "Dados")
corrplot::corrplot(cor(w, # https://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html
method = "spearman",
use = "pairwise.complete.obs"),
method = "circle", tl.srt = 90,
type = "upper", diag = FALSE, tl.col = "black")
lattice::cloud(df_pns$cc ~ df_pns$peso_af*df_pns$esta_af, # Z~X*Y
col = "blue",
xlab = "Peso (cm)",
ylab = "Estatura (cm)",
zlab = "CC (cm)",
main = "Gráfico 3D simples",
sub = "PNS, 2013")
rm(w)
# par(mfrow=c(1,2))
# par(mfcol=c(1,2))
# layout(matrix(c(1,1,2,3),2,2, byrow = TRUE)
# dev.new()
#### PARTE 2 (GGPLOT) ####
names(df_pns)
## [1] "uf" "sexo" "idade" "raca"
## [5] "compa" "plano" "srh1" "incapacidade"
## [9] "srh2" "ex_colo" "ex_mamo" "relacao_sexual"
## [13] "gravidez" "aborto" "n_aborto" "paridade"
## [17] "nasc_vivo" "pre_natal" "t_pre_natal1" "t_pre_natal2"
## [21] "peso_pregest" "gpg_tot" "tipo_parto" "peso_af"
## [25] "esta_af" "cc_af" "pas" "pad"
## [29] "educ"
## The setup
ggplot(df_pns) # se apenas o dataset é conhecido
ggplot(df_pns,
aes(x = plano)) # se apenas o eixo "x" é conhecido. O eixo y deve ser especificado em geom()
ggplot(df_pns,
aes(x = plano, y = pas)) # se os eixos "x" e "y" são fixos para todos os layers
ggplot(df_pns,
aes(x = plano, color = raca)) # cada categoria de "raca" terá uma cor diferente, uma vez adicionado geom()
ggplot(df_pns,
aes(x = plano), color = "steelblue") # The aes argument stands for aesthetics. ggplot2 considers the X and Y axis of the plot to be aesthetics as well, along with color, size, shape, fill etc. If you want to have the color, size etc fixed (i.e. not vary based on a variable from the dataframe), you need to specify it outside the aes()
## The Layers (also called "geoms")
ggplot(df_pns,
aes(x = peso_af, y = cc_af, color = educ)) +
geom_point() + # layer 1: add scatterplot geom
geom_smooth() # layer 2: add smoothing geom
## `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'
ggplot(df_pns) +
geom_point(aes(x = peso_af, y = cc_af, color = educ)) +
geom_smooth(aes(x = peso_af, y = cc_af, color = educ)) # mesmo que acima, mas especificando "aes" dentro de "geom"
## `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'
ggplot(df_pns,
aes(x = peso_af, y = cc_af)) +
geom_point(aes(color = educ)) +
geom_smooth() # integrando os múltiplos smoothing lines em linha única
## `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'
ggplot(df_pns) +
geom_point(aes(x = peso_af, y = cc_af, color = educ)) +
geom_smooth(aes(x = peso_af, y = cc_af)) # mesmo que acima
## `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'
ggplot(df_pns,
aes(x = peso_af, y = cc_af, shape = educ)) +
geom_point()
## The Labels
gg = ggplot(df_pns,
aes(x = peso_af, y = cc_af, color = educ)) +
geom_point() +
labs(title = "Scatterplot", # add título para o gráfico e eixos "x" e "y"
x = "Peso (Kg)",
y = "Circunferência de cintura (cm)")
print(gg)
## The Theme
gg1 = gg + theme( # customizar componentes non-data do gráfico
plot.title = element_text(size = 25, face = "bold"), # manipular tamanho e cor do título do grafico
axis.title.x = element_text(size = 15), # manipular tamanho do título do eixo "x"
axis.title.y = element_text(size = 15), # manipular tamanho do título do eixo "y"
axis.text.x = element_text(size = 15), # manipular tamanho dos ticks no eixo "x"
axis.text.y = element_text(size = 15)) + # manipular tamanho dos ticks no eixo "y"
scale_color_discrete(name = "Escolaridade") # add titulo e axis text e manipular título da legenda
print(gg1)
## The Facets
gg1 + facet_wrap(~ educ, ncol=3) # apresentacao em grafs separados, segundo educ
gg1 + facet_wrap(raca ~ educ) # linha: raca, coluna = educ
gg1 + facet_wrap(raca ~ educ, scales = "free")
gg1 + facet_grid(raca ~ educ)
### OUTROS EXEMPLOS DE GGPLOT
geom_line()
## geom_line: na.rm = FALSE
## stat_identity: na.rm = FALSE
## position_identity
gg3 = ggplot(df_pns, aes(x = raca)) +
geom_bar() +
labs(title="Gráfico de Frequência 1") # eixo "y" derivado pela contagem dos itens de "x"
print(gg3)
gg4 = ggplot(df_pns, aes(x = educ, y = paridade)) +
geom_bar(stat = "identity") + # Y axis is explicit 'stat=identity'
labs(title="Gráfico de Frequência 2") # + coord_polar(theta = "y", start=0)
print(gg4)
gridExtra::grid.arrange(gg3, gg4, ncol=2) # custom layout
gg5 = ggplot(df_pns, aes(x = relacao_sexual, y = pas)) +
geom_bar(stat = "identity") + # Y axis is explicit 'stat=identity'
labs(title="Gráfico de Frequência 3") +
coord_flip()
print(gg5)
ggplot(df_pns,
aes(x = peso_af, y = cc_af)) +
geom_point(aes(color = educ)) +
geom_smooth() +
coord_cartesian(ylim = c(0,200))
## `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'
ggplot(df_pns,
aes(x = peso_af, y = cc_af)) +
geom_point(aes(color = educ)) +
geom_smooth() +
coord_equal()
## `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'
ggplot(df_pns,
aes(x = peso_af, y = cc_af)) +
geom_point(aes(color = educ)) +
geom_smooth() +
coord_equal() +
theme_bw() # mudar tema/backgroup: theme_gray(), theme_bw(), theme_linedraw(), theme_light(), theme_minimal(), theme_classic(), theme_void()
## `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'
ggplot(df_pns,
aes(x = peso_af, y = cc_af)) +
geom_point(aes(color = educ)) +
geom_smooth() +
coord_equal() +
theme(legend.position = "none") # mudar posição da legenda: "left", "right", "bottom", "top"
## `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'
ggplot(df_pns,
aes(x = peso_af, y = cc_af)) +
geom_point(aes(color = educ)) +
geom_smooth() +
coord_equal() +
theme(legend.justification = c(1,0), # add legenda dentro do gráfico
legend.position = c(1,0))
## `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'
library(grid)
grob = grobTree(textGrob("MEU TEXTO AQUI", x=0.1, y=0.9, hjust=0,
gp=gpar(col="firebrick", fontsize=20, fontface="bold")))
ggplot(df_pns, aes(x = srh2)) +
geom_bar() +
labs(title="Annotation Example") +
annotation_custom(grob)
gg6 = ggplot(df_pns,
aes(x = educ, y = cc_af)) +
geom_boxplot(aes(color = educ)) + # alternativo: geom_violin()
labs(title = "Gráfico de caixas",
subtitle = "Boxplot",
x = "Escolaridade",
y = "Circunferência (cm)") +
theme_bw() +
theme(legend.position = "none")
print(gg6)
ggsave("myggplot.png", plot = gg6) # salvar grafico
## Saving 7 x 5 in image
ggplot(df_pns, aes(cc_af)) +
geom_density(aes(fill=factor(educ)), alpha=0.8) +
labs(title="Gráfico de densidade",
subtitle="CC por escolaridade",
caption="Fonte: PNS, 2013",
x="Escolaridade",
fill="Escolaridade")
###########################
#### TÓPICOS ESPECIAIS ####
###########################
### BIBLIOMETRICS # http://www.bibliometrix.org/
#library(bibliometrix)
#library(RISmed)
#search_topic = "(intergrowth[tiab] AND gestational[tiab])"
#search_query = EUtilsSummary(search_topic)
#summary(search_query)
#QueryId(search_query)
#D = EUtilsGet(search_query)
#M = pubmed2df(D)
#results = biblioAnalysis(M, sep = ";")
#options(width=100)
#S = summary(object = results, k = 10, pause = FALSE)
### CORRELATION PLOT
library(ggcorrplot)
w = df_pns[, c(3,24:28)]
corr = round(cor(w), 1)
ggcorrplot(corr, hc.order = TRUE,
type = "lower",
lab = TRUE,
lab_size = 3,
method="circle",
colors = c("tomato2", "white", "springgreen3"),
title="Correlograma",
ggtheme=theme_bw)
### ANIMATED BUBBLE CHART
library(gganimate) # https://github.com/dgrtwo/gganimate
library(gapminder)
ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
geom_point(alpha = 0.7, show.legend = FALSE) +
scale_colour_manual(values = country_colors) +
scale_size(range = c(2, 12)) +
scale_x_log10() +
facet_wrap(~continent) +
# Here comes the gganimate specific bits
labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') +
transition_time(year) +
ease_aes('linear')
###########
### FIM ###
###########
rm(list = ls())