2018-05-08

Justificativa

  • Relatórios impressos são inanimados.
  • Relatórios para WEB permitem elementos reativos/animados.
    • Consulta ao banco de dados.
    • Atualização do conteúdo exibido.
    • Gráficos reativos.
    • GIFs/vídeos.
  • Elementos interativos na visualização de dados potencializam a absorção de informação.
  • Mas o uso incorreto por comprometer a compreensão ou afastar o leitor.

Objetivo

  • Apresentar pacotes no R para confecção de gráficos reativos.
    • Gráficos estatísticos tradicionais.
    • Dados geográficos (mapas).
    • Dados em rede de relacionamento (network).
    • Animações.

Gráficos tradicionais

Quais são

Quantidade de variáveis envolvidas:

  • Univariados.
  • Bivariados.
  • Multivariados.

Objetivo da visualização:

  • Para representar a distribuição dos valores/categorias.
  • Para representar a relação entre variáveis.
  • Para representar a conexão/fluxo entre variáveis/observações.

googleVis

Uso do googleVis

library(googleVis)
ls("package:googleVis")
##  [1] "Andrew"                "Cairo"                
##  [3] "CityPopularity"        "createGoogleGadget"   
##  [5] "dino"                  "Exports"              
##  [7] "Fruits"                "gvisAnnotatedTimeLine"
##  [9] "gvisAnnotationChart"   "gvisAreaChart"        
## [11] "gvisBarChart"          "gvisBubbleChart"      
## [13] "gvisCalendar"          "gvisCandlestickChart" 
## [15] "gvisColumnChart"       "gvisComboChart"       
## [17] "gvisGauge"             "gvisGeoChart"         
## [19] "gvisGeoMap"            "gvisHistogram"        
## [21] "gvisIntensityMap"      "gvisLineChart"        
## [23] "gvisMap"               "gvisMerge"            
## [25] "gvisMotionChart"       "gvisOrgChart"         
## [27] "gvisPieChart"          "gvisSankey"           
## [29] "gvisScatterChart"      "gvisSteppedAreaChart" 
## [31] "gvisTable"             "gvisTimeline"         
## [33] "gvisTreeMap"           "OpenClose"            
## [35] "Population"            "Regions"              
## [37] "renderGvis"            "Stock"

p <- gvisScatterChart(
    data = cars[, c("speed", "dist")],
    options = list(legend = "none",
                   lineWidth = 0,
                   pointSize = 1,
                   title = "Distância x Velocidade",
                   vAxis = "{title: 'Distância'}",
                   hAxis = "{title: 'Velocidade'}",
                   width = 700,
                   height = 500))
# Exibe uma página completa.
p
## <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
##   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
## <html xmlns="http://www.w3.org/1999/xhtml">
## <head>
## <title>ScatterChartID104452a3400</title>
## <meta http-equiv="content-type" content="text/html;charset=utf-8" />
## <style type="text/css">
## body {
##   color: #444444;
##   font-family: Arial,Helvetica,sans-serif;
##   font-size: 75%;
##   }
##   a {
##   color: #4D87C7;
##   text-decoration: none;
## }
## </style>
## </head>
## <body>
##  <!-- ScatterChart generated in R 3.4.4 by googleVis 0.6.2 package -->
## <!-- Tue May  8 20:25:07 2018 -->
## 
## 
## <!-- jsHeader -->
## <script type="text/javascript">
##  
## // jsData 
## function gvisDataScatterChartID104452a3400 () {
## var data = new google.visualization.DataTable();
## var datajson =
## [
##  [
## 4,
## 2
## ],
## [
## 4,
## 10
## ],
## [
## 7,
## 4
## ],
## [
## 7,
## 22
## ],
## [
## 8,
## 16
## ],
## [
## 9,
## 10
## ],
## [
## 10,
## 18
## ],
## [
## 10,
## 26
## ],
## [
## 10,
## 34
## ],
## [
## 11,
## 17
## ],
## [
## 11,
## 28
## ],
## [
## 12,
## 14
## ],
## [
## 12,
## 20
## ],
## [
## 12,
## 24
## ],
## [
## 12,
## 28
## ],
## [
## 13,
## 26
## ],
## [
## 13,
## 34
## ],
## [
## 13,
## 34
## ],
## [
## 13,
## 46
## ],
## [
## 14,
## 26
## ],
## [
## 14,
## 36
## ],
## [
## 14,
## 60
## ],
## [
## 14,
## 80
## ],
## [
## 15,
## 20
## ],
## [
## 15,
## 26
## ],
## [
## 15,
## 54
## ],
## [
## 16,
## 32
## ],
## [
## 16,
## 40
## ],
## [
## 17,
## 32
## ],
## [
## 17,
## 40
## ],
## [
## 17,
## 50
## ],
## [
## 18,
## 42
## ],
## [
## 18,
## 56
## ],
## [
## 18,
## 76
## ],
## [
## 18,
## 84
## ],
## [
## 19,
## 36
## ],
## [
## 19,
## 46
## ],
## [
## 19,
## 68
## ],
## [
## 20,
## 32
## ],
## [
## 20,
## 48
## ],
## [
## 20,
## 52
## ],
## [
## 20,
## 56
## ],
## [
## 20,
## 64
## ],
## [
## 22,
## 66
## ],
## [
## 23,
## 54
## ],
## [
## 24,
## 70
## ],
## [
## 24,
## 92
## ],
## [
## 24,
## 93
## ],
## [
## 24,
## 120
## ],
## [
## 25,
## 85
## ] 
## ];
## data.addColumn('number','speed');
## data.addColumn('number','dist');
## data.addRows(datajson);
## return(data);
## }
##  
## // jsDrawChart
## function drawChartScatterChartID104452a3400() {
## var data = gvisDataScatterChartID104452a3400();
## var options = {};
## options["allowHtml"] = true;
## options["legend"] = "none";
## options["lineWidth"] = 0;
## options["pointSize"] = 1;
## options["title"] = "Distância x Velocidade";
## options["vAxis"] = {title: 'Distância'};
## options["hAxis"] = {title: 'Velocidade'};
## options["width"] = 700;
## options["height"] = 500;
## 
## 
##     var chart = new google.visualization.ScatterChart(
##     document.getElementById('ScatterChartID104452a3400')
##     );
##     chart.draw(data,options);
##     
## 
## }
##   
##  
## // jsDisplayChart
## (function() {
## var pkgs = window.__gvisPackages = window.__gvisPackages || [];
## var callbacks = window.__gvisCallbacks = window.__gvisCallbacks || [];
## var chartid = "corechart";
##   
## // Manually see if chartid is in pkgs (not all browsers support Array.indexOf)
## var i, newPackage = true;
## for (i = 0; newPackage && i < pkgs.length; i++) {
## if (pkgs[i] === chartid)
## newPackage = false;
## }
## if (newPackage)
##   pkgs.push(chartid);
##   
## // Add the drawChart function to the global list of callbacks
## callbacks.push(drawChartScatterChartID104452a3400);
## })();
## function displayChartScatterChartID104452a3400() {
##   var pkgs = window.__gvisPackages = window.__gvisPackages || [];
##   var callbacks = window.__gvisCallbacks = window.__gvisCallbacks || [];
##   window.clearTimeout(window.__gvisLoad);
##   // The timeout is set to 100 because otherwise the container div we are
##   // targeting might not be part of the document yet
##   window.__gvisLoad = setTimeout(function() {
##   var pkgCount = pkgs.length;
##   google.load("visualization", "1", { packages:pkgs, callback: function() {
##   if (pkgCount != pkgs.length) {
##   // Race condition where another setTimeout call snuck in after us; if
##   // that call added a package, we must not shift its callback
##   return;
## }
## while (callbacks.length > 0)
## callbacks.shift()();
## } });
## }, 100);
## }
##  
## // jsFooter
## </script>
##  
## <!-- jsChart -->  
## <script type="text/javascript" src="https://www.google.com/jsapi?callback=displayChartScatterChartID104452a3400"></script>
##  
## <!-- divChart -->
##   
## <div id="ScatterChartID104452a3400" 
##   style="width: 700; height: 500;">
## </div>
##  <div><span>Data: cars[, c("speed", "dist")] &#8226; Chart ID: <a href="Chart_ScatterChartID104452a3400.html">ScatterChartID104452a3400</a> &#8226; <a href="https://github.com/mages/googleVis">googleVis-0.6.2</a></span><br /> 
## <!-- htmlFooter -->
## <span> 
##   R version 3.4.4 (2018-03-15) 
##   &#8226; <a href="https://developers.google.com/terms/">Google Terms of Use</a> &#8226; <a href="https://google-developers.appspot.com/chart/interactive/docs/gallery/scatterchart">Documentation and Data Policy</a>
## </span></div>
## </body>
## </html>

# getOption("gvis.tags")
# Configure o options() e use `results = "asis"` no chunk.
options(gvis.plot.tag = "chart")

# Para não exibir metadados.
# p$html$footer <- NULL
# p$html$caption <- NULL

# Exibe um fragmento HTML.
plot(p)
## <!-- ScatterChart generated in R 3.4.4 by googleVis 0.6.2 package -->
## <!-- Tue May  8 20:25:07 2018 -->
## 
## 
## <!-- jsHeader -->
## <script type="text/javascript">
##  
## // jsData 
## function gvisDataScatterChartID104452a3400 () {
## var data = new google.visualization.DataTable();
## var datajson =
## [
##  [
## 4,
## 2
## ],
## [
## 4,
## 10
## ],
## [
## 7,
## 4
## ],
## [
## 7,
## 22
## ],
## [
## 8,
## 16
## ],
## [
## 9,
## 10
## ],
## [
## 10,
## 18
## ],
## [
## 10,
## 26
## ],
## [
## 10,
## 34
## ],
## [
## 11,
## 17
## ],
## [
## 11,
## 28
## ],
## [
## 12,
## 14
## ],
## [
## 12,
## 20
## ],
## [
## 12,
## 24
## ],
## [
## 12,
## 28
## ],
## [
## 13,
## 26
## ],
## [
## 13,
## 34
## ],
## [
## 13,
## 34
## ],
## [
## 13,
## 46
## ],
## [
## 14,
## 26
## ],
## [
## 14,
## 36
## ],
## [
## 14,
## 60
## ],
## [
## 14,
## 80
## ],
## [
## 15,
## 20
## ],
## [
## 15,
## 26
## ],
## [
## 15,
## 54
## ],
## [
## 16,
## 32
## ],
## [
## 16,
## 40
## ],
## [
## 17,
## 32
## ],
## [
## 17,
## 40
## ],
## [
## 17,
## 50
## ],
## [
## 18,
## 42
## ],
## [
## 18,
## 56
## ],
## [
## 18,
## 76
## ],
## [
## 18,
## 84
## ],
## [
## 19,
## 36
## ],
## [
## 19,
## 46
## ],
## [
## 19,
## 68
## ],
## [
## 20,
## 32
## ],
## [
## 20,
## 48
## ],
## [
## 20,
## 52
## ],
## [
## 20,
## 56
## ],
## [
## 20,
## 64
## ],
## [
## 22,
## 66
## ],
## [
## 23,
## 54
## ],
## [
## 24,
## 70
## ],
## [
## 24,
## 92
## ],
## [
## 24,
## 93
## ],
## [
## 24,
## 120
## ],
## [
## 25,
## 85
## ] 
## ];
## data.addColumn('number','speed');
## data.addColumn('number','dist');
## data.addRows(datajson);
## return(data);
## }
##  
## // jsDrawChart
## function drawChartScatterChartID104452a3400() {
## var data = gvisDataScatterChartID104452a3400();
## var options = {};
## options["allowHtml"] = true;
## options["legend"] = "none";
## options["lineWidth"] = 0;
## options["pointSize"] = 1;
## options["title"] = "Distância x Velocidade";
## options["vAxis"] = {title: 'Distância'};
## options["hAxis"] = {title: 'Velocidade'};
## options["width"] = 700;
## options["height"] = 500;
## 
## 
##     var chart = new google.visualization.ScatterChart(
##     document.getElementById('ScatterChartID104452a3400')
##     );
##     chart.draw(data,options);
##     
## 
## }
##   
##  
## // jsDisplayChart
## (function() {
## var pkgs = window.__gvisPackages = window.__gvisPackages || [];
## var callbacks = window.__gvisCallbacks = window.__gvisCallbacks || [];
## var chartid = "corechart";
##   
## // Manually see if chartid is in pkgs (not all browsers support Array.indexOf)
## var i, newPackage = true;
## for (i = 0; newPackage && i < pkgs.length; i++) {
## if (pkgs[i] === chartid)
## newPackage = false;
## }
## if (newPackage)
##   pkgs.push(chartid);
##   
## // Add the drawChart function to the global list of callbacks
## callbacks.push(drawChartScatterChartID104452a3400);
## })();
## function displayChartScatterChartID104452a3400() {
##   var pkgs = window.__gvisPackages = window.__gvisPackages || [];
##   var callbacks = window.__gvisCallbacks = window.__gvisCallbacks || [];
##   window.clearTimeout(window.__gvisLoad);
##   // The timeout is set to 100 because otherwise the container div we are
##   // targeting might not be part of the document yet
##   window.__gvisLoad = setTimeout(function() {
##   var pkgCount = pkgs.length;
##   google.load("visualization", "1", { packages:pkgs, callback: function() {
##   if (pkgCount != pkgs.length) {
##   // Race condition where another setTimeout call snuck in after us; if
##   // that call added a package, we must not shift its callback
##   return;
## }
## while (callbacks.length > 0)
## callbacks.shift()();
## } });
## }, 100);
## }
##  
## // jsFooter
## </script>
##  
## <!-- jsChart -->  
## <script type="text/javascript" src="https://www.google.com/jsapi?callback=displayChartScatterChartID104452a3400"></script>
##  
## <!-- divChart -->
##   
## <div id="ScatterChartID104452a3400" 
##   style="width: 700; height: 500;">
## </div>

x <- boxplot(Sepal.Length ~ Species,
             data = iris,
             outline = FALSE,
             plot = FALSE)
x <- data.frame(t(x$stats[-3, ]))
names(x) <- c("Low", "Open", "Close", "High")
x <- cbind(Species = levels(iris$Species), x)

p <- gvisCandlestickChart(
    data = x,
    options = list(legend = "none",
                   hAxis = "{title:'Espécies'}",
                   vAxis = "{title:'Comprimento da pétala'}",
                   colors = "['#123654']",
                   width = 700,
                   height = 500))
plot(p)

br$População <- log10(br$População)
str(br)
## 'data.frame':    27 obs. of  2 variables:
##  $ Estado   : chr  "São Paulo" "Minas Gerais" "Rio de Janeiro" "Bahia" ...
##  $ População: num  7.65 7.32 7.22 7.18 7.05 ...
breaks <- seq(floor(min(br$População)),
              ceiling(max(br$População)),
              by = 0.5)

library(RColorBrewer)
pal <- brewer.pal(n = length(breaks), name = "Blues")

# Dicionário para os intervalos de classe e cores associadas.
cl <- sprintf("{values:[%s],\n colors:[%s]}",
              paste0(sprintf("'%0.1f'", breaks), collapse = ", "),
              paste0(sprintf("'%s'", pal), collapse = ", "))
cat(cl)
## {values:['5.0', '5.5', '6.0', '6.5', '7.0', '7.5', '8.0'],
##  colors:['#EFF3FF', '#C6DBEF', '#9ECAE1', '#6BAED6', '#4292C6', '#2171B5', '#084594']}

map <- gvisGeoChart(
    data = br,
    locationvar = "Estado",
    colorvar = "População",
    options = list(title = "lala",
                   region = "BR",
                   displayMode = "regions",
                   resolution = "provinces",
                   colorAxis = cl,
                   width = 700,
                   height = 500))
plot(map)

## 'data.frame':    27 obs. of  4 variables:
##  $ capital: chr  "Aracaju - SE" "Belém - PA" "Belo Horizonte - MG" "Boa Vista - RR" ...
##  $ lat    : num  -10.91 -1.46 -19.92 2.82 -15.78 ...
##  $ lon    : num  -37.1 -48.5 -43.9 -60.7 -47.9 ...
##  $ latlon : chr  "-10.911:-37.072" "-1.456:-48.504" "-19.921:-43.938" "2.82:-60.673" ...
map <- gvisMap(data = br,
               locationvar = "latlon",
               tipvar = "capital",
               options = list(showTip = TRUE,
                              showLine = TRUE,
                              enableScrollWheel = TRUE,
                              mapType = "terrain",
                              useMapTypeControl = TRUE,
                              width = "700px",
                              height = "500px"))
plot(map)

Detalhes

  • O principal argumento da função é um data.frame.
  • Para alguns gráficos é necessário computar valores antes (boxplot).
  • Para mapas os polígonos tem que estar com nome conforme a base do Google.
  • Customização do gráfico é feita em JavaScript no parâmetro options.
  • É necessário conhecer detalhes da implementação em JS para ajuste fino.
  • Consultar documentação do Google: https://developers.google.com/chart/.

rCharts

Uso do rChart

library(methods)
library(rCharts)
grep(ls("package:rCharts"),
     pattern = "Plot$",
     ignore.case = FALSE,
     value = TRUE)
##  [1] "dimplePlot"    "dPlot"         "highchartPlot" "hPlot"        
##  [5] "morrisPlot"    "mPlot"         "nPlot"         "nvd3Plot"     
##  [9] "riPlot"        "rPlot"         "rrPlot"        "uPlot"        
## [13] "vPlot"         "xPlot"
data(economics, package = "ggplot2")

econ <- transform(economics, date = as.character(date))

m1 <- mPlot(x = "date",
            y = c("psavert", "uempmed"),
            type = "Line",
            data = econ)
m1$set(pointSize = 0, lineWidth = 1)
m1$print("chart2", include_assets = TRUE)

data(diamonds, package = "ggplot2")

rp <- nPlot(~color,
            data = diamonds,
            type = "pieChart")
# rp$chart(color = gray(1:7/7))
rp$print(include_assets = TRUE)

highcharter

Uso do highcharter

Para usar o highcharter em apresentações é necessário incluir algumas linhas adicionais de código: https://stackoverflow.com/questions/35641110/highcharter-markdown-presentation.

library("highcharter")

data(mpg, package = "ggplot2")

hc <- hchart(mpg, "scatter", hcaes(x = displ, y = hwy, group = class))

wname <- "plot1.html"
htmlwidgets::saveWidget(hc,
                        file = wname,
                        selfcontained = TRUE,
                        background = "transparent")
iframetxt <- sprintf(paste("<iframe frameBorder=\"0\"",
                           "src=\"%s\"",
                           "width=\"100%%\"",
                           "height=\"600\"",
                           "\b></iframe>",
                           collapse = " "), wname)
cat(iframetxt)

hc <- hchart(diamonds$price,
             color = "#B71C1C",
             name = "Price") %>%
    hc_title(text = "You can zoom me")
wname <- "plot2.html"
htmlwidgets::saveWidget(hc,
                        file = wname,
                        selfcontained = TRUE,
                        background = "transparent")
iframetxt <- sprintf(
    "<iframe frameBorder=\"0\" src=\"%s\" width=\"100%%\" height=\"600\"></iframe>", wname)
cat(iframetxt)

plotly

Uso do plotly

library(plotly)
head(ls("package:plotly"))
## [1] "%>%"             "add_annotations" "add_area"        "add_bars"       
## [5] "add_boxplot"     "add_choropleth"
gg <- ggplot(data = cars,
             mapping = aes(x = speed, y = dist)) +
    geom_point() +
    geom_smooth() +
    xlab("Velocidade") +
    ylab("Distância")

ggplotly(gg, width = "600px", height = "400px")

irisw <- reshape2::melt(iris, id.vars = "Species")
gg <- ggplot(irisw, aes(fill = Species, x = value)) +
    geom_density(alpha = 0.3) +
    facet_wrap(facets = ~variable, scales = "free")
ggplotly(gg, width = "600px", height = "300px")

gg <- ggplot(irisw, aes(x = Species, y = value)) +
    geom_boxplot() +
    facet_wrap(facets = ~variable, scales = "free")
ggplotly(gg, width = "600px", height = "300px")

Resumo dos recursos gráficos tradicionais

  1. plotly
    • É o mais fácil de usar considerando que o usuário já saiba ggplot2.
    • A customização é feita na ggplot2.
    • O gráfico tem recurso de mouse hover, zoom, screenshot, etc.
  2. highchater
    • Tem uma bilioteca grande de gráficos (tradicionais, mapas, etc).
    • Boa aparência e recursos de zoom e mouse hover.
    • Possui integração com Shiny.
  3. googleVis
    • Dá acesso via R aos gráficos do Google Charts.
    • A biblioteca é grande mas a customização é em JS.
  4. rChart
    • Tem gráficos interessantes mas a documentação é escassa.

Mapas

Aula do dia 17/05

  • Recursos para exibição interativa de dados espaciais serão vistos na aula do dia 17/05.
  • A aula será dada pelo Acadêmico Gabriel Sartori.

Animações

animation

Uso do animation

library(animation)

da <- data.frame(x = seq(0, 2, by = 0.1))
da$y <- c(5.5, 7.2, 10.4, 7.4, 7.2, 9.1, 15.9, 12.7, 11.3, 14.4, 14.8,
          17.1, 31.4, 17.5, 27.6, 19.6, 27.1, 21, 33.8, 30.2, 45.1)

x_grid <- seq(0, 2, lenght.out = 1000)
b_grid <- seq(0, 2, by = 0.05)
b_grid <- b_grid[-c(1, length(grid))]
desvios <- rep(NA, length(b_grid))

# Demostração de uma regressão segmentada com diferentes pontos de
# quebra.
anim_fun <- function() {
    xlim <- extendrange(da$x, f = 0.025)
    for (i in 1:length(b_grid)) {
        #------------------------------------
        # Ajuste do modelo com valor do ponto de quebra fixo.
        b <- b_grid[i]
        m0 <- lm(y ~ x + I(pmax(x - b, 0)),
                 data = da)
        beta <- coefficients(m0)
        desvios[i] <- sum(residuals(m0)^2)
        cols <- c(rep(3, sum(da$x < b_grid[i])),
                  rep(4, sum(da$x > b_grid[i] | da$x == b_grid[i])))
        #------------------------------------
        # Gráfico.
        par(mfrow = c(1, 2), mar = c(3, 3, 1, 1))
        #------------------------------------
        # Gráfico 1.
        plot(y ~ x, xlim = xlim, data = da, ann = FALSE, pch = 19,
             col = cols)
        mtext(text = "x", side = 1, line = 2)
        mtext(text = "y", side = 2, line = 2)
        curve(beta[1] + beta[2] * x,
              from = 0, to = b, col = 3, add = TRUE)
        curve(beta[1] + beta[2] * b + (beta[3] + beta[2]) * (x - b),
              from = b, to = 2, col = 4, lwd = 2, add = TRUE)
        abline(v = b)
        #------------------------------------
        # Gráfico 2.
        plot(b_grid, xlim = xlim, ylim = c(300, 500), desvios,
             type = "o", pch = 1, xlab = "Pontos de Quebra")
        mtext(text = "x", side = 1, line = 2)
        mtext(text = "SQE", side = 2, line = 2)
        abline(v = b)
        ani.pause(interval = 0.1)
    }
}
anim_fun()
wname <- "piecewise.html"
saveHTML(anim_fun(),
         interval = 0.1,
         autobrowse = FALSE,
         htmlfile = wname,
         img.name = sub(x = wname, "\\.html$", ""),
         imgdir = sub(x = wname, "\\.html$", ""),
         verbose = FALSE,
         ani.height = 300,
         ani.width = 600)

Gráficos tridimensionais

rgl

SVM

library(knitr)
library(rgl)
knit_hooks$set(webgl = hook_webgl)

library(e1071)

svm_model <- svm(cl ~ x + y + z,
                 data = t,
                 type = "C-classification",
                 kernel = "linear",
                 scale = FALSE)
w <- t(svm_model$coefs) %*% svm_model$SV
w
##               x      y.1        z
## [1,] -0.5289387 -2.23671 4.080385
detalization <- 50
grid <- expand.grid(x = seq(from = min(t$x),
                            to = max(t$x),
                            length.out = detalization),
                    y = seq(from = min(t$y),
                            to = max(t$y),
                            length.out = detalization))
grid$z <- (svm_model$rho -
           w[1, 1] * grid[, 1] - w[1, 2] * grid[, 2])/w[1, 3]

with(t, {
    plot3d(x = x,
           y = y,
           z = z,
           col = c("red", "blue")[as.integer(cl)],
           type = "s",
           size = 1)
})
points3d(x = grid$x, y = grid$y, z = grid$z, col = "gray")

You must enable Javascript to view this page properly.

Regressão

library(rgl)

da <- expand.grid(r = 1:2, C = -1:1, B = -1:1, A = -1:1,
                  KEEP.OUT.ATTRS = FALSE)
da$y <- c(-35, -25, 110, 75, 4, 5, -45, -60, -10, 30, -40, -30, -40, 15,
          80, 54, 31, 36, 17, 24, 55, 120, -23, -5, -65, -58, -55, -44,
          -64, -62, 20, 4, 110, 44, -20, -31, -39, -35, 90, 113, -30,
          -55, -55, -67, -28, -26, -61, -52, 15, -30, 110, 135, 54, 4)
str(da)

# Modelo reduzido.
m0 <- lm(y ~ (poly(A, 2) + poly(B, 2) + poly(C, 2))^2,
         data = da)

pred <- list(B = seq(-1.2, 1.2, by = 0.05),
             C = seq(-1.2, 1.2, by = 0.05))
pred$fxy <- outer(pred$B,
                  pred$C,
                  FUN = function(x, y) {
                      predict(m0,
                              newdata = data.frame(B = x,
                                                   C = y,
                                                   A = 0))
                  })

persp3d(x = pred$B,
        y = pred$C,
        z = pred$fxy,
        zlim = range(da$y),
        alpha = 0.7,
        color = "tomato")
with(subset(da, A == 0), {
    plot3d(x = B,
           y = C,
           z = y,
           type = "s",
           size = 1)
})

You must enable Javascript to view this page properly.

Próxima aula

  • Interfaces gráficas com rpanel.
  • leaflet e ggmap com Gabriel Sartori.