'Hide plots in plotly subplot if empty

I am looking for an easy way how to hide plotly graph inside subplot() if it is empty - meaning the plot_ly() function has been called on an empty dataframe. The intended usage is when some filtering inside shiny app returns an empty dataframe, I'd prefer for the empty plot to not be displayed (instead of displaying empty plot or an error message).

library(dplyr)
library(plotly)
library(lubridate)
t1 = 
  tibble(x = rnorm(30),
         d = seq(today() - 29, today(), 
                 by = "1 day"))

t2 = 
  tibble(x = rnorm(30),
         d = seq(today() - 29, today(), 
                 by = "1 day")) %>%  
  filter(d > today()) # you apply some filter in shiny that results in an empty dataset

p1 = 
  t1 %>% 
  plot_ly(x = ~d, y = ~x)


p2 = 
  t2 %>% 
  plot_ly(x = ~d, y = ~x)
 
subplot(p1, p2, shareX = T)

I tried testing for an empty dataset using nrow() and needs(). But it always returns NULL objects which crashes subplot() with an error.

Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source