Display Image Data in R
How to display image data with R.
Plotly Studio: Transform any dataset into an interactive data application in minutes with AI. Try Plotly Studio now.
Note: We are retiring documentation for R, MATLAB, Julia, and F#. Learn more about this change here.
This tutorial shows how to display and explore image data. If you would like instead a logo or static image, use layout.Image as explained here.
Display RGB Image Data with Image Trace
Note that Image trace only accepts multichannel images. For single images, use Heatmap. Image trace is different from the layout.Image class, which can be used for adding background images or logos to figures.
library(plotly)
library(EBImage)
img_rgb = list(list(c(255, 0, 0),c(0, 255, 0),c(0, 0, 255)),
list(c(0,255, 0),c(0, 0, 255),c(255, 0, 0)))
fig <- plot_ly(type="image", z=img_rgb)
fig
Read image arrays from image files
In order to create a numerical array to be passed to Image trace, you can use a third-party library like EBImage to open an image from a URL.
library(plotly)
library(EBImage)
img = readImage('https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Crab_Nebula.jpg/240px-Crab_Nebula.jpg')
fig <- plot_ly(type="image", z=img*255)
fig
Define the data range covered by the color range with zmin and zmax
The data range and color range are mapped together using the parameters zmin and zmax, which correspond respectively to the data values mapped to black [0, 0, 0] and white [255, 255, 255].
The default value of zmin and zmax depends on the colormodal value. In this example colormodel is "rgb"(by default), so the default value of zmin is [0, 0, 0] and zmax is [250, 250, 250].
library(plotly)
library(EBImage)
img = readImage('https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Crab_Nebula.jpg/240px-Crab_Nebula.jpg')
# Stretch the contrast of the red channel only, resulting in a more red image
fig <- plot_ly(type="image", z=img*250,
zmin=c(10, 0, 0), zmax=c(200, 250, 250))
fig