Jelle Jansen
Jelle Jansen

Reputation: 478

legendgroup plotly R subplot

Hello I have the following code to build a subplot. I want to group the legend so only "spot" and "avg base" appear once. I have tried this using legendgroup but can't get it to work.

mom.base <- mtcars[c(1,2,3),c(1,2,3)]
spt <- mtcars[c(1,2,3),c(4,5,6)]

mom.base <- as.xts(mom.base, order.by = as.Date(c("2017-01-01","2017-01-02","2017-01-03")))
spt <- as.xts(spt, order.by = as.Date(c("2017-01-01","2017-01-02","2017-01-03")))


plot_list <- NULL
for (i in 1:3){
  mom.plot <- mom.base[,i]
  spt.plot <- spt[,i]
  df <- cbind(mom.plot,spt.plot)
  colnames(df) <- c("avgbase","spot")

  p <- plot_ly((fortify(df)), x = ~factor(Index), y = ~ spot, 
               type = 'scatter', mode = 'lines', name = 'spot') %>% 
    add_trace(x = ~factor(Index), y = ~ avgbase, name = "avg base", line = list(dash = "dash")) %>%  
    layout(title = "test",
           xaxis = list(title = ''),
           yaxis = list(title = names(mom.plot)))
  plot_list[[i]] = p
}
subplot(plot_list, nrows=1, titleY = TRUE, shareX = TRUE)

link to image with legend

Upvotes: 1

Views: 3364

Answers (1)

Jelle Jansen
Jelle Jansen

Reputation: 478

enter image description hereanswered using answer found here

comes down to this:

      p1 <- df[[1]] %>% 
    group_by(type) %>% 
    plot_ly(x=~factor(Index), y = ~value, color = ~type, colors = c("#132B43", "#56B1F7"), type = 'scatter', mode = 'lines')

  p2 <- df[[2]] %>% 
    group_by(type) %>% 
    plot_ly(x=~factor(Index), y = ~value, color = ~type, colors = c("#132B43", "#56B1F7"), type = 'scatter', mode = 'lines', showlegend = F)

  p3 <- df[[3]] %>% 
    group_by(type) %>% 
    plot_ly(x=~factor(Index), y = ~value, color = ~type, colors = c("#132B43", "#56B1F7"), type = 'scatter', mode = 'lines', showlegend = F)

subplot(p1,p2,p3,nrows=1,titleY = TRUE, shareX = TRUE, margin = c(0.085,0.01,0.1,0.1))

Upvotes: 1

Related Questions