Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming legends of 3D Surface plots in R Plotly

Tags:

r

plotly

I was wondering if there is a way to name the legends that are displayed by plotly for multiple surfaces on the same plot equivalent to the trace method:

Using the multiple surface example on plotly:

https://plot.ly/r/3d-surface-plots/

library(plotly)
    z <- c(
  c(8.83,8.89,8.81,8.87,8.9,8.87),
  c(8.89,8.94,8.85,8.94,8.96,8.92),
  c(8.84,8.9,8.82,8.92,8.93,8.91),
  c(8.79,8.85,8.79,8.9,8.94,8.92),
  c(8.79,8.88,8.81,8.9,8.95,8.92),
  c(8.8,8.82,8.78,8.91,8.94,8.92),
  c(8.75,8.78,8.77,8.91,8.95,8.92),
  c(8.8,8.8,8.77,8.91,8.95,8.94),
  c(8.74,8.81,8.76,8.93,8.98,8.99),
  c(8.89,8.99,8.92,9.1,9.13,9.11),
  c(8.97,8.97,8.91,9.09,9.11,9.11),
  c(9.04,9.08,9.05,9.25,9.28,9.27),
  c(9,9.01,9,9.2,9.23,9.2),
  c(8.99,8.99,8.98,9.18,9.2,9.19),
  c(8.93,8.97,8.97,9.18,9.2,9.18)
)
dim(z) <- c(15,6)
z2 <- z + 1
z3 <- z - 1

p <- plot_ly(showscale = FALSE) %>%
  add_surface(z = ~z) %>%
  add_surface(z = ~z2, opacity = 0.98) %>%
  add_surface(z = ~z3, opacity = 0.98)

If I change the ploty code to below:

p <- plot_ly(showscale = TRUE) %>%
  add_surface(z = ~z, name="Example 1") %>%
  add_surface(z = ~z2, opacity = 0.98,name="Example 2") %>%
  add_surface(z = ~z3, opacity = 0.98,name="Example 3")

The name is not displayed above the legends as one would expect based on the trace example shown below:

https://plot.ly/r/legend/#legend-names

library(plotly)
library(tidyr)
library(plyr)

data <- spread(Orange, Tree, circumference)
data <- rename(data, c("1" = "Tree1", "2" = "Tree2", "3" = "Tree3", "4" = "Tree4", "5" = "Tree5"))

p <- plot_ly(data, x = ~age, y = ~Tree1, type = 'scatter', mode = 'lines', 
        legendgroup = 'group1', name = 'Zone 1 - Tree 1') %>%
  add_trace(y = ~Tree2, legendgroup = 'group2', name = 'Zone 2 - Tree 1') %>%
  add_trace(y = ~Tree3, legendgroup = 'group1', name = 'Zone 1 - Tree 2') %>%
  add_trace(y = ~Tree4, legendgroup = 'group2', name = 'Zone 2 - Tree 2') %>%
  add_trace(y = ~Tree5, legendgroup = 'group1', name = 'Zone 1 - Tree 3') 

Is there way to get an equivalent result with multiple surfaces for the legend labeling ?

like image 928
RK1 Avatar asked Jan 28 '23 13:01

RK1


1 Answers

Are you looking for this:

p <- plot_ly() %>%
    add_surface(z = ~z, colorbar=list(title='Example 1')) %>%
    add_surface(z = ~z2, opacity = 0.98, colorbar=list(title='Example 2')) %>%
    add_surface(z = ~z3, opacity = 0.98, colorbar=list(title='Example 3'))
like image 160
MLavoie Avatar answered Jan 31 '23 09:01

MLavoie