Search code examples
r3dplotlypca

Change Legend Titles in R Plotly


I am using the following code to generate a 3D scatter plot with vectors in Plotly - R studio. Currently, the legend labels are displayed as "trace 1, trace 2, etc", but I'd like to change that with my own text. Any idea how to achieve this?

#Define the data from df to be plotted, basically three columns of a data frame
x = df[,1]
y = df[,2]
z = df[,3]

#Scatter and Axis Labels
p <- plot_ly() %>%
  add_trace(x=x, y=y, z=z,
            type="scatter3d", mode="markers",
            marker = list(color=y, 
                          colorscale = 'Viridis', 
                          opacity = 0.02,showscale = F)) %>% 
  layout(title = "TITLE",
         scene = list(
           xaxis = list(title = "LABEL 1"), 
           yaxis = list(title = "LABEL 2"), 
           zaxis = list(title = "LABEL 3")))


#Add Vectors to the Plot  
for (k in 1:nrow(df_vector)) {
  x <- c(0, df_vector[k,1])
  y <- c(0, df_vector[k,2])
  z <- c(0, df_vector[k,3])
  p <- p %>% add_trace(x=x, y=y, z=z,
                       type="scatter3d", mode="lines",
                       line = list(width=8),
                       opacity = 1)
}

Solution

  • Use the name argument to add_trace. I've mocked up some data below, but in future bear in mind that it's helpful to include easily-readable example data using (eg) dput.

    library(plotly)
    ## Reproducible by setting RND seed
    set.seed(42)
    ## Define the data from df to be plotted, basically three columns of a data frame
    df <- data.frame(x = rnorm(100), y = rnorm(100), z = rnorm(100))
    
    ## Scatter and Axis Labels
    p <- plot_ly(df) %>%
        add_trace(x=~x, y=~y, z=~z,
            type="scatter3d", mode="markers",
            name = "markers"
            # ,
            # marker = list( 
            #     colorscale = 'Viridis', 
            #     opacity = 0.02,showscale = F)
            ) %>% 
        layout(title = "TITLE",
            scene = list(
                xaxis = list(title = "LABEL 1"), 
                yaxis = list(title = "LABEL 2"), 
                zaxis = list(title = "LABEL 3")))
    
    
    #Add Vectors to the Plot  
    for (k in 1:nrow(df[1:3, ])) {
        x <- c(0, df[k, 1])
        y <- c(0, df[k, 2])
        z <- c(0, df[k, 3])
        p <- p %>% add_trace(x=x, y=y, z=z,
            name = paste("my trace name", k),
            type="scatter3d", mode="lines",
            line = list(width=8),
            opacity = 1)
    }