Home > Software design >  Show single legend for grouped 3D lines in R plotly
Show single legend for grouped 3D lines in R plotly

Time:10-26

The default behavior of plotly is to automagically add several legends when the data is grouped by a variable. In my case, I would like set only one legend despite the group. Is this possible at all? The example below illustrates my question:

library(dplyr)
library(plotly)

lines_data <- tibble(
  x = c(rep(1, 10), rep(2, 10)),
  y = c(rep(5, 10), rep(7, 10)),
  z = rep(seq(from = 0.5, to = 5.7, length.out = 10), times = 2),
  gp = rep(letters[1:2], each = 10)
)

plotly::plot_ly(
  data = lines_data,
  x = ~x, 
  y = ~y,
  z = ~z,
  split = ~gp,
  type = "scatter3d",
  mode = "lines",
  line = list(color = "red", width = 10)
)

plolty 3D lines

I would like to have a single legend that says "line".

Thank you for your help.

CodePudding user response:

There are many ways to accomplish this in R, normally. At this point, I believe it just doesn't work for the type scatter3d. I have a workaround, though.

This uses the library htmlwidgets. I didn't call the library; I just attached it to the function call. The onRender call looks for the last trace in the legend and removes it. If you wanted to remove the first element, you would just change last to first. (JQuery is sneaky like that...with the 'literalness')

plotly::plot_ly(
  data = lines_data,
  x = ~x, 
  y = ~y,
  z = ~z,
  split = ~gp,
  type = "scatter3d",
  mode = "lines",
  name = "line",
  legendgroup = "line",       # added so you can still toggle traces
  line = list(color = "red", width = 10)) %>% 
  htmlwidgets::onRender("function(){
    $('svg g.traces').last().remove() 
  }")

enter image description here

  • Related