HTML WIDGETS
El paquete “Htmlwidgets” permite crear visualizaciones interactivas de javascript desde R.
Para utilizar widgets no se requiere programar en Java, solo basta llamar la función en R pero sí es requerido en caso de crear un nuevo paquete.
Creación de un widget usando scaffolWidget
Todos los widgets incluyen los siguientes componentes:
Dependencias: Estos son los elementos de JavaScript y CSS utilizados por el widget (por ejemplo, la biblioteca para la que está creando un contenedor).
Unión R: Esta es la función a la que llamarán los usuarios finales para proporcionar datos de entrada al widget, así como para especificar varias opciones sobre cómo se debe representar el widget. Esto también incluye algunas funciones breves necesarias para usar el widget en las aplicaciones Shiny.
Enlace de JavaScript: Este es el código JavaScript que une todo, pasando los datos y las opciones reunidas en el enlace R a la biblioteca JavaScript subyacente.
install.packages("htmlwidgets")
library(htmlwidgets)
devtools::create("mywidget")
## Package: mywidget
## Title: What the Package Does (one line, title case)
## Version: 0.0.0.9000
## Authors@R: person("First", "Last", email = "first.last@example.com", role = c("aut", "cre"))
## Description: What the package does (one paragraph).
## Depends: R (>= 3.6.0)
## License: What license is it under?
## Encoding: UTF-8
## LazyData: true
## ✔ Writing 'mywidget.Rproj'
## ✔ Adding '.Rproj.user' to '.gitignore'
## ✔ Adding '^mywidget\\.Rproj$', '^\\.Rproj\\.user$' to '.Rbuildignore'
# create package using devtools
setwd("mywidget")
# navigate to package dir
htmlwidgets::scaffoldWidget("mywidget")
# create widget scaffolding
devtools::install()
##
checking for file ‘/cloud/project/mywidget/DESCRIPTION’ ...
✔ checking for file ‘/cloud/project/mywidget/DESCRIPTION’
##
─ preparing ‘mywidget’:
##
checking DESCRIPTION meta-information ...
✔ checking DESCRIPTION meta-information
##
─ checking for LF line-endings in source and make files and shell scripts
##
─ checking for empty or unneeded directories
##
─ building ‘mywidget_0.0.0.9000.tar.gz’
##
##
Running /opt/R/3.6.0/lib/R/bin/R CMD INSTALL \
## /tmp/RtmpEIDaif/mywidget_0.0.0.9000.tar.gz --install-tests
## * installing to library ‘/home/rstudio-user/R/x86_64-pc-linux-gnu-library/3.6’
## * installing *source* package ‘mywidget’ ...
## ** using staged installation
## ** R
## ** inst
## ** byte-compile and prepare package for lazy loading
## No man pages found in package ‘mywidget’
## ** help
## *** installing help indices
## ** building package indices
## ** testing if installed package can be loaded from temporary location
## ** testing if installed package can be loaded from final location
## ** testing if installed package keeps a record of temporary installation path
## * DONE (mywidget)
# install the package so we can try it
Para la crecion de widgets se puede consultar el siguiente link:
http://www.htmlwidgets.org/develop_intro.html
Existe una multitud de paquetes para todo tipo de necesidades que se pueden consultar en la Web. En los siguientes links se pueden estudiar los htmlwidgets disponibles con sus respectivos tutoriales y codigo.
https://www.htmlwidgets.org/showcase_leaflet.html
http://gallery.htmlwidgets.org/
1. Paquete Leaflet:
Es una libreria de Java para crear mapas interactivos que se pueden navegar y editar con marcadores, lineas, limites, etc. La funcion () retorna un mapa y objetos que pueden ser modificados.
Las entradas de datos a la funcion son:
Crear el mapa:
1.1 LLamar la funcion leaflet()
install.packages("leaflet")
library(leaflet)
m <- leaflet() %>%
addTiles()
m
1.2 Agregar coordenadas
m <- leaflet() %>%
addTiles() %>% # agregar titulos al mapa
addMarkers(lng=-84.046489, lat=9.931248, popup="Clase de R") # agregar marcadores
m # imprimir el mapa
1.3 Agregar varios marcadores
Se utiliza el paquete SP: clases y metodos para datos espaciales
library(sp)
data <- read.csv("mock.csv")
data$logitud <- as.numeric(data$logitud)
data$latitud <- as.numeric(data$latitud)
data_sp <- SpatialPointsDataFrame(data[,c(1,2)],data[,-c(1,2)])
##dataframe espacial para manipular objetos espaciales
m <- leaflet() %>%
addTiles() %>%
addMarkers(data = data, lng = ~ logitud, lat = ~ latitud )
m
1.4 Cambiar estilo del mapa
Link a catalogo de mapas
http://leaflet-extras.github.io/leaflet-providers/preview/index.html
m <- leaflet() %>%
addProviderTiles("Esri.WorldImagery")
m
1.5 Incluir poli lineas.
Linea
data <- read.csv("coordenadas_v.csv")
m <- leaflet(data = data) %>%
addTiles() %>%
addPolylines(lng = ~ long, lat = ~ lat, color = "red") %>% # buscar todo en cada columna
addPopups(lat = ~lat,lng = ~ long, popup = ~ punto)
m
1.6 Rectangulo
m=leaflet() %>%
addTiles() %>%
addRectangles(
lng1=-118.456554, lat1=34.078039,
lng2=-118.436383, lat2=34.062717,
fillColor = "transparent"
)
m
2. Paquete Plotly
Es una aplicación Web para crear y compartir graficos iteractivos.
Link a libreria de graficos:
install.packages("plotly")
library(plotly)
2.1 Crear un scatterplot básico
Al seleccionar mode = “markers” se genera un scatterplot
plot_ly(mtcars, x = mtcars$wt , y = mtcars$mpg, mode = "markers")
2.2 Segmentar con colores
plot_ly(mtcars, x = mtcars$wt , y = mtcars$mpg, mode = "markers", color = as.factor(mtcars$cyl))
2.3 Color por rango de valores
plot_ly(mtcars, x = mtcars$wt , y = mtcars$mpg, mode = "markers", color = mtcars$disp)
2.4 Cambiar tamaño de puntos
plot_ly(mtcars, x = mtcars$wt , y = mtcars$mpg, mode = "markers", color = as.factor(mtcars$cyl), size = mtcars$hp)
2.5 Graficos en 3D
temp <- rnorm(100, mean = 30, sd = 5)
pres <- rnorm(100)
dtiempo <- 1:100
plot_ly(x = temp,y = pres, z = dtiempo,
type = "scatter3d", mode = "markers", color = temp)
2.6 Series de tiempo
Datos a utilizar para el ejercicio
airmiles
## Time Series:
## Start = 1937
## End = 1960
## Frequency = 1
## [1] 412 480 683 1052 1385 1418 1634 2178 3362 5948 6109
## [12] 5981 6753 8003 10566 12528 14760 16769 19819 22362 25340 25343
## [23] 29269 30514
time(airmiles)
## Time Series:
## Start = 1937
## End = 1960
## Frequency = 1
## [1] 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950
## [15] 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
2.7 Crear serie de tiempo
plot_ly(x=time(airmiles),y = airmiles)
2.8 Generar multiples series de tiempo
library(tidyr)
library(dplyr)
stocks <- as.data.frame(EuStockMarkets) %>%
gather(index, price) %>% # reacomodo de columnas a filas de indices vs precio
mutate(time = rep(time(EuStockMarkets),4)) # crear la variable de tiempo
plot_ly(stocks,x = stocks$time, y = stocks$price, color = stocks$index)
2.9 Histograma
plot_ly(x=precip , type = "histogram")
2.10 Boxplot
plot_ly(iris,y = iris$Petal.Length,color = iris$Species, type = "box")
2.11 Heatmap
superficie <- matrix(rnorm(100*100),nrow = 100, ncol = 100 )
plot_ly(z = superficie, type = "heatmap")
2.12 Paquete opcional para mapas de calor
install.packages("d3heatmap")
library(d3heatmap)
d3heatmap(mtcars, scale="column", colors="Blues")
2.12 Superficie 3D
plot_ly(z = volcano, type = "surface")
3. Paquete DT
Permite desplegar matrices y dataframes como tablas interactivas en HTML para realizar filtros y ordenamiento de datos.
3.1 Crear datatable
install.packages("DT")
library(DT)
datatable(infert, options = list(pageLength = 6),
caption = "Tabla 1") # colocar titulos
3.2 Editar el datatable
Permite editar los campos del datatable
datatable(infert, editable = TRUE)
3.3 Editar nombres de columnas
datatable(head(infert), colnames = c("schooling" = "education"))
3.4 Agregar filtros
datatable(infert,filter = "top")
4. Paquete Radarchart:
4.1 Crea graficos interactivos de radar o “spider”.
El paquete radarchart debe recibir los datos en un formato en el que cada fila corresponda a un eje del grafico y cada columna es un dato de anotaciones.
Funcion chartJSRadar(scores, labs, maxScale )
Argumentos de la funcion:
scores: El data frame o lista de anotaciones de cada eje. Labs: Etiquetas para cada eje, si no se especifica se toma de la primer columna. maxScale: Maximo valor del eje.
"install.packages(htmlwidgets)"
## [1] "install.packages(htmlwidgets)"
install.packages("radarchart")
library(htmlwidgets)
library(radarchart)
scores <- data.frame("label" =c("Puntos triples","Puntos dobles","Disparos libres","Rebotes","Asistencias"),
"Raúl" = c(7,7,8,7,6),
"Mario" = c(3,2,6,6,6),
"César" = c(6,6,8,9,6),
"Julio" = c(7,7,8,7,6),
"Fabian" = c(8,8,7,9,6))
chartJSRadar(scores,MaxScale = 10,showToolTiplabel=TRUE, main = "Rendimiento por jugador")