2.7 Raster images

In R, there is native support for raster objects which encode bitmap images as essentially a matrix of color codes.

m <- matrix(hcl(0, 80, seq(50, 80, 10)), nrow = 4, ncol = 5)
(r <- as.raster(m))
#>      [,1]      [,2]      [,3]      [,4]      [,5]     
#> [1,] "#C54E6D" "#C54E6D" "#C54E6D" "#C54E6D" "#C54E6D"
#> [2,] "#E16A86" "#E16A86" "#E16A86" "#E16A86" "#E16A86"
#> [3,] "#FE86A1" "#FE86A1" "#FE86A1" "#FE86A1" "#FE86A1"
#> [4,] "#FFA2BC" "#FFA2BC" "#FFA2BC" "#FFA2BC" "#FFA2BC"
plot(r)

The raster2uri() function converts raster objects to a data URI, so they can be easily embedded via plotly’s image API:

plot_ly() %>%
  layout(images = list(
    source = raster2uri(r), # converts a raster object to a data URI.
    xref = "x", yref = "y", x = 0, y = 0, sizex = 1, sizey = 1,
    sizing = "stretch", xanchor = "left", yanchor = "bottom"
  ))

Figure 2.33: A simple raster object displayed as an image

For more examples of the image API, see https://plot.ly/r/logos/