Linguagens de Programação para Ciência de Dados

1 Leitura dos dados

Para explorar os recursos básicos de visualização, serão usados dados reais sobre a venda do modelo Renault Duster extraídos da WEB. Os dados estão disponíveis online em http://www.leg.ufpr.br/~walmes/data/duster_venda_260314.txt.

Os dados contém informações sobre o preço de venda (R$, valor) e distância percorrida (km, km) além de outras características descritoras do veículo, como ano de fabricação, cor, tipo de câmbio.

#-----------------------------------------------------------------------
# Dados de carros Duster à venda no webmotors em 26/03/2014.

# Importa a tabela de dados da web.
url <- "http://www.leg.ufpr.br/~walmes/data/duster_venda_260314.txt"
dus <- read.table(file = url,
                  header = TRUE,
                  sep = "\t",
                  encoding = "utf-8")
str(dus)
# 'data.frame': 699 obs. of  10 variables:
#  $ modelo: Factor w/ 11 levels "RENAULT DUSTER 1.6 4X2 16V FLEX 4P MANUAL",..: 3 1 2 2 1 1 2 3 6 2 ...
#  $ cor   : Factor w/ 9 levels "Azul","Branco",..: 5 1 5 5 5 8 6 6 6 6 ...
#  $ km    : int  31442 40800 56000 NA 45000 50000 44000 30000 41000 55000 ...
#  $ ano   : Factor w/ 7 levels "2011/2011","2011/2012",..: 2 2 2 2 2 4 3 4 2 2 ...
#  $ valor : num  41990 42500 42900 42990 43800 ...
#  $ cambio: Factor w/ 2 levels "AUTOMÁTICO","MANUAL": 2 2 2 2 2 2 2 2 2 2 ...
#  $ poten : num  1.6 1.6 1.6 1.6 1.6 1.6 1.6 1.6 2 1.6 ...
#  $ trac  : Factor w/ 2 levels "4X2","4X4": 1 1 1 1 1 1 1 1 1 1 ...
#  $ cat   : Factor w/ 5 levels " "," DYNAMIQUE ",..: 3 1 2 2 1 1 2 3 2 2 ...
#  $ novo  : Factor w/ 2 levels "novo","usado": 2 2 2 2 2 2 2 2 2 2 ...

# Cria ano do veículo com extração regex.
dus$ano <- factor(gsub(x = as.character(dus$ano),
                       pattern = "/\\d{4}$",
                       replacement = ""))

# Quantidade de NA em cada coluna.
apply(dus, MARGIN = 2, FUN = function(x) sum(is.na(x)))
# modelo    cor     km    ano  valor cambio  poten   trac    cat   novo 
#      0      0    132      0      0      0      0      0      0      0

#-----------------------------------------------------------------------
# Carrega o pacote `lattice` e `latticeExtra`.

library(lattice)
library(latticeExtra)
# Loading required package: RColorBrewer

ls("package:lattice")
#   [1] "as.factorOrShingle"           "as.shingle"                  
#   [3] "axis.default"                 "banking"                     
#   [5] "barchart"                     "barley"                      
#   [7] "bwplot"                       "canonical.theme"             
#   [9] "cloud"                        "col.whitebg"                 
#  [11] "contourplot"                  "current.column"              
#  [13] "current.panel.limits"         "current.row"                 
#  [15] "densityplot"                  "diag.panel.splom"            
#  [17] "do.breaks"                    "dotplot"                     
#  [19] "draw.colorkey"                "draw.key"                    
#  [21] "environmental"                "equal.count"                 
#  [23] "ethanol"                      "histogram"                   
#  [25] "is.shingle"                   "larrows"                     
#  [27] "lattice.getOption"            "lattice.options"             
#  [29] "latticeParseFormula"          "level.colors"                
#  [31] "levelplot"                    "llines"                      
#  [33] "lplot.xy"                     "lpoints"                     
#  [35] "lpolygon"                     "lrect"                       
#  [37] "lsegments"                    "ltext"                       
#  [39] "ltransform3dMatrix"           "ltransform3dto3d"            
#  [41] "make.groups"                  "melanoma"                    
#  [43] "oneway"                       "packet.number"               
#  [45] "packet.panel.default"         "panel.3dscatter"             
#  [47] "panel.3dwire"                 "panel.abline"                
#  [49] "panel.arrows"                 "panel.average"               
#  [51] "panel.axis"                   "panel.barchart"              
#  [53] "panel.brush.splom"            "panel.bwplot"                
#  [55] "panel.cloud"                  "panel.contourplot"           
#  [57] "panel.curve"                  "panel.densityplot"           
#  [59] "panel.dotplot"                "panel.error"                 
#  [61] "panel.fill"                   "panel.grid"                  
#  [63] "panel.histogram"              "panel.identify"              
#  [65] "panel.identify.cloud"         "panel.identify.qqmath"       
#  [67] "panel.levelplot"              "panel.levelplot.raster"      
#  [69] "panel.linejoin"               "panel.lines"                 
#  [71] "panel.link.splom"             "panel.lmline"                
#  [73] "panel.loess"                  "panel.mathdensity"           
#  [75] "panel.number"                 "panel.pairs"                 
#  [77] "panel.parallel"               "panel.points"                
#  [79] "panel.polygon"                "panel.qq"                    
#  [81] "panel.qqmath"                 "panel.qqmathline"            
#  [83] "panel.rect"                   "panel.refline"               
#  [85] "panel.rug"                    "panel.segments"              
#  [87] "panel.smoothScatter"          "panel.spline"                
#  [89] "panel.splom"                  "panel.stripplot"             
#  [91] "panel.superpose"              "panel.superpose.2"           
#  [93] "panel.superpose.plain"        "panel.text"                  
#  [95] "panel.tmd.default"            "panel.tmd.qqmath"            
#  [97] "panel.violin"                 "panel.wireframe"             
#  [99] "panel.xyplot"                 "parallel"                    
# [101] "parallelplot"                 "prepanel.default.bwplot"     
# [103] "prepanel.default.cloud"       "prepanel.default.densityplot"
# [105] "prepanel.default.histogram"   "prepanel.default.levelplot"  
# [107] "prepanel.default.parallel"    "prepanel.default.qq"         
# [109] "prepanel.default.qqmath"      "prepanel.default.splom"      
# [111] "prepanel.default.xyplot"      "prepanel.lmline"             
# [113] "prepanel.loess"               "prepanel.qqmathline"         
# [115] "prepanel.spline"              "prepanel.tmd.default"        
# [117] "prepanel.tmd.qqmath"          "qq"                          
# [119] "qqmath"                       "rfs"                         
# [121] "Rows"                         "shingle"                     
# [123] "show.settings"                "simpleKey"                   
# [125] "simpleTheme"                  "singer"                      
# [127] "splom"                        "standard.theme"              
# [129] "strip.custom"                 "strip.default"               
# [131] "stripplot"                    "tmd"                         
# [133] "trellis.currentLayout"        "trellis.device"              
# [135] "trellis.focus"                "trellis.grobname"            
# [137] "trellis.last.object"          "trellis.panelArgs"           
# [139] "trellis.par.get"              "trellis.par.set"             
# [141] "trellis.switchFocus"          "trellis.unfocus"             
# [143] "trellis.vpname"               "USMortality"                 
# [145] "USRegionalMortality"          "which.packet"                
# [147] "wireframe"                    "xscale.components.default"   
# [149] "xyplot"                       "xyplot.ts"                   
# [151] "yscale.components.default"
ls("package:latticeExtra")
#  [1] "ancestry"                     "as.layer"                    
#  [3] "asTheEconomist"               "axis.grid"                   
#  [5] "biocAccess"                   "combineLimits"               
#  [7] "custom.theme"                 "custom.theme.2"              
#  [9] "dendrogramGrob"               "doubleYScale"                
# [11] "drawLayer"                    "EastAuClimate"               
# [13] "ecdfplot"                     "flattenPanel"                
# [15] "ggplot2like"                  "ggplot2like.opts"            
# [17] "glayer"                       "glayer_"                     
# [19] "gvhd10"                       "horizonplot"                 
# [21] "layer"                        "layer_"                      
# [23] "mapplot"                      "marginal.plot"               
# [25] "mergedTrellisLegendGrob"      "panel.2dsmoother"            
# [27] "panel.3dbars"                 "panel.3dpolygon"             
# [29] "panel.3dtext"                 "panel.ablineq"               
# [31] "panel.ecdfplot"               "panel.ellipse"               
# [33] "panel.horizonplot"            "panel.key"                   
# [35] "panel.levelplot.points"       "panel.lmlineq"               
# [37] "panel.mapplot"                "panel.qqmath.tails"          
# [39] "panel.qqmath.xyarea"          "panel.quantile"              
# [41] "panel.rootogram"              "panel.scaleArrow"            
# [43] "panel.segplot"                "panel.smoother"              
# [45] "panel.tskernel"               "panel.voronoi"               
# [47] "panel.xblocks"                "panel.xyarea"                
# [49] "postdoc"                      "prepanel.ecdfplot"           
# [51] "prepanel.horizonplot"         "prepanel.mapplot"            
# [53] "prepanel.rootogram"           "prepanel.segplot"            
# [55] "resizePanels"                 "rootogram"                   
# [57] "SeatacWeather"                "segplot"                     
# [59] "simpleSmoothTs"               "theEconomist.axis"           
# [61] "theEconomist.opts"            "theEconomist.theme"          
# [63] "tileplot"                     "USAge.df"                    
# [65] "USAge.table"                  "USCancerRates"               
# [67] "useOuterStrips"               "xscale.components.fractions" 
# [69] "xscale.components.log"        "xscale.components.log10.3"   
# [71] "xscale.components.log10ticks" "xscale.components.logpower"  
# [73] "xscale.components.subticks"   "xyplot.list"                 
# [75] "yscale.components.fractions"  "yscale.components.log"       
# [77] "yscale.components.log10.3"    "yscale.components.log10ticks"
# [79] "yscale.components.logpower"   "yscale.components.subticks"

funs <- c(ls("package:lattice"), ls("package:latticeExtra"))

# Funções de alto nível.
c(grep(x = funs, pattern = "^[^.]+plot$", value = TRUE),
  c("histogram", "wireframe", "splom", "qqmath"))
#  [1] "bwplot"       "contourplot"  "densityplot"  "dotplot"     
#  [5] "levelplot"    "parallelplot" "stripplot"    "xyplot"      
#  [9] "ecdfplot"     "horizonplot"  "mapplot"      "segplot"     
# [13] "tileplot"     "histogram"    "wireframe"    "splom"       
# [17] "qqmath"

# Funções de baixo nível.
grep(x = funs, pattern = "^panel\\.", value = TRUE)
#  [1] "panel.3dscatter"        "panel.3dwire"          
#  [3] "panel.abline"           "panel.arrows"          
#  [5] "panel.average"          "panel.axis"            
#  [7] "panel.barchart"         "panel.brush.splom"     
#  [9] "panel.bwplot"           "panel.cloud"           
# [11] "panel.contourplot"      "panel.curve"           
# [13] "panel.densityplot"      "panel.dotplot"         
# [15] "panel.error"            "panel.fill"            
# [17] "panel.grid"             "panel.histogram"       
# [19] "panel.identify"         "panel.identify.cloud"  
# [21] "panel.identify.qqmath"  "panel.levelplot"       
# [23] "panel.levelplot.raster" "panel.linejoin"        
# [25] "panel.lines"            "panel.link.splom"      
# [27] "panel.lmline"           "panel.loess"           
# [29] "panel.mathdensity"      "panel.number"          
# [31] "panel.pairs"            "panel.parallel"        
# [33] "panel.points"           "panel.polygon"         
# [35] "panel.qq"               "panel.qqmath"          
# [37] "panel.qqmathline"       "panel.rect"            
# [39] "panel.refline"          "panel.rug"             
# [41] "panel.segments"         "panel.smoothScatter"   
# [43] "panel.spline"           "panel.splom"           
# [45] "panel.stripplot"        "panel.superpose"       
# [47] "panel.superpose.2"      "panel.superpose.plain" 
# [49] "panel.text"             "panel.tmd.default"     
# [51] "panel.tmd.qqmath"       "panel.violin"          
# [53] "panel.wireframe"        "panel.xyplot"          
# [55] "panel.2dsmoother"       "panel.3dbars"          
# [57] "panel.3dpolygon"        "panel.3dtext"          
# [59] "panel.ablineq"          "panel.ecdfplot"        
# [61] "panel.ellipse"          "panel.horizonplot"     
# [63] "panel.key"              "panel.levelplot.points"
# [65] "panel.lmlineq"          "panel.mapplot"         
# [67] "panel.qqmath.tails"     "panel.qqmath.xyarea"   
# [69] "panel.quantile"         "panel.rootogram"       
# [71] "panel.scaleArrow"       "panel.segplot"         
# [73] "panel.smoother"         "panel.tskernel"        
# [75] "panel.voronoi"          "panel.xblocks"         
# [77] "panel.xyarea"

# Lista de itens que podem ser customizados.
str(trellis.par.get())
# List of 35
#  $ grid.pars        : list()
#  $ fontsize         :List of 2
#   ..$ text  : num 12
#   ..$ points: num 8
#  $ background       :List of 2
#   ..$ alpha: num 1
#   ..$ col  : chr "transparent"
#  $ panel.background :List of 1
#   ..$ col: chr "transparent"
#  $ clip             :List of 2
#   ..$ panel: chr "on"
#   ..$ strip: chr "on"
#  $ add.line         :List of 4
#   ..$ alpha: num 1
#   ..$ col  : chr "#000000"
#   ..$ lty  : num 1
#   ..$ lwd  : num 1
#  $ add.text         :List of 5
#   ..$ alpha     : num 1
#   ..$ cex       : num 1
#   ..$ col       : chr "#000000"
#   ..$ font      : num 1
#   ..$ lineheight: num 1.2
#  $ plot.polygon     :List of 5
#   ..$ alpha : num 1
#   ..$ col   : chr "#00ffff"
#   ..$ border: chr "black"
#   ..$ lty   : num 1
#   ..$ lwd   : num 1
#  $ box.dot          :List of 5
#   ..$ alpha: num 1
#   ..$ col  : chr "#000000"
#   ..$ cex  : num 1
#   ..$ font : num 1
#   ..$ pch  : num 16
#  $ box.rectangle    :List of 5
#   ..$ alpha: num 1
#   ..$ col  : chr "#0080ff"
#   ..$ fill : chr "transparent"
#   ..$ lty  : num 1
#   ..$ lwd  : num 1
#  $ box.umbrella     :List of 4
#   ..$ alpha: num 1
#   ..$ col  : chr "#0080ff"
#   ..$ lty  : num 2
#   ..$ lwd  : num 1
#  $ dot.line         :List of 4
#   ..$ alpha: num 1
#   ..$ col  : chr "#e6e6e6"
#   ..$ lty  : num 1
#   ..$ lwd  : num 1
#  $ dot.symbol       :List of 5
#   ..$ alpha: num 1
#   ..$ cex  : num 0.8
#   ..$ col  : chr "#0080ff"
#   ..$ font : num 1
#   ..$ pch  : num 16
#  $ plot.line        :List of 4
#   ..$ alpha: num 1
#   ..$ col  : chr "#0080ff"
#   ..$ lty  : num 1
#   ..$ lwd  : num 1
#  $ plot.symbol      :List of 6
#   ..$ alpha: num 1
#   ..$ cex  : num 0.8
#   ..$ col  : chr "#0080ff"
#   ..$ font : num 1
#   ..$ pch  : num 1
#   ..$ fill : chr "transparent"
#  $ reference.line   :List of 4
#   ..$ alpha: num 1
#   ..$ col  : chr "#e6e6e6"
#   ..$ lty  : num 1
#   ..$ lwd  : num 1
#  $ strip.background :List of 2
#   ..$ alpha: num 1
#   ..$ col  : chr [1:7] "#ffe5cc" "#ccffcc" "#ccffff" "#cce6ff" ...
#  $ strip.shingle    :List of 2
#   ..$ alpha: num 1
#   ..$ col  : chr [1:7] "#ff7f00" "#00ff00" "#00ffff" "#0080ff" ...
#  $ strip.border     :List of 4
#   ..$ alpha: num 1
#   ..$ col  : chr [1:7] "#000000" "#000000" "#000000" "#000000" ...
#   ..$ lty  : num [1:7] 1 1 1 1 1 1 1
#   ..$ lwd  : num [1:7] 1 1 1 1 1 1 1
#  $ superpose.line   :List of 4
#   ..$ alpha: num 1
#   ..$ col  : chr [1:7] "#0080ff" "#ff00ff" "darkgreen" "#ff0000" ...
#   ..$ lty  : num [1:7] 1 1 1 1 1 1 1
#   ..$ lwd  : num [1:7] 1 1 1 1 1 1 1
#  $ superpose.symbol :List of 6
#   ..$ alpha: num [1:7] 1 1 1 1 1 1 1
#   ..$ cex  : num [1:7] 0.8 0.8 0.8 0.8 0.8 0.8 0.8
#   ..$ col  : chr [1:7] "#0080ff" "#ff00ff" "darkgreen" "#ff0000" ...
#   ..$ fill : chr [1:7] "#CCFFFF" "#FFCCFF" "#CCFFCC" "#FFE5CC" ...
#   ..$ font : num [1:7] 1 1 1 1 1 1 1
#   ..$ pch  : num [1:7] 1 1 1 1 1 1 1
#  $ superpose.polygon:List of 5
#   ..$ alpha : num [1:7] 1 1 1 1 1 1 1
#   ..$ col   : chr [1:7] "#CCFFFF" "#FFCCFF" "#CCFFCC" "#FFE5CC" ...
#   ..$ border: chr [1:7] "black" "black" "black" "black" ...
#   ..$ lty   : num [1:7] 1 1 1 1 1 1 1
#   ..$ lwd   : num [1:7] 1 1 1 1 1 1 1
#  $ regions          :List of 2
#   ..$ alpha: num 1
#   ..$ col  : chr [1:100] "#FF80FFFF" "#FF82FFFF" "#FF85FFFF" "#FF87FFFF" ...
#  $ shade.colors     :List of 2
#   ..$ alpha  : num 1
#   ..$ palette:function (irr, ref, height, saturation = 0.9)  
#  $ axis.line        :List of 4
#   ..$ alpha: num 1
#   ..$ col  : chr "#000000"
#   ..$ lty  : num 1
#   ..$ lwd  : num 1
#  $ axis.text        :List of 5
#   ..$ alpha     : num 1
#   ..$ cex       : num 0.8
#   ..$ col       : chr "#000000"
#   ..$ font      : num 1
#   ..$ lineheight: num 1
#  $ axis.components  :List of 4
#   ..$ left  :List of 3
#   .. ..$ tck : num 1
#   .. ..$ pad1: num 1
#   .. ..$ pad2: num 1
#   ..$ top   :List of 3
#   .. ..$ tck : num 1
#   .. ..$ pad1: num 1
#   .. ..$ pad2: num 1
#   ..$ right :List of 3
#   .. ..$ tck : num 1
#   .. ..$ pad1: num 1
#   .. ..$ pad2: num 1
#   ..$ bottom:List of 3
#   .. ..$ tck : num 1
#   .. ..$ pad1: num 1
#   .. ..$ pad2: num 1
#  $ layout.heights   :List of 19
#   ..$ top.padding      : num 1
#   ..$ main             : num 1
#   ..$ main.key.padding : num 1
#   ..$ key.top          : num 1
#   ..$ xlab.top         : num 1
#   ..$ key.axis.padding : num 1
#   ..$ axis.top         : num 1
#   ..$ strip            : num 1
#   ..$ panel            : num 1
#   ..$ axis.panel       : num 1
#   ..$ between          : num 1
#   ..$ axis.bottom      : num 1
#   ..$ axis.xlab.padding: num 1
#   ..$ xlab             : num 1
#   ..$ xlab.key.padding : num 0
#   ..$ key.bottom       : num 1
#   ..$ key.sub.padding  : num 1
#   ..$ sub              : num 1
#   ..$ bottom.padding   : num 1
#  $ layout.widths    :List of 15
#   ..$ left.padding     : num 1
#   ..$ key.left         : num 1
#   ..$ key.ylab.padding : num 0
#   ..$ ylab             : num 1
#   ..$ ylab.axis.padding: num 1
#   ..$ axis.left        : num 1
#   ..$ axis.panel       : num 1
#   ..$ strip.left       : num 1
#   ..$ panel            : num 1
#   ..$ between          : num 1
#   ..$ axis.right       : num 1
#   ..$ axis.key.padding : num 1
#   ..$ ylab.right       : num 1
#   ..$ key.right        : num 1
#   ..$ right.padding    : num 1
#  $ box.3d           :List of 4
#   ..$ alpha: num 1
#   ..$ col  : chr "#000000"
#   ..$ lty  : num 1
#   ..$ lwd  : num 1
#  $ par.xlab.text    :List of 5
#   ..$ alpha     : num 1
#   ..$ cex       : num 1
#   ..$ col       : chr "#000000"
#   ..$ font      : num 1
#   ..$ lineheight: num 1
#  $ par.ylab.text    :List of 5
#   ..$ alpha     : num 1
#   ..$ cex       : num 1
#   ..$ col       : chr "#000000"
#   ..$ font      : num 1
#   ..$ lineheight: num 1
#  $ par.zlab.text    :List of 5
#   ..$ alpha     : num 1
#   ..$ cex       : num 1
#   ..$ col       : chr "#000000"
#   ..$ font      : num 1
#   ..$ lineheight: num 1
#  $ par.main.text    :List of 5
#   ..$ alpha     : num 1
#   ..$ cex       : num 1.2
#   ..$ col       : chr "#000000"
#   ..$ font      : num 2
#   ..$ lineheight: num 1
#  $ par.sub.text     :List of 5
#   ..$ alpha     : num 1
#   ..$ cex       : num 1
#   ..$ col       : chr "#000000"
#   ..$ font      : num 2
#   ..$ lineheight: num 1

2 Gráficos para uma variável categórica

#-----------------------------------------------------------------------
# Gráfico de barras e setores.

# Tabela de frequência.
x <- xtabs(~cambio, data = dus)
class(x)
# [1] "xtabs" "table"

# Gráfico padrão.
barchart(x,
         horizontal = FALSE,
         xlab = "Tipo de câmbio",
         ylab = "Frequência absoluta")


# A lattice também trabalha com fórmulas.
tb <- as.data.frame(x)

# CUIDADO: a origem desse gráfico não é o zero!
barchart(Freq ~ cambio,
         data = tb,
         xlab = "Tipo de câmbio",
         ylab = "Frequência absoluta",
         col = c("seagreen", "yellowgreen"))


barchart(Freq ~ cambio,
         data = tb,
         origin = 0, # <-- ATENÇÃO.
         xlab = "Tipo de câmbio",
         ylab = "Frequência absoluta",
         col = c("seagreen", "yellowgreen"))

Deve-se ter cuidado com a refência das barras. O argumento origin = permite especificar a origem.

# Para as cores do carro.
x <- xtabs(~cor, data = dus)
levels(dus$cor)
# [1] "Azul"       "Branco"     "Cinza"      "Indefinida" "Prata"     
# [6] "Preto"      "Verde"      "Vermelho"   "Vinho"

tb <- as.data.frame(x)
tb
#          cor Freq
# 1       Azul   14
# 2     Branco  193
# 3      Cinza   30
# 4 Indefinida    7
# 5      Prata  223
# 6      Preto  155
# 7      Verde   58
# 8   Vermelho   18
# 9      Vinho    1

# Vetor que cores para usar com cada cor de veiculo.
cols <- c("blue", "white", "gray50", "Yellow", "gray90", "black",
          "green4", "red", "red4")

cbind(levels(dus$cor), cols)
#                    cols    
#  [1,] "Azul"       "blue"  
#  [2,] "Branco"     "white" 
#  [3,] "Cinza"      "gray50"
#  [4,] "Indefinida" "Yellow"
#  [5,] "Prata"      "gray90"
#  [6,] "Preto"      "black" 
#  [7,] "Verde"      "green4"
#  [8,] "Vermelho"   "red"   
#  [9,] "Vinho"      "red4"

# Com anotação sobre as barras.
barchart(Freq ~ reorder(cor, -Freq),
         data = tb,
         origin = 0,
         col = cols,
         xlab = "Cores",
         ylab = "Frequência absoluta") +
    layer({
        panel.text(x = x, y = y, pos = 3, label = y)
    })

3 Gráfico para duas variáveis categóricas

#-----------------------------------------------------------------------
# Gráficos de barras emplilhadas (stacked) e lado a lado.

x <- xtabs(~cambio + ano, data = dus)
x
#             ano
# cambio       2011 2012 2013 2014
#   AUTOMÁTICO   51   40  100    4
#   MANUAL       88  204  180   32

cols <- c("#660d32", "#bc1a5e")

# Barras empilhadas.
barchart(x,
         xlab = "Ano",
         stack = TRUE,
         auto.key = TRUE,
         ylab = "Frequência absoluta")


# Barras lado a lado.
barchart(x,
         xlab = "Ano",
         stack = FALSE,
         horizontal = FALSE,
         auto.key = list(space = "right"),
         ylab = "Frequência absoluta")


tb <- as.data.frame(x)
tb
#       cambio  ano Freq
# 1 AUTOMÁTICO 2011   51
# 2     MANUAL 2011   88
# 3 AUTOMÁTICO 2012   40
# 4     MANUAL 2012  204
# 5 AUTOMÁTICO 2013  100
# 6     MANUAL 2013  180
# 7 AUTOMÁTICO 2014    4
# 8     MANUAL 2014   32

barchart(Freq ~ ano,
         groups = cambio,
         auto.key = list(space = "right", title = "Ano"),
         data = tb,
         origin = 0,
         xlab = "Câmbio",
         ylab = "Frequência absoluta")


cols <- c("#07B1FF", "#0CE8BB", "#00FF40", "#BEE80C")
barchart(Freq ~ cambio,
         groups = ano,
         auto.key = list(space = "right", title = "Ano"),
         data = tb,
         origin = 0,
         xlab = "Ano",
         ylab = "Frequência absoluta",
         par.settings = list(superpose.polygon = list(col = cols)))


#-----------------------------------------------------------------------
# Anotações nas barras.

cols <- c("#07B1FF", "#0CE8BB", "#00FF40", "#BEE80C")
barchart(Freq ~ cambio,
         groups = ano,
         auto.key = list(corner = c(0, 1), title = "Ano"),
         data = tb,
         origin = 0,
         xlab = "Ano",
         ylab = "Frequência absoluta",
         par.settings = list(superpose.polygon = list(col = cols))) +
    layer({
        # print(ls()) # Descomente para ver os objetos do escopo.
        g <- scale(as.integer(groups)/(nlevels(groups) + box.ratio),
                   scale = FALSE)
        print(g)
        panel.text(x = as.integer(x) + g, y = y, pos = 3, label = y)
    }) +
    layer({
        panel.abline(h = seq(0, 200, by = 25),
                     lty = 2,
                     col = "gray50")
    }, under = TRUE)

#             [,1]
# [1,] -0.25000000
# [2,] -0.25000000
# [3,] -0.08333333
# [4,] -0.08333333
# [5,]  0.08333333
# [6,]  0.08333333
# [7,]  0.25000000
# [8,]  0.25000000
# attr(,"scaled:center")
# [1] 0.4166667
# Mais dimensões.
x <- xtabs(~cambio + ano + cor, data = dus)

tb <- as.data.frame(x)
head(tb)
#       cambio  ano  cor Freq
# 1 AUTOMÁTICO 2011 Azul    4
# 2     MANUAL 2011 Azul    3
# 3 AUTOMÁTICO 2012 Azul    0
# 4     MANUAL 2012 Azul    6
# 5 AUTOMÁTICO 2013 Azul    0
# 6     MANUAL 2013 Azul    1

barchart(Freq ~ ano | cor,
         groups = cambio,
         auto.key = list(columns = 2, title = "Câmbio", cex.title = 1.1),
         data = tb,
         origin = 0,
         xlab = "Ano",
         ylab = "Frequência absoluta",
         par.settings = list(superpose.polygon = list(col = cols)))


barchart(Freq ~ ano | cor,
         groups = cambio,
         auto.key = list(columns = 2, title = "Câmbio", cex.title = 1.1),
         data = tb,
         origin = 0,
         xlab = "Ano",
         ylab = "Frequência absoluta",
         scales = list(y = list(relation = "free")),
         par.settings = list(superpose.polygon = list(col = cols)))

4 Gráficos para uma variável contínua

#-----------------------------------------------------------------------
# Histograma.

# Gráfico básico.
# hist(dus$valor)

histogram(~valor,
          data = dus,
          xlab = "Preço de venda (R$)",
          ylab = "Frequência relativa",
          col = "orange") +
    layer(panel.rug(x, col = 1))


# Se breaks é um escalar então entende-se que é uma *sugestão* para o
# número de clases.
histogram(~valor,
          data = dus,
          breaks = 15,
          type = c("percent", "count", "density")[2],
          xlab = "Preço de venda (R$)",
          ylab = "Frequência absoluta",
          col = "orange") +
    layer(panel.rug(x, col = 1))


# Se breaks é um vetor então entende-se que são os limites para
# classificação dos valores.
histogram(~valor,
          data = dus,
          breaks = seq(35000, 75000, by = 2500),
          type = c("percent", "count", "density")[2],
          xlab = "Preço de venda (R$)",
          ylab = "Frequência absoluta",
          col = "orange") +
    layer(panel.rug(x, col = 1))


# Gráfico onde a altura é a densidade e não a frequência.
histogram(~valor,
          data = dus,
          type = c("percent", "count", "density")[3],
          xlab = "Preço de venda (R$)",
          ylab = "Frequência absoluta",
          col = "#ba6dff") +
    layer(panel.rug(x, col = 1))

#-----------------------------------------------------------------------
# Gráficos de densidade.

densityplot(~valor,
            data = dus,
            kernel = "rectangular",
            bw = 2000,
            xlab = "Preço de venda (R$)",
            ylab = "Frequência absoluta",
            # plot.points = c("jitter", "rug")[2],
            plot.points = FALSE,
            col = "#ba6dff") +
    layer({
        panel.rug(x, col = 1)
    })


densityplot(~valor,
            groups = cambio,
            auto.key = list(corner = c(0.95, 0.95)),
            data = dus,
            xlab = "Preço de venda (R$)",
            ylab = "Frequência absoluta",
            plot.points = "jitter")


densityplot(~valor | ano,
            groups = cambio,
            auto.key = list(corner = c(0.05, 0.95)),
            data = dus,
            xlab = "Preço de venda (R$)",
            ylab = "Frequência absoluta",
            plot.points = "jitter")

#-----------------------------------------------------------------------
# Gráfico de frequência acumulada empírica.

# Gráfico onde a altura é a densidade e não a frequência.
ecdfplot(~valor,
         data = dus,
         xlab = "Preço de venda (R$)",
         ylab = "Frequência acumulada",
         col = "#ba6dff") +
    layer({
        panel.rug(x, col = 1)
    })


ecdfplot(~valor,
         groups = cambio,
         auto.key = list(corner = c(0.05, 0.8)),
         data = dus,
         xlab = "Preço de venda (R$)",
         ylab = "Frequência acumulada")


ecdfplot(~valor | ano,
         groups = cambio,
         auto.key = list(corner = c(0.05, 0.85)),
         data = dus,
         xlab = "Preço de venda (R$)",
         ylab = "Frequência acumulada")

5 Gráfico para duas variáveis contínuas

#-----------------------------------------------------------------------
# Diagrama de dispersão.

# Diagrama de dispersão básico.
xyplot(valor ~ km, data = dus)


# Adicionar uma linha de tendência suave.
xyplot(valor ~ km,
       data = dus,
       type = c("p", "smooth"))


xyplot(valor ~ km, data = dus) +
    layer({
        panel.smoother(x, y)
    })


# Usar cores diferentes para identificar o tipo de câmbio.
xyplot(valor ~ km,
       groups = cambio,
       auto.key = TRUE,
       data = dus)


# Adicionar uma linha de tendência suave.
xyplot(valor ~ km,
       groups = cambio,
       auto.key = TRUE,
       data = dus) +
    glayer({
        panel.smoother(x = x, y = y, col = col.line, span = 0.9)
    })


n <- head(names(sort(table(dus$cor), decreasing = TRUE)), n = 4)

xyplot(valor ~ km | cor,
       groups = cambio,
       auto.key = TRUE,
       data = subset(dus, cor %in% n)) +
    glayer({
        panel.smoother(x = x, y = y, col = col.line, span = 0.9)
    })

6 Gráfico para variável contínua e categórica

#-----------------------------------------------------------------------

# Preço em função dos anos.
bwplot(valor ~ ano, data = dus, pch = "|")


# Edita níveis do fator.
levels(dus$cat)
# [1] " "              " DYNAMIQUE "    " EXPRESSION "   " TECH ROAD "   
# [5] " TECH ROAD II "
levels(dus$cat) <- trimws(levels(dus$cat))
dus2 <- droplevels(subset(dus, cat != ""))
dus2 <- transform(dus2, valor = valor/1000, km = km/1000)

names(trellis.par.get())
#  [1] "grid.pars"         "fontsize"          "background"       
#  [4] "panel.background"  "clip"              "add.line"         
#  [7] "add.text"          "plot.polygon"      "box.dot"          
# [10] "box.rectangle"     "box.umbrella"      "dot.line"         
# [13] "dot.symbol"        "plot.line"         "plot.symbol"      
# [16] "reference.line"    "strip.background"  "strip.shingle"    
# [19] "strip.border"      "superpose.line"    "superpose.symbol" 
# [22] "superpose.polygon" "regions"           "shade.colors"     
# [25] "axis.line"         "axis.text"         "axis.components"  
# [28] "layout.heights"    "layout.widths"     "box.3d"           
# [31] "par.xlab.text"     "par.ylab.text"     "par.zlab.text"    
# [34] "par.main.text"     "par.sub.text"
str(trellis.par.get()$box.dot)
# List of 5
#  $ alpha: num 1
#  $ col  : chr "#000000"
#  $ cex  : num 1
#  $ font : num 1
#  $ pch  : num 16
str(trellis.par.get()$box.rectangle)
# List of 5
#  $ alpha: num 1
#  $ col  : chr "#0080ff"
#  $ fill : chr "transparent"
#  $ lty  : num 1
#  $ lwd  : num 1
str(trellis.par.get()$box.umbrella)
# List of 4
#  $ alpha: num 1
#  $ col  : chr "#0080ff"
#  $ lty  : num 2
#  $ lwd  : num 1

# Customização do gráfico.
bw_ps <- list(plot.symbol = list(col = 1),
              box.dot = list(pch = "|"),
              box.umbrella = list(col = 1, lty = 1),
              box.rectangle = list(col = 1, fill = "seagreen"))

bwplot(valor ~ cat,
       data = dus2,
       xlab = "Modelo",
       ylab = "Preço de venda (R$)",
       par.settings = bw_ps)


bwplot(valor ~ cat | ano,
       data = dus2,
       xlab = "Modelo",
       ylab = "Preço de venda (R$)",
       as.table = TRUE,
       par.settings = bw_ps)


# Indicação do valor da média.
bwplot(valor ~ cat,
       data = dus2,
       xlab = "Modelo",
       ylab = "Preço de venda (R$)",
       par.settings = bw_ps) +
    layer({
        # panel.xyplot(x = x, y = y, jitter.x = TRUE)
        m <- aggregate(y ~ x, FUN = mean)
        panel.points(x = m$x, y = m$y, col = "red", pch = 19)
    })


# Indicação do valor da média.
bwplot(valor ~ cat | cambio,
       data = dus2,
       xlab = "Modelo",
       ylab = "Preço de venda (R$)",
       par.settings = bw_ps) +
    layer({
        m <- aggregate(y ~ x, FUN = mean)
        panel.points(x = m$x, y = m$y, col = "red", pch = 19)
        fiv <- by(y, x, FUN = fivenum, simplify = FALSE)
        fiv <- do.call(cbind, fiv)
        aiq <- fiv[4, ] - fiv[2, ]
        l <- fiv[2, ] - 1.5 * aiq
        u <- fiv[4, ] + 1.5 * aiq
        i <- seq_along(u)
        panel.segments(x0 = i - 0.5, x1 = i + 0.5, y0 = l, y1 = l,
                       col = "gray50", lty = 3)
        panel.segments(x0 = i - 0.5, x1 = i + 0.5, y0 = u, y1 = u,
                       col = "gray50", lty = 3)
    })

25px