✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.

Colorscales in R

How to create colorscales in R with Plotly.


Write, deploy, & scale Dash apps and R data visualizations on a Kubernetes Dash Enterprise cluster.
Get Pricing  |  Demo Dash Enterprise  |  Dash Enterprise Overview


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.

Colorscale for Scatter Plots

library(plotly)

fig <- plot_ly(
  type = 'scatter',
  mode='markers',
  y=rep(5, 40),
  marker=list(
    size=seq(0, 39),
    color=seq(0, 39),
    colorbar=list(
      title='Colorbar'
    ),
    colorscale='Viridis',
    reversescale =T
  )
  )
fig <- fig %>% layout(
    xaxis = list(
      showgrid = F,
      zeroline = F
    ),
    yaxis = list(
      showgrid = F,
      zeroline = F
    )
  )

Colorscale Contour

library(plotly)

fig <- plot_ly(
  type = 'contour',
  z=matrix(c(10, 10.625, 12.5, 15.625, 20,
      5.625, 6.25, 8.125, 11.25, 15.625,
      2.5, 3.125, 5., 8.125, 12.5,
      0.625, 1.25, 3.125, 6.25, 10.625,
      0, 0.625, 2.5, 5.625, 10),
      nrow=5, ncol=5)
)

fig

Share Color Axis

This example shows how to specify the color scale and color bar per trace. To share colorscale information in multiple subplots, you can use coloraxis. Below we show how to set a reference coloraxis1 to a shared coloraxis, which are set in the layout. Note that multiple color scales can be linked to the same color.

library(plotly)

fig1 <- plot_ly(
    type = "heatmap",
    x = c(1,2,3,4),
    z = list(c(1,2,3,4), c(4,-3,-1,1)),
    coloraxis = 'coloraxis')
fig2 <- plot_ly(
    type = "heatmap",
    x = c(3,4,5,6),
    z = list(c(10,2,1,0), c(4,3,5,6)),
    coloraxis = 'coloraxis')
fig <- subplot(fig1, fig2)
fig <- fig %>% layout(coloraxis=list(colorscale='Jet'))

fig

Reference

See https://plotly.com/r/reference/#heatmap-colorscale for more information and 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)