Arranging Views in Plotly R with Main Label

Viewed 38

Using the code snippet from the help page here, I'm trying to create a unique main label for each subplot but am not entirely successful. Any suggestions on how to do this?

library(plotly)
vars <- setdiff(names(economics), "date")
plots <- lapply(vars, function(var) {
  plot_ly(economics, x = ~date, y = as.formula(paste0("~", var))) %>%
    add_lines(name = var) %>% layout(title = paste("Title for", var, sep=' ')   )
})
subplot(plots, nrows = length(plots), shareX = TRUE, titleX = FALSE)
1 Answers

I wish I had noticed this question sooner! Here is one way that you can make this happen.

I took the titles out of the plot build. Otherwise, you'll get an error.

library(plotly)

vars <- setdiff(names(economics), "date")
plots <- lapply(vars, function(var) {
  plot_ly(economics, x = ~date, y = as.formula(paste0("~", var))) %>%
    add_lines(name = var) #%>% layout(title = paste("Title for", var, sep=' ')) 
})

Then I created a vector of the titles.

nms <- invisible(lapply(vars, function(v){paste0("Title for ", v)}) %>% unlist())

Here I used annotations to create title objects to add to the subplot.

annots = lapply(
  1:length(plots),
  function(j){
    list(x = .5,
         y = 1 - (j - 1) * .205,
         xanchor = "center",
         yanchor = "center",
         xref = "paper",
         yref = "paper",
         showarrow = F,
         text = nms[j])
  }
) 

subplot(plots, nrows = length(plots), shareX = TRUE, titleX = FALSE) %>% 
  layout(annotations = annots)

enter image description here

Related