plotly R: keep categorical column names, but don't plot them

Viewed 921

With this object:

fullDT <-
structure(list(QuarterAndYear = structure(1:12, .Label = c("2015 Q1", 
"2015 Q2", "2015 Q3", "2015 Q4", "2016 Q1", "2016 Q2", "2016 Q3", 
"2016 Q4", "2017 Q1", "2017 Q2", "2017 Q3", "2017 Q4"), class = "factor"), 
    `TRUE` = c(3, 0, 1, 0, 2, 1, 0, 1, 3, 0, 0, 0), `FALSE` = c(0, 
    0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0), OTHER = c(0, 0, 0, 0, 0, 
    0, 0, 0, 0, 0, 0, 0)), class = c("data.table", "data.frame"
), row.names = c(NA, -12L), sorted = "QuarterAndYear")

I can plot a graph like this:

plot_ly(fullDT,x = ~QuarterAndYear,y=0,type = "scatter",mode = "lines")%>%add_trace(y = ~`TRUE`)%>%add_trace(y = ~`FALSE`)%>%add_trace(y = ~OTHER)%>%layout(xaxis= list(type = "category"))

Which gives me almost everything I need. Namely, it gives me the first column category names as tick labels for the x-axis. However, the "trace 0" shows up in the legend. If I remove this:

plot_ly(fullDT,type = "scatter",mode = "lines")%>%add_trace(y = ~`TRUE`)%>%add_trace(y = ~`FALSE`)%>%add_trace(y = ~OTHER)%>%layout(xaxis= list(type = "category"))

the x-axis is now unlabeled. I'm not sure how to get both of these to work simultaneously. I could do some sort of legend magic, maybe? but I feel like theres a cleaner way.

I've tried some layout(xaxis = list(...)) stuff to no avail...

1 Answers

When drawing a plot, you can start empty and add as you go. When you plot the x with no y, it adds the trace0. So draw the plot you want, then add the traces using the colNames subset, remove your x from it, and trace in a loop.

p <- plot_ly(type = 'scatter', mode = 'lines') %>% 
  layout(yaxis = list(title = "TRUE"))
colNames <- names(fullDT)
colNames <- colNames[-which(colNames == 'QuarterAndYear')]
for(trace in colNames){
  p <- p %>% plotly::add_trace(data = fullDT, x = ~ QuarterAndYear, y = as.formula(paste0("~`", trace, "`")), name = trace)
  print(paste0("~`", trace, "`"))
}
p

Related