WebGL Text and Annotations in R

How to add WebGL text labels and annotations to plots in R.


New to Plotly?

Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

Heatmap with Annotations

library(plotly)
library(random)

n=250
t=12
x = c(rep(0:(n-1), times=t))
y = c(rep(0:(t-1), each=n))
z = randomNumbers(n=n*t, min=1, max=10, col=n)
text = c(replicate(t*n, sample(c("A","T","G","C"), 1)))

steps = list()
for (e in c(0:(n-30))){
  step <-  list(
    list(
      args = list('xaxis.range', c(-0.5 + e, 30.5 + e)),
      method = "relayout",
      label = e,
      value = e
    )
  )
  steps[e] <- step
}

fig <- plot_ly() 
fig <- fig %>%
  add_trace(
    type='heatmap',
    z = z
  ) 
fig <- fig %>%
  add_trace(
    mode = "text",
    text = text,
    type = "scattergl",
    textfont = list(
      size = 20
    ),
    x = x,
    y = y
  ) 
fig <- fig %>%
  layout(
    xaxis = list(
      range = c(-0.5, 30.5),
      showline = F,
      zeroline = F,
      showgrid = F
    ),
    yaxis = list(
      showline = F,
      zeroline = F,
      showgrid = F
    ),
    sliders=list(
      list(
        active = 0,
        steps = steps
      )
    )
  )

fig

Reference

See https://plotly.com/r/reference/#scattergl for more information and chart attribute options!

What About Dash?

Dash for R is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash for R at https://dashr.plot.ly/installation.

Everywhere in this page that you see fig, you can display the same figure in a Dash for R application by passing it to the figure argument of the Graph component from the built-in dashCoreComponents package like this:

library(plotly)

fig <- plot_ly() 
# fig <- fig %>% add_trace( ... )
# fig <- fig %>% layout( ... ) 

library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)

app <- Dash$new()
app$layout(
    htmlDiv(
        list(
            dccGraph(figure=fig) 
        )
     )
)

app$run_server(debug=TRUE, dev_tools_hot_reload=FALSE)