Search code examples
rplotr-markdownknitrrnotebook

R notebook produce blank outputs before desired ones


I wrote a R code to display multiple images in one:

library(tidyverse)
library(fable)

myfit <- tsibbledata::global_economy |>
  filter(Code %in% c("CAF", "AUT")) %>%
  model(arima = ARIMA(Exports))

plot_list <- sapply(1:2, function(x) {myfit %>% slice(x) %>%
                                                  feasts::gg_tsresiduals() +
                                                  labs(title=x)})

gridExtra::grid.arrange(grobs = plot_list,
                        layout_matrix = rbind(c(1,1), c(2,3), c(4,4), c(5,6)))

But it generates 2 blank plots first at the sapply level inside the RStudio notebook.

2 blank plots first

I tried to add the invisible function, but that did not solve the problem:

[...]
plot_list <- sapply(1:2, function(x) {invisible(myfit %>% slice(x) %>%
                                                  feasts::gg_tsresiduals() +
                                                  labs(title=x))})
[...]

I also tried to add chunk options such as results='hide' or fig.keep='last'. The last chunk option works into the html ouput (Knit), not inside the RStudio notebook output, with the code above but that does not suit me because I will need to print several plots like this, not only the last.

How can I get rid of it?


Solution

  • That's just how feasts::gg_tresiduals() works --- it first creates a "new grid" on which to plot the three subplots later, which is printed directly by the Rstudio. If you really-really need to suppress the output, consider using R.devices::suppressGraphics(), e.g.

    plot_list <- 1:2 |>
        sapply(\(x) 
               myfit |>
                   slice(x) |>
                   feasts::gg_tsresiduals() |>
                   R.devices::suppressGraphics()
        )