Joy
Joy

Reputation: 769

R Plotly 3d trace -- how to get new labels (not x, y, z)

Consider this example taken from Plotly:

library(plotly)
# volcano is a numeric matrix that ships with R
p <- plot_ly(z = ~volcano) %>% add_surface()
p

Notice how if you hover, there's a nice trace that shows x (row indices from your matrix), y (column indices), and z (matrix content at given row and column). How could I change the trace and the axes to something like "Measure1", "Measure2", "Measure3" instead of x,y, z? I've tried layout() but what I put isn't cutting it. This is what I attempted, but "zaxis" isn't a thing, and the other labels don't change,

library(plotly)
# volcano is a numeric matrix that ships with R
p <- plot_ly(z = ~volcano) %>% add_surface() %>% 
layout (xaxis = list(title = "Measure1", showgrid = F),  
  yaxis = list(title = "Measure2"),
  zaxis = list(title="Measure3")
)

p

I'm sure I'm missing something elementary, but I'm stuck. Any help warmly received.

Upvotes: 1

Views: 765

Answers (2)

Maximilian Peters
Maximilian Peters

Reputation: 31689

To extend the previous answer from user2510479:

You can set the axis labels for Plotly surface plots via scene and xaxis/yaxis/zaxis title.

The hoverinfo can be set via text which needs to be an array which has the same dimensions as your z-values. hoverinfo needs to text in order to show those values.

enter image description here

library(plotly)

txt <- array(dim=dim(volcano))
for (x in 0:dim(volcano)[[2]] - 1) {
  for (y in 0:dim(volcano)[[1]] - 1) {
    txt[1 + x*dim(volcano)[[1]] + y] = paste('Measure1: ', x, '<br />Measure2: ', y, '<br />Measure3: ', volcano[1 + x * dim(volcano)[[1]] + y])
  }
}
p <- plot_ly(z = volcano,
             text = txt,
             hoverinfo = 'text') %>% add_surface()
p <- layout(p, scene = list(xaxis = list(title = "Measure1"), 
                            yaxis = list(title = "Measure2"), 
                            zaxis = list(title = "Measure3")
                            )
            )

p

Upvotes: 3

user2510479
user2510479

Reputation: 1540

  p <- plot_ly(z = ~volcano) %>% add_surface() %>% 
  layout(title = "Layout options in Volcano plot",
  scene = list(
  xaxis = list(title = "Measure1"), 
  yaxis = list(title = "Measure2"), 
  zaxis = list(title = "Measure3")))

  p

Upvotes: 2

Related Questions