Day 16: Sparkline

Welcome back for the 16th day of the #packagecalendar, today we will be taking a look at the sparkline package by Kent Russell. The sparkline package provides a wrapper around the jQuery library of the same name.

The package is available from CRAN and can be downloaded with

install.packages("Sparkline")

This package is quite similar to the datalegreyar package from day 1.

sparkline will take a series of numbers and create a miniature chart from them. Here we will reuse data from day 13

First, let’s pull out a single time-series using dplyr.

library(dplyr)
holy_nights_hits <- carrol_trends %>%
  filter(keyword == "O Holy Night") %>%
  mutate(hits = as.numeric(if_else(hits == "<1", "0", hits))) %>%
  pull(hits)

Then we simply pass the vector to the sparkline() function.

library(sparkline)
sparkline(holy_nights_hits)

What makes sparklines really special is the ability for you to embed them in other applications. In the following example, we group the data by keyword and year. Then we have a sparkline for each year inside our table.

.ReactTable {
  background: #2f3238;
}
library(reactable)
library(dplyr)
library(sparkline)
library(lubridate)

data <- carrol_trends %>%
  mutate(hits = as.numeric(if_else(hits == "<1", "0", hits)),
         year = year(date)) %>%
  filter(year > 2014) %>%
  group_by(keyword, year) %>%
  summarise(hits = list(hits))

reactable(data, columns = list(
  hits = colDef(cell = function(values) {
    sparkline(values)
  })
))

This is all for today. sparkline is highly customizable and can be used in many applications.