@@ -24,7 +24,7 @@ add_data <- function(p, data = NULL) {
2424# ' @inheritParams plot_ly
2525# ' @param p a plotly object
2626# ' @param inherit inherit attributes from [plot_ly()]?
27- # ' @param z a numeric matrix
27+ # ' @param z a numeric matrix (unless [add_image()], which wants a raster object, see [as.raster()]).
2828# ' @param x the x variable.
2929# ' @param y the y variable.
3030# ' @param text textual labels.
@@ -393,6 +393,43 @@ add_ribbons <- function(p, x = NULL, ymin = NULL, ymax = NULL, ...,
393393 )
394394}
395395
396+ # ' @inheritParams add_trace
397+ # ' @rdname add_trace
398+ # ' @param colormodel Sets the colormodel for image traces if `z` is not a raster object.
399+ # ' If `z` is a raster object (see [as.raster()]), the `'rgba'` colormodel is always used.
400+ # ' @export
401+ add_image <- function (p , z = NULL , colormodel = NULL , ... , data = NULL , inherit = TRUE ) {
402+
403+ if (inherit ) {
404+ z <- z %|| % p $ x $ attrs [[1 ]][[" z" ]]
405+ colormodel <- colormodel %|| % p $ x $ attrs [[1 ]][[" colormodel" ]]
406+ }
407+
408+ if (inherits(z , " raster" )) {
409+ cols <- col2rgb(z , alpha = TRUE )
410+ dims <- c(dim(z ), 4 )
411+ z <- array (numeric (prod(dims )), dims )
412+ matrix_ <- function (x ) {
413+ matrix (x , byrow = TRUE , nrow = dims [1 ], ncol = dims [2 ])
414+ }
415+ z [,,1 ] <- matrix_(cols [" red" ,])
416+ z [,,2 ] <- matrix_(cols [" green" ,])
417+ z [,,3 ] <- matrix_(cols [" blue" ,])
418+ z [,,4 ] <- matrix_(cols [" alpha" ,])
419+
420+ # Throw if we detect another colormodel
421+ if (! identical(colormodel %|| % " rgba" , " rgba" )) {
422+ warning(" Passing a raster object to z requires rgba colormodel" )
423+ }
424+ colormodel <- " rgba"
425+ }
426+
427+ add_trace(
428+ p , z = z , colormodel = colormodel , ... ,
429+ data = data , type = " image"
430+ )
431+ }
432+
396433# ' @inheritParams add_trace
397434# ' @rdname add_trace
398435# ' @param r For polar chart only. Sets the radial coordinates.
0 commit comments