Introducción

Highcharter

Highcharter es un paquete de R para crear gráficos dinámicos de Highcharts que utilizan internamente javascript.

Highcharts es una biblioteca de gráficos javascript muy madura y flexible y tiene una gran y poderosa API.

Las principales características de este paquete son:

  • Permite generar varios tipos de gráficos con el mismo estilo: dispersión, burbuja, línea, serie de tiempo, mapas de calor, treemap, gráficos de barras, redes, etc.
  • Permite generar varios objetos R con una sola función. Con la función hchart() se puede usar: data.frames, numéricos, histogramas, caracteres, densidad, factores, ts, mts, xts, stl, ohlc, acf, pronósticos, mforecast, ets, igraph, dist, dendrogram, phylo, survfit clases.
  • Soporta gráficos Highstock, gráficos de velas.
  • Soporta temas como economist, financial times, google, 538 entre otros.
  • Soporta interesante complementos de movimiento, puntos de arrastre, fuente, anotaciones entre otros.

La función hchart permite visualizar los siguientes tipos de gráficos:

    Data Frames   ·   Numeric & Histograms   ·   Densities   ·   Character & Factor   ·   Time Series   ·   Seasonal Decomposition of Time Series by Loess   ·   Forecast package   ·   igraph   ·   xts from quantmod package   ·   xts ohlc objects   ·   Autocovariance & Autocorrelation   ·   Multivariate Time series   ·   Survival Models   ·   Principal Components   ·   Matrix   ·   Distance matrix   ·   Correlation matrix

Todo esto lo puedes revisar en la web oficial de highcharter.

Gráficos dinámicos

Función hchart - “Dispersión”

easypackages::libraries(c("dplyr", "highcharter"))
## Loading required package: dplyr
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
## Loading required package: highcharter
## Highcharts (www.highcharts.com) is a Highsoft software product which is
## not free for commercial and Governmental use
## All packages loaded successfully
data(diamonds, mpg, package = "ggplot2")

hchart(mpg, "scatter", hcaes(x = displ, y = hwy, group = class)) %>%
  hc_title(text = "Dispersión diamonds") %>%
  hc_add_theme(hc_theme_economist())

Función hchart - “columnas”

mpgman2 <- mpg %>%
  count(class, year) %>%
  glimpse()
## Observations: 14
## Variables: 3
## $ class <chr> "2seater", "2seater", "compact", "compact", "midsize", "...
## $ year  <int> 1999, 2008, 1999, 2008, 1999, 2008, 1999, 2008, 1999, 20...
## $ n     <int> 2, 3, 25, 22, 20, 21, 6, 5, 16, 17, 19, 16, 29, 33
hchart(mpgman2, "column", hcaes(x = class, y = n, group = year)) %>% hc_add_theme(hc_theme_darkunica())

Función hchart - “barras”

hchart(mpgman2, "bar", hcaes(x = class, y = n, group = year))  %>% hc_add_theme(hc_theme_gridlight())

Función hchart - “treemap”

mpgman3 <- mpg %>% 
  group_by(manufacturer) %>% 
  summarise(n = n(), unique = length(unique(model))) %>% 
  arrange(-n, -unique) %>% 
  glimpse()
## Observations: 15
## Variables: 3
## $ manufacturer <chr> "dodge", "toyota", "volkswagen", "ford", "chevrol...
## $ n            <int> 37, 34, 27, 25, 19, 18, 14, 14, 13, 9, 8, 5, 4, 4, 3
## $ unique       <int> 4, 6, 4, 4, 4, 3, 2, 2, 3, 1, 1, 1, 1, 1, 1
hchart(mpgman3, "treemap", hcaes(x = manufacturer, value = n, color = unique)) 

Función hchart - “lineal”

library(ggplot2)
economics_long2 <- economics_long %>% 
  filter(variable %in% c("pop", "uempmed", "unemploy")) %>% 
  print()
## Source: local data frame [1,722 x 4]
## Groups: variable [3]
## 
##          date variable  value     value01
##        <date>   <fctr>  <dbl>       <dbl>
## 1  1967-07-01      pop 198712 0.000000000
## 2  1967-08-01      pop 198911 0.001628811
## 3  1967-09-01      pop 199113 0.003282177
## 4  1967-10-01      pop 199311 0.004902803
## 5  1967-11-01      pop 199498 0.006433395
## 6  1967-12-01      pop 199657 0.007734807
## 7  1968-01-01      pop 199808 0.008970739
## 8  1968-02-01      pop 199920 0.009887457
## 9  1968-03-01      pop 200056 0.011000614
## 10 1968-04-01      pop 200208 0.012244731
## # ... with 1,712 more rows
hchart(economics_long2, "line", hcaes(x = date, y = value01, group = variable)) %>% hc_add_theme(hc_theme_google())

Función hchart - “numérico o histograma”

hchart(diamonds$price) %>% hc_add_theme(hc_theme_elementary())

Función hchart - “sectores”

hchart(mpgman2 %>% filter(year==2008) , "pie", hcaes(x = class, y = n)) %>% hc_add_theme(hc_theme_538())

Función hchart - “densidad”

hchart(density(diamonds$price), type = "area", color = "#B71C1C", name = "Price") %>% hc_add_theme(hc_theme_elementary())

Función hchart - “quantmod”

library(quantmod)
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## 
## Attaching package: 'xts'
## The following objects are masked from 'package:dplyr':
## 
##     first, last
## Loading required package: TTR
## Version 0.4-0 included new data defaults. See ?getSymbols.
x <- getSymbols("USD/JPY", src = "oanda", auto.assign = FALSE)
## 'getSymbols' currently uses auto.assign=TRUE by default, but will
## use auto.assign=FALSE in 0.5-0. You will still be able to use
## 'loadSymbols' to automatically load data. getOption("getSymbols.env")
## and getOption("getSymbols.auto.assign") will still be checked for
## alternate defaults.
## 
## This message is shown once per session and may be disabled by setting 
## options("getSymbols.warning4.0"=FALSE). See ?getSymbols for details.
hchart(x)

Función hchart - “forecast”

library("forecast")
airforecast <- forecast(auto.arima(AirPassengers), level = 95)
hchart(airforecast) %>% hc_add_theme(hc_theme_sandsignika())

Función hchart - “Componentes Principales”

hchart(princomp(USArrests, cor = TRUE)) %>% hc_add_theme(hc_theme_538())

Boxplot

data(diamonds, package = "ggplot2")

hcboxplot(x = diamonds$x, var = diamonds$color,
          name = "Length", color = "#2980b9") %>%
  hc_add_theme(hc_theme_economist())

Gráfico de barras y de sectores incrustado

data("favorite_bars")
data("favorite_pies")

highchart() %>%
  # Data
  hc_add_series(favorite_pies, "column", hcaes(x = pie, y = percent), name = "Pie") %>%
  hc_add_series(favorite_bars, "pie", hcaes(name = bar, y = percent), name = "Bars") %>% 
        hc_add_theme(hc_theme_ffx()) %>%
  # Optiosn for each type of series
  hc_plotOptions(
    series = list(
      showInLegend = FALSE,
      pointFormat = "{point.y}%"
    ),
    column = list(
      colorByPoint = TRUE
    ),
    pie = list(
      colorByPoint = TRUE, center = c('30%', '10%'),
      size = 120, dataLabels = list(enabled = FALSE)
    )) %>%
  # Axis
  hc_yAxis(
    title = list(text = "percentage of tastiness"),
    labels = list(format = "{value}%"), max = 100
  ) %>%
  hc_xAxis(categories = favorite_pies$pie) %>%
  # Titles and credits
  hc_title(
    text = "This is a bar graph describing my favorite pies
    including a pie chart describing my favorite bars"
  ) %>%
  hc_subtitle(text = "In percentage of tastiness and awesomeness") %>%
  hc_credits(
    enabled = TRUE, text = "Source: HIMYM",
    style = list(fontSize = "12px")
  )

Mapas dinámicos

mapdata <- get_data_from_map(download_map_data("countries/us/us-all"))
glimpse(mapdata)
## Observations: 52
## Variables: 19
## $ hc-group    <chr> "admin1", "admin1", "admin1", "admin1", "admin1", ...
## $ hc-middle-x <dbl> 0.36, 0.56, 0.51, 0.47, 0.41, 0.43, 0.71, 0.46, 0....
## $ hc-middle-y <dbl> 0.47, 0.52, 0.67, 0.52, 0.38, 0.40, 0.67, 0.38, 0....
## $ hc-key      <chr> "us-ma", "us-wa", "us-ca", "us-or", "us-wi", "us-m...
## $ hc-a2       <chr> "MA", "WA", "CA", "OR", "WI", "ME", "MI", "NV", "N...
## $ labelrank   <chr> "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", ...
## $ hasc        <chr> "US.MA", "US.WA", "US.CA", "US.OR", "US.WI", "US.M...
## $ woe-id      <chr> "2347580", "2347606", "2347563", "2347596", "23476...
## $ state-fips  <chr> "25", "53", "6", "41", "55", "23", "26", "32", "35...
## $ fips        <chr> "US25", "US53", "US06", "US41", "US55", "US23", "U...
## $ postal-code <chr> "MA", "WA", "CA", "OR", "WI", "ME", "MI", "NV", "N...
## $ name        <chr> "Massachusetts", "Washington", "California", "Oreg...
## $ country     <chr> "United States of America", "United States of Amer...
## $ region      <chr> "Northeast", "West", "West", "West", "Midwest", "N...
## $ longitude   <chr> "-71.99930000000001", "-120.361", "-119.591", "-12...
## $ woe-name    <chr> "Massachusetts", "Washington", "California", "Oreg...
## $ latitude    <chr> "42.3739", "47.4865", "36.7496", "43.8333", "44.37...
## $ woe-label   <chr> "Massachusetts, US, United States", "Washington, U...
## $ type        <chr> "State", "State", "State", "State", "State", "Stat...
set.seed(1234)

data_fake <- mapdata %>% 
  select(code = `hc-a2`) %>% 
  mutate(value = 1e5 * abs(rt(nrow(.), df = 10)))

glimpse(data_fake)
## Observations: 52
## Variables: 2
## $ code  <chr> "MA", "WA", "CA", "OR", "WI", "ME", "MI", "NV", "NM", "C...
## $ value <dbl> 119426.518, 255662.317, 3668.575, 122246.930, 79283.064,...
hcmap("countries/us/us-all", data = data_fake, value = "value",
      joinBy = c("hc-a2", "code"), name = "Fake data",
      dataLabels = list(enabled = TRUE, format = '{point.name}'),
      borderColor = "#0EAD82", borderWidth = 0.1,
      tooltip = list(valueDecimals = 2, valuePrefix = "$", valueSuffix = " USD")) 

º