Search code examples
rplotlyaxis-labelssurface

How to change axis labels in a 3d surface plot using plotly in R


I have a 2D matrix (11 rows, 20 columns) (avgspeed), where first column is penetration, first row (header) is traffic volume, cells are average speed.

100 200 300 400
[1,] 38.5 38.1 37.7 37.2
[2,] 38.2 37.7 37.5 36.9

Full dataset here: https://laesze-my.sharepoint.com/:x:/g/personal/borsos_attila_o365_sze_hu/EciUlfLjKY5PiLLJJk6v4xEB9qfpU1FA3WrHRaKc7HPKLA?e=nZYbYa

Using plotly I have this surface plot: https://chart-studio.plotly.com/~borsosa/1/#/

p<- plot_ly(z= ~avgspeed)
p <- p %>% add_surface() %>%
  layout(title = "3D surface plot of average speed",
          legend = list(title = list(text="Average speed")), 
         scene = list(
    xaxis = list(title = "traffic volume [veh/h]"),
    yaxis = list(title = "penetration [%]"),
    zaxis = list(title = "average speed [km/h]")))

I have two issues I could not solve:

  1. How to change the legend title (from avgspeed to Average speed)
  2. I would like to see the traffic volume going from 100 to 2000 (seq(100, 2000, by = 100)) on the xaxis and penetration from 0 to 100 (seq(0, 100, by = 10) on the y axis)

Solution

  • There are 2 questions, and 2 answers here...

    1. colorbar=list(title='Example 1') as in my code below.

    2. use range(c(100,2000)) and ticks = 100 as in my code below.

    sources:

    enter image description here

    code:

    library(tidyverse)
    library(plotly)
    
    
    data = matrix(data = rnorm(100),nrow = 10,ncol = 10)
    
    
    p = plot_ly() %>% 
      add_trace(z = ~data,
                name = 'ZED',
                type = 'surface',
                colorbar=list(title='Example 1'))
    
    p %>% 
      layout(
        scene = list(
          xaxis = list(title = 'xaxis',range = c(0,20)),
          yaxis = list(title = 'yaxis'),
          zaxis = list(title = 'zaxis')
        ),
        margin = list(
            b = 40, 
            l = 60, 
            r = 10, 
            t = 25
          )
      )