Pacote Lattice

O pacote Lattice foi desenvolvido por Deepayan Sarkar tendo como principal característica aprimorar a visualização de relacionamentos multivariados. Em particular, o pacote suporta a representação de gráficos em treliça (trellis graphs) – que expõe o relacionamento entre uma ou mais variáveis quando condicionadas a uma ou mais variáveis.

O Lattice requer a escolha de um tipo de gráfico, uma fórmula e um conjunto de dados.

Exemplos de uso

library(lattice)
library(mlmRev)
## Loading required package: lme4
## Loading required package: Matrix
library(latticeExtra)
## Loading required package: RColorBrewer
library(MASS)

data(Chem97,package ="mlmRev")
head(Chem97) # Pontuações no exame de Química de nível A de 1997 na Grã-Bretanha.
summary(Chem97)
##       lea            school         student          score       
##  118    :  969   698    :  188   1      :    1   Min.   : 0.000  
##  116    :  931   1408   :  126   2      :    1   1st Qu.: 4.000  
##  119    :  916   431    :  118   3      :    1   Median : 6.000  
##  109    :  802   416    :  111   4      :    1   Mean   : 5.813  
##  113    :  791   1215   :   99   5      :    1   3rd Qu.: 8.000  
##  129    :  762   908    :   94   6      :    1   Max.   :10.000  
##  (Other):25851   (Other):30286   (Other):31016                   
##  gender         age            gcsescore        gcsecnt        
##  M:17262   Min.   :-6.0000   Min.   :0.000   Min.   :-6.28568  
##  F:13760   1st Qu.:-3.0000   1st Qu.:5.750   1st Qu.:-0.53568  
##            Median :-1.0000   Median :6.375   Median : 0.08932  
##            Mean   :-0.4678   Mean   :6.286   Mean   : 0.00000  
##            3rd Qu.: 3.0000   3rd Qu.:6.900   3rd Qu.: 0.61432  
##            Max.   : 5.0000   Max.   :8.000   Max.   : 1.71432  
## 
xtabs(~ score, data=Chem97)
## score
##    0    2    4    6    8   10 
## 3688 3627 4619 5739 6668 6681
xtabs(~gender, data=Chem97)
## gender
##     M     F 
## 17262 13760
histogram(~gcsescore|factor(score),data=Chem97,aspect =0.7) # histograma

densityplot(~gcsescore|factor(score),data=Chem97,
plot.points=FALSE,layout=c(3,2),aspect =0.7) # densidade

densityplot(~gcsescore,data=Chem97,groups=score, aspect=0.3,
plot.points=FALSE,auto.key=list(columns=3))

bwplot(~gcsescore|factor(score),data=Chem97) # boxplot

bwplot(gcsescore~factor(gender)|factor(score),data=Chem97) # qual a diferença com o gráfico anterior?

bwplot(gcsescore~factor(gender)|factor(score),data=Chem97,
panel = panel.violin,aspect =0.7) # violino

O gráfico dotplot (gráfico de pontos) representa cada observação obtida em uma escala horizontal, permitindo visualizar a distribuição dos dados ao longo deste eixo. No eixo horizontal, dividimos a escala dos valores em pequenos intervalos, sendo marcado um ponto por observação.

O dotplot, ou gráfico de pontos, é muito útil para visualizar estratificações. A estratificação é uma técnica que agrupa dados em subgrupos, de acordo com determinados critérios, aumentando o poder da análise.

data(barley,package ="lattice")
head(barley) # Rendimentos em alqueires por acre, de 10 variedades de cevada.
dotplot(variety~yield|site,barley,layout=c(3,2),aspect=0.7,
groups=year,type=c("p","h"),auto.key=list(space="right"))

data("oats",package ="MASS")
head(oats)
names(oats)
## [1] "B" "V" "N" "Y"
xyplot(Y ~ N | B, oats, aspect = "xy", type="o",
groups = V,lty = 2, pch = 1:3,
col.line = "darkgrey", col.symbol = "black",
xlab = "Concentração de nitrogênio (cwt/acre)",
ylab = "Produção (bushels/acre)",
main = "Produção de três variedades de aveia",
sub = "Experimento em blocos casualizados no esquema de parcelas subdivididas")

Resumo pacote lattice

Gráfico de interação entre fatores

summary(oats)
##    B                V           N            Y        
##  I  :12   Golden.rain:24   0.0cwt:18   Min.   : 53.0  
##  II :12   Marvellous :24   0.2cwt:18   1st Qu.: 86.0  
##  III:12   Victory    :24   0.4cwt:18   Median :102.5  
##  IV :12                    0.6cwt:18   Mean   :104.0  
##  V  :12                                3rd Qu.:121.2  
##  VI :12                                Max.   :174.0
attach(oats)

# análise de variância

oatsModel <- aov(Y ~ V*N + B, data = oats)

interaction.plot(x.factor = V,trace.factor = N,response = Y, 
                 fun = mean,type="b",col=c("black","red","green"),
                 pch=c(19, 17, 15), fixed=TRUE,leg.bty = "o")

library(phia)
## Loading required package: car
## Loading required package: carData
## Registered S3 methods overwritten by 'car':
##   method                          from
##   influence.merMod                lme4
##   cooks.distance.influence.merMod lme4
##   dfbeta.influence.merMod         lme4
##   dfbetas.influence.merMod        lme4
IM = interactionMeans(oatsModel)
par(mfrow=c(1,1))
plot(IM)

###

library(MASS)
model = lm(Y ~ B + V*N, data = oats)

library(car)
Anova(model)
library(multcompView)
library(multcomp)
## Loading required package: mvtnorm
## Loading required package: survival
## Loading required package: TH.data
## 
## Attaching package: 'TH.data'
## The following object is masked from 'package:MASS':
## 
##     geyser
library(lsmeans)
## Loading required package: emmeans
## The 'lsmeans' package is now basically a front end for 'emmeans'.
## Users are encouraged to switch the rest of the way.
## See help('transition') for more information, including how to
## convert old 'lsmeans' objects and scripts to work with 'emmeans'.
marginal =  lsmeans(model,~ V)
## NOTE: Results may be misleading due to involvement in interactions
CLD = CLD(marginal,alpha=0.05,
          Letters=letters,adjust="tukey")
## Warning: 'CLD' will be deprecated. Its use is discouraged.
## See '? CLD' for an explanation. Use 'pwpp' or 'multcomp::cld' instead.
CLD
CLD$V = factor(CLD$V,
        levels=c("Golden.rain", "Marvellous", "Northampton", "Victory"))
CLD$.group=gsub(" ", "", CLD$.group)
V<-oats$V

library(ggplot2)
## 
## Attaching package: 'ggplot2'
## The following object is masked from 'package:latticeExtra':
## 
##     layer
ggplot(CLD,aes(x = V,y = lsmean,label = .group)) +
    geom_point(shape = 15,size = 4,position = "dodge") +
    geom_errorbar(aes(ymin = lower.CL,ymax = upper.CL),
    width = 0.2,size = 0.7,position = "dodge") +  theme_bw() +
    theme(axis.title = element_text(face = "bold"),
          axis.text = element_text(face = "bold"),
          plot.caption = element_text(hjust = 0)) + ylab("Least square mean\nmidichlorian count") +
    ggtitle ("Produção de aveia") +
            labs(caption  = paste0("Experimento fatorial"),hjust=0.5) + 
  geom_text(nudge_x = c(0, 0, 0),nudge_y = c(10,10,10),color   = "black")
## Warning: Width not defined. Set with `position_dodge(width = ?)`

Gráficos dinâmicos (animações)

library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:MASS':
## 
##     select
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
df <- data.frame(
  x = c(1,2,3,4), 
  y = c(1,2,3,4), 
  f = c(1,2,3,4))

p <- ggplot(df, aes(x, y)) +
    geom_point(aes(frame = f))
## Warning: Ignoring unknown aesthetics: frame
p <- ggplotly(p)
p
###

library(gapminder)
head(gapminder)
p1 <- ggplot(gapminder, aes(gdpPercap, lifeExp, color = continent)) +
  geom_point(aes(size = pop, frame = year, ids = country)) +
  scale_x_log10()
## Warning: Ignoring unknown aesthetics: frame, ids
p1 <- ggplotly(p1)
p1
base <- gapminder %>%
  plot_ly(x = ~gdpPercap, y = ~lifeExp, size = ~pop, 
          text = ~country, hoverinfo = "text") %>%
  layout(xaxis = list(type = "log"))

base %>% add_markers(color = ~continent, frame = ~year, ids = ~country) %>% animation_opts(1000, easing = "elastic", redraw = FALSE) %>%
  animation_button(x = 1, xanchor = "right", y = 0, yanchor = "bottom") %>% animation_slider(
    currentvalue = list(prefix = "YEAR ", font = list(color="red")))
## Warning: `line.width` does not currently support multiple values.
## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

## Warning: `line.width` does not currently support multiple values.

Mais informações no link: https://plotly-r.com/animating-views.html

library(gganimate)

ggplot(mtcars, aes(factor(cyl), mpg)) + 
  geom_boxplot() + 
  transition_states(gear,
    transition_length = 2,
    state_length = 1) +
  enter_fade() + 
  exit_shrink() +
  ease_aes('sine-in-out')

theme_set(theme_bw())

library(gapminder)
head(gapminder)
p <- ggplot(gapminder, 
  aes(x = gdpPercap, y=lifeExp, size = pop, colour = country)) +
  geom_point(show.legend = FALSE, alpha = 0.7) +
  scale_color_viridis_d() +
  scale_size(range = c(2, 12)) +
  scale_x_log10() +
  labs(x = "GDP per capita", y = "Life expectancy")
p

p + transition_time(year) +
  labs(title = "Year: {frame_time}")

# Salvando a animação

anim <- ggplot(iris, aes(x = Petal.Width, y = Petal.Length)) + 
  geom_point(aes(colour = Species), size = 2) + 
  transition_states(Species,
                    transition_length = 2,
                    state_length = 1)

animate(anim + enter_fade() + exit_fly(y_loc = 1),
  renderer = av_renderer())

Figuras no R

O pacote magick permite para modernizar e simplificar o processamento de imagem de alta qualidade em R. Ele envolve o ImageMagick STL, que é talvez a biblioteca de processamento de imagem de código aberto mais abrangente disponível atualmente. A biblioteca ImageMagick possui uma grande quantidade de funcionalidades.

library(magick)
## Linking to ImageMagick 6.9.9.14
## Enabled features: cairo, freetype, fftw, ghostscript, lcms, pango, rsvg, webp
## Disabled features: fontconfig, x11
library(rsvg)
library(png)
library(grid)

str(magick::magick_config())
## List of 21
##  $ version           :Class 'numeric_version'  hidden list of 1
##   ..$ : int [1:4] 6 9 9 14
##  $ modules           : logi FALSE
##  $ cairo             : logi TRUE
##  $ fontconfig        : logi FALSE
##  $ freetype          : logi TRUE
##  $ fftw              : logi TRUE
##  $ ghostscript       : logi TRUE
##  $ jpeg              : logi TRUE
##  $ lcms              : logi TRUE
##  $ libopenjp2        : logi FALSE
##  $ lzma              : logi TRUE
##  $ pangocairo        : logi TRUE
##  $ pango             : logi TRUE
##  $ png               : logi TRUE
##  $ rsvg              : logi TRUE
##  $ tiff              : logi TRUE
##  $ webp              : logi TRUE
##  $ wmf               : logi FALSE
##  $ x11               : logi FALSE
##  $ xml               : logi TRUE
##  $ zero-configuration: logi TRUE
library(magick)
tiger <- image_read('http://jeroen.github.io/images/tiger.svg')
#tiger
image_info(tiger)
#logo <- image_read("logo.png")
#image_append(image_scale(logo, "100"), stack = TRUE)

#image_annotate(logo, "R é mágico!", size = 50, color = "red", boxcolor = "black", degrees = 30, location = "+40+90")

### Formato raster

# plot(as.raster(logo))

earth <- image_read("https://jeroen.github.io/images/earth.gif") %>%
  image_scale("200x") %>%
  image_quantize(128)
earth

###

Pacote imager

O pacote imager contém uma grande variedade de funções para trabalhar com dados de imagem, sendo que a maioria dessas funções vem da biblioteca CImg de David Tschumperlé.

Mais informações em: http://dahtah.github.io/imager/

library(imager)
## Loading required package: magrittr
## 
## Attaching package: 'imager'
## The following object is masked from 'package:magrittr':
## 
##     add
## The following object is masked from 'package:grid':
## 
##     depth
## The following object is masked from 'package:plotly':
## 
##     highlight
## The following objects are masked from 'package:stats':
## 
##     convolve, spectrum
## The following object is masked from 'package:graphics':
## 
##     frame
## The following object is masked from 'package:base':
## 
##     save.image
fig1 <- system.file('extdata/parrots.png',package='imager')
fig1 <- load.image(fig1)
plot(fig1)

###

library(grid)

qplot(speed, dist, data = cars, geom = c("point", "smooth"))
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
grid.raster(earth, width = 0.15, height = 0.3,
            hjust = -2, vjust = 1)

Lendo um texto de uma figura

library(tesseract)
# img <- image_read("http://jeroen.github.io/images/testocr.png")
# print(img)

# extrai o texto

# cat(image_ocr(img))

Referências