4

I was using plotly to render a 3D scatter plot in a shiny app with a color gradient. While the basic scatter plot itself is no problem I cannot seem to be able to change the colors of the color gradient, even for the example provided here: https://plotly.com/r/3d-scatter-plots/. (see code snippet).

I tried multiple color combinations with both standard colors and hexacode.

library(plotly)

fig <- plot_ly(mtcars, x = ~wt, y = ~hp, z = ~qsec,
               marker = list(color = ~mpg, colorscale = c('#FFE1A1', '#683531'), showscale = TRUE))
fig <- fig %>% add_markers()
fig <- fig %>% layout(scene = list(xaxis = list(title = 'Weight'),
                                   yaxis = list(title = 'Gross horsepower'),
                                   zaxis = list(title = '1/4 mile time')),
                      annotations = list(
                        x = 1.13,
                        y = 1.05,
                        text = 'Miles/(US) gallon',
                        xref = 'paper',
                        yref = 'paper',
                        showarrow = FALSE
                        ))
fig


Any help is greatly appreciated. Cheers

1 Answers1

5

It looks like the documentation page you quoted above is out-of-date. This is an example of plotly of having quirks.

From the documentation,
Colorscale: The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, [[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)'] ]. To control the bounds of the colorscale in color space, usecmin and cmax.

To translate this into usable R see this question: R, How to change color of plotly 3d surface?

Thus for your problem above here is a possible solution:

plot_ly(mtcars, x = ~wt, y = ~hp, z = ~qsec, 
        marker = list(color = ~mpg, colorscale = list(c(0, 1), c("yellow", "blue")), showscale = TRUE))

Another option is the use the predifined palettes from ColorBrewer and others with this line:

plot_ly(mtcars, x = ~wt, y = ~hp, z = ~qsec, 
        marker = list(color = ~mpg, colorscale = "Greens", showscale = TRUE))

The available options are: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis.

Dave2e
  • 22,192
  • 18
  • 42
  • 50