library(rasterly)
library(data.table)
library(lubridate)
library(grid)
library(plotly)

rasterly makes it easy to rapidly generate raster images for large datasets. Although the package is inspired by the Datashader library available for Python, rasterly does not attempt to reproduce all the features of Datashader. Rather, rasterly offers comparable performance to Datashader when generating rasters from source data. rasterly attempts to provide a flexible, convenient interface which should feel familiar to users of ggplot2 and its aesthetics-based approach to customizing plots and figures.

A raster may be described as a matrix of cells or pixels arranged in grid-like fashion, in which each pixel represents a value in the source data. When combined with the package and Plotly.js, rasterly enables analysts to generate interactive figures with very large datasets which are responsive enough to embed into Dash for R applications.

The rasterly function creates a rasterly object, to which aggregation layers may be added. This function is the first step in the process of generating raster image data using the package. The rasterly function is not intended to be used in isolation, since aggregation layers are required for full functionality.

Basic

If we were to use graphics::plot(), it would take several minutes to render the image. What if we “rasterized” the image instead?

A raster image, in essence, is a large sparse matrix and each element is a hexadecimal color (A character vector with elements of 7 or 9 characters, “#” followed by the red, blue, green and optionally alpha values). Since the range (x, y) of this display can be acquired, we can also map the image into a data.frame with mapping coordinates x, y and color. For example:

image <- as.raster(matrix((1:4)/4, nrow = 2))
image
##      [,1]      [,2]     
## [1,] "#404040" "#BFBFBF"
## [2,] "#808080" "#FFFFFF"
##    x y   color
## 1: 1 5 #404040
## 2: 1 2 #808080
## 3: 2 5 #BFBFBF
## 4: 2 2 #FFFFFF

In this way, we can transform a large dataset (million or billion) into a raster image (say 400 \(\times\) 400), then, mapping this image to a data.frame but dropping blank ones. So the size can decrease from 160000 to rough 30k or 40k (It really depends on data). In other word, we can always reduce a huge size to a reasonable size and the darkness of color is judged by the “Reduction Function” (see section ‘API’ for more info)

rasterly Structure

Subsetting

rasterly() generates a parent layer containing initial settings to generate the raster, which include plot_height, plot_width among others; child layers such as rasterly_points() can be piped in as well. Note that “p” above is a list of environments. The elements in “p” can be easily extracted or replaced by [ and [<-.

  • level helps to define which layer to replace; the default is 1 (the parent layer generated by rasterly()).
  • Available states which can be extracted or replaced are listed here:
    1. Aggregation: data, mapping, plot_width, plot_height, range, x_range, y_range, xlim, ylim, aesthetics, reduction_func, glyph, max_size, group_by_data_table, drop_data, variable_check
    2. Display: background, color, alpha, span, show_raster, layout

Build rasterly by rasterly_build()

To retrieve display info, use rasterly_build():

It contains:

  • agg: aggregation matrices, a list of numerical matrices
  • image: a raster matrix (has the same dimension with aggregation matrices)
  • lims: a list of x limits and y limits for each layer
  • x_range: the range of x over all layers
  • y_range: the range of y over all layers
  • plot_height: plot height, number of rows in aggregation matrix
  • plot_width: plot width, number of columns in aggregation matrix
  • variable_names: names of variables
  • background: background color
  • colors: color used to map in each pixel or used for categorical variable. It is distinguished by whether “color” is set in aes() or not

Display

rasterly does not provide any functionality to display the raster image data it generates, but instead relies on other packages.

plotly graphics

ggplot graphics

ggRasterly takes the arguments from rasterly and returns a ggplot object. In this case, image will be transformed to a data.frame automatically.

API

rasterly application programming interface

r <- rasterly(data = ridesDf, 
                mapping = aes(x = Lat, y = Lon))

Mapping system

  • Set color

Different colors represent different hours:

The colors attribute in “image” within build_g is generated via weighted arithmetic means (default) computed from the aggregation matrices. We can choose the “cover” layout to display multiple aggregation matrices:

The resulting raster will be overlaid onto the plotting surface.

  • Set on

reduction_func is implemented on which variable

  • Set size

To control the number of pixels allocated to an observation, we can set the size aesthetic; when specified, the max_size argument provides the upper bound of the number of pixels a single observation is allocated:

Currently, only x, y, color, on and size can be set using aes().

Reduction function

A reduction operator function is used when aggregating data points within each bin. One option is to reduce using the mean of the points.

The mean reduction function averages the y column (default setting) for every observation. It’s also possible to average over other features using the on aesthetic; consult the list of available reduction functions below for additional details.

Currently supported reduction functions:

  • sum: If on is not provided within aes(), the default is to take the sum within each bin. When on is specified, the function reduces by taking the sum of all elements within the variable named in on.

  • any: When on is provided within aes(), the any reduction function specifies whether any elements in on should be mapped to each bin.

  • mean: If on is not provided in mapping aes(), on would be set as variable “y” by default. When on is given, the mean reduction function takes the mean of all elements within the variable specified by on.

The following functions require that on is first provided via aes():

  • m2: The m2 function computes the sum of square differences from the mean of all elements in the variable specified by on.

  • var: The var function computes the variance over all elements in the vector specified by on.

  • sd: The sd function computes the standard deviation over all elements in the vector specified by on.

  • first: The first function returns the first element in the vector specified by on.

  • last: The last function returns the last element in the vector specified by on.

  • min: The min function returns the minimum value in the vector specified by on.

  • max: The min function returns the maximum value in the vector specified by on.