13 de julho de 2015

Objetivos do curso

  • Explorar a diferenƧa entre tabelas e grĆ”ficos
  • Familiarizar os alunos com a produção de grĆ”ficos no R
  • Conhecer o repertório bĆ”sico de grĆ”ficos usados para variĆ”veis quantitativas ou categóricas

Programa

  1. Tabelas

  2. GrƔficos para dados quantitativos
    • Histograma
    • Boxplot
    • Scatterplot
    • Matriz de correlação
    • GrĆ”ficos para o tempo
  3. GrÔficos para dados categóricos
    • Barra para uma variĆ”vel
    • Barra para duas variĆ”veis
    • Mosaicplot

Carregar os pacotes que serão usados

library(ggplot2)
library(Lock5Data)
library(openintro)
library(GGally)
library(car)
library (vcd)

1. Tabelas

Tabelas

Vantagem das tabelas

  • Apresenta os nĆŗmeros com precisĆ£o
  • Permitir usar dados de origens diferentes

TendĆŖncia

  • Usada com parcimĆ“nia em sites e publicaƧƵes de dados oficiais
  • Planilhas como "pano de fundo" da apresentação de grĆ”ficos mesmo em sites que divulgam estatĆ­stica oficial.

Tabelas no R

Para fazer tabelas para o word, use o word

tabela <- table(hsb2$race, hsb2$gender)
tabela
##                   
##                    female male
##   african american     13    7
##   asian                 8    3
##   hispanic             11   13
##   white                77   68

O R Ć© bom para exportar tabelas para o latex e markdown.

Regras para uma boa tabela

  • Sem linhas internas na horizontal ou vertical
  • Casas decimais: consultar manuais; quase nunca mais de dois dĆ­gitos.
  • Fontes e notas
  • Nova moda; comentĆ”rios abaixo da tabela.

Vale a pena manter tabelas com os coeficientes de anƔlise multivariadas?

2.GrƔficos

Ciências sociais em direção aos grÔficos

  • Weissgerber, T. L., Milic, N. M., Winham, S. J., & Garovic, V. D. (2015). Beyond Bar and Line Graphs: Time for a New Data Presentation Paradigm. PLOS Biology, 13(4).

  • Schwabish, J. A. (2014). An Economist's Guide to Visualizing Data. Journal of Economic Perspectives, 28(1), 209–234.

  • Healy, K., & Moody, J. (2014). Data Visualization in Sociology. Annual Review of Sociology, 40(1), 105–128.

  • Kastellec, J. P., & Leoni, E. L. (2007). Using Graphs Instead of Tables in Political Science. Perspective on Politics, 5(04), 755–771.

  • Gelman, A., Pasarica, C., & Dodhia, R. (2002). Let's Practice What We Preach. The American Statistician, 56(2), 121–130.

Um exemplo de medicina

GrƔficos em que programa?

  • Excel
  • Tableau
  • SPSS
  • Stata

GrƔficos no R

2.GrƔficos para dados quantitativos

2.1 Histograma

2.2 Boxplot

2.3 Scatterplot

2.4 Matriz de correlação

2.5 GrƔficos para o tempo

2.1 Histograma

Carregar e olhar o banco que serĆ” usado

library(Lock5Data)
data("AllCountries")
names(AllCountries)
##  [1] "Country"        "Code"           "LandArea"       "Population"    
##  [5] "Energy"         "Rural"          "Military"       "Health"        
##  [9] "HIV"            "Internet"       "Developed"      "BirthRate"     
## [13] "ElderlyPop"     "LifeExpectancy" "CO2"            "GDP"           
## [17] "Cell"           "Electricity"

str(AllCountries)
## 'data.frame':    213 obs. of  18 variables:
##  $ Country       : Factor w/ 213 levels "Afghanistan",..: 1 2 3 4 5 6 7 8 9 10 ...
##  $ Code          : Factor w/ 211 levels "","AFG","ALB",..: 2 3 4 11 5 6 7 8 9 10 ...
##  $ LandArea      : int  652230 27400 2381740 200 470 1246700 440 2736690 28480 180 ...
##  $ Population    : num  29.021 3.143 34.373 0.066 0.084 ...
##  $ Energy        : int  NA 2088 37069 NA NA 10972 NA 76359 2997 NA ...
##  $ Rural         : num  76 53.3 34.8 7.7 11.1 43.3 69.5 8 36.1 53.2 ...
##  $ Military      : num  4.4 NA 13 NA NA NA NA NA 16.1 NA ...
##  $ Health        : num  3.7 8.2 10.6 NA 21.3 6.8 11 13.7 7.2 NA ...
##  $ HIV           : num  NA NA 0.1 NA NA 2 NA 0.5 0.1 NA ...
##  $ Internet      : num  1.7 23.9 10.2 NA 70.5 3.1 75 28.1 6.2 22.8 ...
##  $ Developed     : int  NA 1 1 NA NA 1 NA 2 1 NA ...
##  $ BirthRate     : num  46.5 14.6 20.8 NA 10.4 42.9 NA 17.3 15.3 11.7 ...
##  $ ElderlyPop    : num  2.2 9.3 4.6 NA NA 2.5 NA 10.5 11.6 9.2 ...
##  $ LifeExpectancy: num  43.9 76.6 72.4 NA NA 47 NA 75.3 73.5 74.7 ...
##  $ CO2           : num  0.025 1.313 3.233 NA 6.528 ...
##  $ GDP           : num  501 3678 4495 NA NA ...
##  $ Cell          : num  37.8 141.9 92.4 NA 77.2 ...
##  $ Electricity   : num  NA 1747 971 NA NA ...

Histograma com o pacote bƔsico

 hist(AllCountries$Health, col = "red")

O mesmo histograma com mais detalhes

hist(AllCountries$Health, ylab = "Proporção", xlab = "Gastos",
      main = "Histograma: Gastos do governo com saĆŗde", col = "lightgray") 

GramƔtica do ggplot2: layers

ggplot(dataset…) +

aesthetic mapping (aes): basicamente as variƔveis x e y (e eventaulmente uma terceira); obs: antes o banco de dados.

geoms: define a forma geomĆ©trica que serĆ” usada: linha, boxplot, barras…

stats: posiciona geoms para outras estatĆ­sticas.

scales: mapeia o espaƧo dos dados (linear, logaritimico)

Histograma

ggplot(AllCountries, aes(Health)) + geom_histogram(binwidt = 1) 

Histograma

ggplot(AllCountries, aes(Health)) + 
    geom_histogram(binwidt = 2, fill = "orange", colour = "black") +
    labs(title = "Percentual de gastos em saĆŗde", x = "Gastos", y = " NĆŗmero de paĆ­ses")  

Histograma com percentual

ggplot(AllCountries,aes(Health,  y = (..count..)/sum(..count..))) + 
    geom_histogram(binwidt = 2, fill = "cornsilk", colour = "black") +
    labs(title = "Porcentagem de gastos em saĆŗde", x = "Gastos", y = "Percentual") 

Exercicio: Histograma

  • Carregar banco:
load("~/Dropbox/VisualizacaoCurso/presidente2010_curso.rdata")
  • A. Fazer um histograma bĆ”sico com a votação do PT (Dilma)
  • B. Fazer um histograma (ggplot2) com a votação do PSDB (Serra)

Resposta A

hist(presidente2010_curso$PT_pc, col = "red")

Resposta B

ggplot(presidente2010_curso, aes(PSDB_pc)) + 
    geom_histogram(binwidt = 5, fill = "dodgerblue4", colour = "black")

2.2 Boxplot

novo banco de dados

library(Lock5Data)
data("StudentSurvey")
summary(StudentSurvey$TV)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   0.000   3.000   5.000   6.504   9.000  40.000       1

Boxplot

boxplot(StudentSurvey$TV)

Boxplot com ggplot2

ggplot(StudentSurvey, aes( 1, TV)) + geom_boxplot()  

Boxplot segmentado por variÔvel categórica

boxplot(StudentSurvey$TV ~ StudentSurvey$Gender)

Boxplot com ggplot2 segmentado (I)

ggplot(StudentSurvey, aes(Gender, TV)) + geom_boxplot()

Boxplot com ggplot2 segmentado (II)

ggplot(StudentSurvey, aes(Gender, TV, fill = Gender)) + geom_boxplot() 

Boxplot com ggplot2 segmentado (III)

ggplot(StudentSurvey, aes(Gender, TV, fill = Gender)) + geom_boxplot() +
   guides(fill = FALSE) + coord_flip()

Exercicio: Boxplot

  • Fazer um boxplot da votação da Dilma por regiĆ£o

Resposta: ajuste dos dados

library(dplyr)
presidente2010_curso$regiao <- factor(presidente2010_curso$regiao, 
levels = c(1, 2, 3, 4, 5), labels = c("Centro-Oeste", "Nordeste", 
                                      "Norte", "Sudeste", "Sul"))

Resposta: fazendo o grƔfico

ggplot(presidente2010_curso, aes(regiao, PT_pc, fill = regiao)) + geom_boxplot() +
   guides(fill = FALSE)

2.3 Diagrama de dispersão (scatterplot)

Scatterplot

data("countyComplete")
plot(countyComplete$hs_grad, countyComplete$poverty, main = "Scatterplot com R bƔsico", 
     xlab = "Pobreza", ylab= "High School", pch = 19)

Scatterplot

library(openintro)
ggplot(countyComplete, aes(hs_grad,poverty)) + geom_point() 

Scatterplot com reta de ajuste (linear)

ggplot(countyComplete, aes(hs_grad,poverty)) + geom_point(shape = 1) +
 geom_smooth(method = "lm")

Scatterplot com "loess" e maior opacidade

ggplot(countyComplete, aes(hs_grad,poverty)) + 
    geom_point(shape = 19, alpha = 1/4) + geom_smooth(method = "loess")

Scatterplot com uma variÔvel categórica

library(openintro)
ggplot(births, aes(weeks, weight, color = premature)) + 
    geom_point() +  geom_smooth(method = "lm") 

Exercicio: Scatterplot

  • Fazer um scatterplot: renda e votos nulos

Resposta: renda e votos nulos

ggplot(presidente2010_curso, aes(rpc_2010,nulo_pc)) + 
geom_point(shape = 19, alpha = 1/4) + geom_smooth(method = "lm")  

Resposta: solução melhor

ggplot(presidente2010_curso, aes(log(rpc_2010),nulo_pc)) + 
    geom_point(shape = 19, alpha = 1/4) + geom_smooth(method = "lm")

Extra: Histogramas, boxplot e scatterplot com facets

histograma (imagem empilhada)

ggplot(presidente2010_curso, aes(x = PSDB_pc)) + 
    geom_histogram(binwidt = 5, fill = "dodgerblue4", colour = "black") +
    facet_grid(~idh5_2010)

Histograma, paralela: grid

ggplot(presidente2010_curso, aes(x = PSDB_pc)) + 
    geom_histogram(binwidt = 5, fill = "dodgerblue4", colour = "black") +
    facet_grid(idh5_2010 ~.)

Histograma, paralela: wrap

ggplot(presidente2010_curso, aes(x = PSDB_pc)) + 
    geom_histogram(binwidt = 5, fill = "dodgerblue4", colour = "black") +
    facet_wrap(~idh5_2010)

Boxplot, paralela: wrap

ggplot(presidente2010_curso, aes(regiao, PT_pc, fill= regiao)) + 
    geom_boxplot() +  facet_wrap(~idh5_2010)

Boxplot, paralela 2: wrap

ggplot(presidente2010_curso, aes(idh5_2010, PT_pc, colour = idh5_2010))+
geom_boxplot() + facet_wrap(~ regiao)

scatterplot paralelo

ggplot(presidente2010_curso, aes(PT_pc, PSDB_pc)) + 
geom_point(shape = 19, alpha = 1/4) + geom_smooth(method = "lm") + 
    facet_grid(regiao ~ .)

2.4 Matriz de correlação

Correlação

cor(countyComplete$black, countyComplete$white, use = "na.or.complete")
## [1] -0.7921438

Matriz de correlação

names(countyComplete)
##  [1] "state"                                    
##  [2] "name"                                     
##  [3] "FIPS"                                     
##  [4] "pop2010"                                  
##  [5] "pop2000"                                  
##  [6] "age_under_5"                              
##  [7] "age_under_18"                             
##  [8] "age_over_65"                              
##  [9] "female"                                   
## [10] "white"                                    
## [11] "black"                                    
## [12] "native"                                   
## [13] "asian"                                    
## [14] "pac_isl"                                  
## [15] "two_plus_races"                           
## [16] "hispanic"                                 
## [17] "white_not_hispanic"                       
## [18] "no_move_in_one_plus_year"                 
## [19] "foreign_born"                             
## [20] "foreign_spoken_at_home"                   
## [21] "hs_grad"                                  
## [22] "bachelors"                                
## [23] "veterans"                                 
## [24] "mean_work_travel"                         
## [25] "housing_units"                            
## [26] "home_ownership"                           
## [27] "housing_multi_unit"                       
## [28] "median_val_owner_occupied"                
## [29] "households"                               
## [30] "persons_per_household"                    
## [31] "per_capita_income"                        
## [32] "median_household_income"                  
## [33] "poverty"                                  
## [34] "private_nonfarm_establishments"           
## [35] "private_nonfarm_employment"               
## [36] "percent_change_private_nonfarm_employment"
## [37] "nonemployment_establishments"             
## [38] "firms"                                    
## [39] "black_owned_firms"                        
## [40] "native_owned_firms"                       
## [41] "asian_owned_firms"                        
## [42] "pac_isl_owned_firms"                      
## [43] "hispanic_owned_firms"                     
## [44] "women_owned_firms"                        
## [45] "manufacturer_shipments_2007"              
## [46] "mercent_whole_sales_2007"                 
## [47] "sales"                                    
## [48] "sales_per_capita"                         
## [49] "accommodation_food_service"               
## [50] "building_permits"                         
## [51] "fed_spending"                             
## [52] "area"                                     
## [53] "density"

Matriz de correlação

cor(countyComplete[, c(10,21, 33, 31)])
##                        white    hs_grad    poverty per_capita_income
## white              1.0000000  0.3523923 -0.4693775         0.1542088
## hs_grad            0.3523923  1.0000000 -0.6807925         0.6389915
## poverty           -0.4693775 -0.6807925  1.0000000        -0.7024140
## per_capita_income  0.1542088  0.6389915 -0.7024140         1.0000000

GrÔfico para matriz de correlação

library(GGally)
ggpairs(countyComplete[, c(10,21, 33, 31)], params = list(labelSize = 8))

Matriz de correlação: presidente 2010

ggpairs(presidente2010_curso[, c("PT_pc", "PSDB_pc", "idh_2010")], 
        params = list(labeSize = 8 ))

Matriz de correlação com o pacote car

library(car)
scatterplotMatrix(~PT_pc + PSDB_pc + idh_2010,
                  data = presidente2010_curso, spread = FALSE)

2.5 GrƔficos para o tempo

GrƔfico para dados no tempo (sƩries temporais)

ggplot(economics, aes(date, psavert)) + geom_point()

GrƔfico para dados no tempo (sƩries temporais), com pontos e linha loess

ggplot(economics, aes(date, psavert)) + geom_point()+ geom_smooth(method = "loess")

GrƔfico para dados temporais com linha

ggplot(economics, aes(date, psavert)) + geom_line()

Diversos modos de apresentar pesquisas de opinião

Carregando o banco

load("~/Dropbox/VisualizacaoCurso/corrida.rdata")
str(corrida)
## 'data.frame':    70 obs. of  5 variables:
##  $ data       : Date, format: "2014-08-15" "2014-08-15" ...
##  $ candidato  : chr  "Dilma" "Aecio" "Marina" "Outros" ...
##  $ instituto  : chr  "DATAFOLHA" "DATAFOLHA" "DATAFOLHA" "DATAFOLHA" ...
##  $ percentual : int  40 22 23 5 8 37 21 32 3 8 ...
##  $ Entrevistas: int  2843 2843 2843 2843 2843 2506 2506 2506 2506 2506 ...

GrƔfico em linha

ggplot(corrida, aes(data, percentual, colour = candidato)) + geom_line() +
    xlab("") + ylab("") + scale_color_manual(values = c("dodgerblue4","darkorchid3",
            "red", "darkolivegreen", "goldenrod1")) 

GrƔfico em linha, segmentado por instituto

ggplot(corrida, aes(data, percentual, colour = candidato)) + geom_line() +
    xlab("") + ylab("") + scale_color_manual(values = c("dodgerblue4","darkorchid3",
            "red", "darkolivegreen", "goldenrod1")) + facet_wrap(~ instituto) 

GrƔfico em linha (loess)

ggplot(corrida, aes(data, percentual, colour = candidato)) + 
    geom_smooth(method = "loess") +  xlab("") + ylab("") + 
    scale_color_manual(values = c("dodgerblue4","darkorchid3",
                                  "red", "darkolivegreen", "goldenrod1")) 

GrƔfico em linha, loess (sem margem de erro)

ggplot(corrida, aes(data, percentual, colour= candidato)) + 
    geom_smooth(method = "loess", se = FALSE) + geom_point() + 
    xlab("") + ylab("") + scale_color_manual(values = c("dodgerblue4",
                    "darkorchid3","red", "darkolivegreen", "goldenrod1")) 

Grafico em ponto e linha, por instituto

ggplot(corrida, aes(data, percentual, colour = candidato)) + 
    geom_smooth(method = "loess", se = FALSE) + geom_point() + 
    xlab("") + ylab("") + scale_color_manual(values = c("dodgerblue4",
    "darkorchid3","red", "darkolivegreen", "goldenrod1")) + 
    facet_wrap(~instituto)

3. GrÔficos para dados categóricos

3.1 Barra para uma variƔvel

3.2 Barra para duas variƔveis

3.3 Mosaicplot

3.1 GrÔfico com uma varível categórica

GrƔfico de barra bƔsico

library(openintro)
dados <- table(hsb2$race)
dados
## 
## african american            asian         hispanic            white 
##               20               11               24              145

GrƔfico de barra bƔsico

barplot(dados)

GrƔfico de barra bƔsico (horizontal)

barplot(dados, main = "GrƔfico de barra, horizontal",
        xlab = "Frequência", ylab = "Religião", horiz = TRUE)

GrƔfico de barra

ggplot(hsb2, aes(x = race)) + geom_bar() 

GrƔfico de barra (cor)

ggplot(hsb2, aes(x = race, fill = race)) + geom_bar()

GrƔfico de barra (horizontal)

ggplot(hsb2, aes(x = race, fill = race)) + geom_bar() + 
    coord_flip() + guides(fill = FALSE)

GrƔfico de barra (percentual)

Para fazer um grƔfico percentual tem que carregar o pacote scales

library(scales)

GrƔfico de barra (percentual)

ggplot(hsb2, aes(x = race)) +  
    geom_bar(aes( y = (..count..)/sum(..count..))) +
    scale_y_continuous(labels = percent_format()) +
  labs(title = "RaƧa dos indivƭduos", x = "RaƧa", y = "")

3.2 GrÔfico de barra com duas variÔveis categóricas

Barras paralelas

ggplot(hsb2, aes(x = race, fill = gender)) + geom_bar(position = "dodge")

Barra paralelas (%)

ggplot(hsb2, aes(x = race, fill = gender)) +  
    geom_bar(aes( y = (..count..)/sum(..count..)), position = "dodge") +
    scale_y_continuous(labels = percent_format())

Barra paralelas (%) e em tons pastƩis

ggplot(hsb2, aes(x = race, fill = gender)) +  
    geom_bar(aes( y = (..count..)/sum(..count..)), position = "dodge") +
    scale_y_continuous(labels = percent_format()) +
    labs(title = "", x = "", y = "") + scale_fill_brewer(palette = "Pastel1")

Barras segmentadas

ggplot(hsb2, aes(x = race, fill = gender)) +  
geom_bar(aes( y = (..count..)/sum(..count..)), position = "stack", 
colour = "black") + scale_y_continuous(labels = percent_format()) +
labs(title = "", x = "", y = "") + scale_fill_brewer(palette = "Pastel1")

Barras segmentadas (100% na coluna)

ggplot(hsb2, aes(x = race, fill = gender)) +  
geom_bar(aes( y = (..count..)/sum(..count..)), position = "fill") +
scale_y_continuous(labels = percent_format()) +
labs(title = "", x = "", y = "") + scale_fill_brewer(palette = "Pastel1") 

3.3 Mosaicplot

GrƔfico mosaico: pacote vcd

library(vcd)
mosaic(~Class + Survived, data = Titanic, legend = TRUE)

Masaico com mais variƔveis e cores

library(vcd)
mosaic(~Class + Sex + Age+ Survived , data =  Titanic, shade = TRUE, legend = TRUE)

Exercicio

  • FaƧa um mosaicplot com a relação entre a faixa de renda e as regiƵes do Brasil (dataset: presidente2010_curso)

Resposta

mosaic(~ regiao + idh5_2010, data = presidente2010_curso, shade = TRUE, legend = TRUE )

Extra: Miscelâneas

Como mudar o fundo: branco com grid

ggplot(hsb2, aes(x = race, fill = race)) + geom_bar() + theme_bw()

Como mudar o fundo: branco

ggplot(hsb2, aes(x = race, fill = race)) + geom_bar() +  theme_classic() 

Mudar as cores das barras

ggplot(hsb2, aes(x = race, fill = race)) + geom_bar() +scale_fill_brewer(palette="Oranges")

Mais uma opção de cor

library(ggthemes)
ggplot(hsb2, aes(x = race, fill = race)) + geom_bar() + scale_fill_brewer()

    theme_economist()
## List of 41
##  $ line                :List of 4
##   ..$ colour  : chr "black"
##   ..$ size    : num 0.5
##   ..$ linetype: num 1
##   ..$ lineend : chr "butt"
##   ..- attr(*, "class")= chr [1:2] "element_line" "element"
##  $ rect                :List of 4
##   ..$ fill    : Named chr "#d5e4eb"
##   .. ..- attr(*, "names")= chr "ebg"
##   ..$ colour  : logi NA
##   ..$ size    : num 0.5
##   ..$ linetype: num 1
##   ..- attr(*, "class")= chr [1:2] "element_rect" "element"
##  $ text                :List of 8
##   ..$ family    : chr "sans"
##   ..$ face      : chr "plain"
##   ..$ colour    : chr "black"
##   ..$ size      : num 10
##   ..$ hjust     : num 0.5
##   ..$ vjust     : num 0.5
##   ..$ angle     : num 0
##   ..$ lineheight: num 1
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.text           :List of 8
##   ..$ family    : NULL
##   ..$ face      : NULL
##   ..$ colour    : NULL
##   ..$ size      :Class 'rel'  num 1
##   ..$ hjust     : NULL
##   ..$ vjust     : NULL
##   ..$ angle     : NULL
##   ..$ lineheight: NULL
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.line           :List of 4
##   ..$ colour  : NULL
##   ..$ size    :Class 'rel'  num 0.8
##   ..$ linetype: NULL
##   ..$ lineend : NULL
##   ..- attr(*, "class")= chr [1:2] "element_line" "element"
##  $ axis.line.y         : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  $ axis.text.x         :List of 8
##   ..$ family    : NULL
##   ..$ face      : NULL
##   ..$ colour    : NULL
##   ..$ size      : NULL
##   ..$ hjust     : NULL
##   ..$ vjust     : num 1
##   ..$ angle     : NULL
##   ..$ lineheight: NULL
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.text.y         :List of 8
##   ..$ family    : NULL
##   ..$ face      : NULL
##   ..$ colour    : NULL
##   ..$ size      : NULL
##   ..$ hjust     : num 0
##   ..$ vjust     : NULL
##   ..$ angle     : NULL
##   ..$ lineheight: NULL
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.ticks          :List of 4
##   ..$ colour  : NULL
##   ..$ size    : NULL
##   ..$ linetype: NULL
##   ..$ lineend : NULL
##   ..- attr(*, "class")= chr [1:2] "element_line" "element"
##  $ axis.ticks.y        : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  $ axis.title          :List of 8
##   ..$ family    : NULL
##   ..$ face      : NULL
##   ..$ colour    : NULL
##   ..$ size      :Class 'rel'  num 1
##   ..$ hjust     : NULL
##   ..$ vjust     : NULL
##   ..$ angle     : NULL
##   ..$ lineheight: NULL
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.title.x        :List of 8
##   ..$ family    : NULL
##   ..$ face      : NULL
##   ..$ colour    : NULL
##   ..$ size      : NULL
##   ..$ hjust     : NULL
##   ..$ vjust     : NULL
##   ..$ angle     : NULL
##   ..$ lineheight: NULL
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.title.y        :List of 8
##   ..$ family    : NULL
##   ..$ face      : NULL
##   ..$ colour    : NULL
##   ..$ size      : NULL
##   ..$ hjust     : NULL
##   ..$ vjust     : NULL
##   ..$ angle     : num 90
##   ..$ lineheight: NULL
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.ticks.length   :Class 'unit'  atomic [1:1] -5
##   .. ..- attr(*, "unit")= chr "points"
##   .. ..- attr(*, "valid.unit")= int 8
##  $ axis.ticks.margin   :Class 'unit'  atomic [1:1] 12.5
##   .. ..- attr(*, "unit")= chr "points"
##   .. ..- attr(*, "valid.unit")= int 8
##  $ legend.background   :List of 4
##   ..$ fill    : NULL
##   ..$ colour  : NULL
##   ..$ size    : NULL
##   ..$ linetype: num 0
##   ..- attr(*, "class")= chr [1:2] "element_rect" "element"
##  $ legend.margin       :Class 'unit'  atomic [1:1] 15
##   .. ..- attr(*, "unit")= chr "points"
##   .. ..- attr(*, "valid.unit")= int 8
##  $ legend.key          :List of 4
##   ..$ fill    : NULL
##   ..$ colour  : NULL
##   ..$ size    : NULL
##   ..$ linetype: num 0
##   ..- attr(*, "class")= chr [1:2] "element_rect" "element"
##  $ legend.key.size     :Class 'unit'  atomic [1:1] 1.2
##   .. ..- attr(*, "unit")= chr "lines"
##   .. ..- attr(*, "valid.unit")= int 3
##  $ legend.key.height   : NULL
##  $ legend.key.width    : NULL
##  $ legend.text         :List of 8
##   ..$ family    : NULL
##   ..$ face      : NULL
##   ..$ colour    : NULL
##   ..$ size      :Class 'rel'  num 1.25
##   ..$ hjust     : NULL
##   ..$ vjust     : NULL
##   ..$ angle     : NULL
##   ..$ lineheight: NULL
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ legend.text.align   : NULL
##  $ legend.title        :List of 8
##   ..$ family    : NULL
##   ..$ face      : NULL
##   ..$ colour    : NULL
##   ..$ size      :Class 'rel'  num 1
##   ..$ hjust     : num 0
##   ..$ vjust     : NULL
##   ..$ angle     : NULL
##   ..$ lineheight: NULL
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ legend.title.align  : NULL
##  $ legend.position     : chr "top"
##  $ legend.direction    : NULL
##  $ legend.justification: chr "center"
##  $ panel.background    :List of 4
##   ..$ fill    : NULL
##   ..$ colour  : NULL
##   ..$ size    : NULL
##   ..$ linetype: num 0
##   ..- attr(*, "class")= chr [1:2] "element_rect" "element"
##  $ panel.border        : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  $ panel.grid.major    :List of 4
##   ..$ colour  : chr "white"
##   ..$ size    :Class 'rel'  num 1.75
##   ..$ linetype: NULL
##   ..$ lineend : NULL
##   ..- attr(*, "class")= chr [1:2] "element_line" "element"
##  $ panel.grid.minor    : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  $ panel.margin        :Class 'unit'  atomic [1:1] 0.25
##   .. ..- attr(*, "unit")= chr "lines"
##   .. ..- attr(*, "valid.unit")= int 3
##  $ strip.background    :List of 4
##   ..$ fill    : Named chr "#d5e4eb"
##   .. ..- attr(*, "names")= chr "ebg"
##   ..$ colour  : logi NA
##   ..$ size    : NULL
##   ..$ linetype: num 0
##   ..- attr(*, "class")= chr [1:2] "element_rect" "element"
##  $ strip.text          :List of 8
##   ..$ family    : NULL
##   ..$ face      : NULL
##   ..$ colour    : NULL
##   ..$ size      :Class 'rel'  num 1.25
##   ..$ hjust     : NULL
##   ..$ vjust     : NULL
##   ..$ angle     : NULL
##   ..$ lineheight: NULL
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ strip.text.x        :List of 8
##   ..$ family    : NULL
##   ..$ face      : NULL
##   ..$ colour    : NULL
##   ..$ size      : NULL
##   ..$ hjust     : NULL
##   ..$ vjust     : NULL
##   ..$ angle     : NULL
##   ..$ lineheight: NULL
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ strip.text.y        :List of 8
##   ..$ family    : NULL
##   ..$ face      : NULL
##   ..$ colour    : NULL
##   ..$ size      : NULL
##   ..$ hjust     : NULL
##   ..$ vjust     : NULL
##   ..$ angle     : num -90
##   ..$ lineheight: NULL
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ plot.background     :List of 4
##   ..$ fill    : Named chr "#d5e4eb"
##   .. ..- attr(*, "names")= chr "ebg"
##   ..$ colour  : logi NA
##   ..$ size    : NULL
##   ..$ linetype: NULL
##   ..- attr(*, "class")= chr [1:2] "element_rect" "element"
##  $ plot.title          :List of 8
##   ..$ family    : NULL
##   ..$ face      : chr "bold"
##   ..$ colour    : NULL
##   ..$ size      :Class 'rel'  num 1.5
##   ..$ hjust     : num 0
##   ..$ vjust     : NULL
##   ..$ angle     : NULL
##   ..$ lineheight: NULL
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ plot.margin         :Class 'unit'  atomic [1:4] 12 10 12 10
##   .. ..- attr(*, "unit")= chr "points"
##   .. ..- attr(*, "valid.unit")= int 8
##  $ panel.grid.major.x  : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  - attr(*, "class")= chr [1:2] "theme" "gg"
##  - attr(*, "complete")= logi TRUE

GrƔfico tipo stata

library(ggthemes)
ggplot(hsb2, aes(x = race, fill = race)) + geom_bar() + theme_stata() + scale_fill_stata()

ou Excel (depois de tanto esforƧo…)

library(ggthemes)
ggplot(hsb2, aes(x = race, fill = race)) + geom_bar() + theme_excel() +scale_fill_excel()

Um mapa dos municĆ­pios brasileiros no ggplot2

Anexo: Desafio O Globo

Refazer a imgem do jornal com ggplo2

Passo 1: criar o banco de dados

library("reshape2")
library("ggplot2")
library ("ggthemes")

sub19 <- c(5.0, 8.1, 8.7, 8.9, 10.2, 10.5)
quinze <- c(4.4, 7.3, 7.8, 8.0, 9.1, 9.5)
ano <- as.Date(c("1990-01-01", "2000-01-01", "2010-01-01", "2011-01-01",
                 "2012-01-01", "2013-01-01"))
jovens <- data.frame(ano, sub19, quinze)
test_data_long <- melt(jovens, id = "ano")  # convert para o formato long

O GrƔfico

ggplot(data = test_data_long, aes(x = ano, y = value, colour = variable)) +
    geom_line() + geom_point() + theme_bw()

O autor