---
title: "Spatiotemporal Visualization"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Spatiotemporal Visualization}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

# don't run on mac
os = ifelse(!Sys.info()[["sysname"]] == "Darwin", TRUE, FALSE)

# - don't run on CRAN
is_cran = ifelse(Sys.getenv("NOT_CRAN") != "", FALSE, TRUE)
```

{mlr3spatiotempcv} makes use of {plotly} to create the 3D plots for visualizing spatiotemporal folds created via the CLUTO algorithm.
Arranging multiple 3D plots in {plotly} is done via [3D subplots](https://plotly.com/r/3d-subplots/).

Unfortunately, {plotly}'s subplot implementation is not dynamic.
This means that multiple "scene" objects need to be specified in `plotly::layout()` to determine the coordinates of the respective subplot.
Depending on the number of chosen folds by the user in `autoplot()`, a different number of scenes with different coordinates needs to be given to align the plots properly.

Hence, manual action is needed to create a properly aligned grid of 3D plots.

Below is an example how to create a 2x2 grid showing four folds as 3D subplots.
It makes use of the returned 3D plotly objects which are returned in a list by `autoplot()`:

```{r, fig.align='center', eval=os&&!is_cran, fig.width=8, fig.height=9}
library(mlr3)
library(mlr3spatiotempcv)
task_st = tsk("cookfarm")
resampling = rsmp("sptcv_cluto", folds = 5, time_var = "Date")
resampling$instantiate(task_st)

pl = plot(resampling, task_st, c(1, 2, 3, 4),
  point_size = 3, axis_label_fontsize = 10)

# Warnings can be ignored
pl_subplot = plotly::subplot(pl)

plotly::layout(pl_subplot,
  title = "Individual Folds",
  scene = list(
    domain = list(x = c(0, 0.5), y = c(0.5, 1)),
    aspectmode = "cube",
    camera = list(eye = list(z = 2.5))
  ),
  scene2 = list(
    domain = list(x = c(0.5, 1), y = c(0.5, 1)),
    aspectmode = "cube",
    camera = list(eye = list(z = 2.5))
  ),
  scene3 = list(
    domain = list(x = c(0, 0.5), y = c(0, 0.5)),
    aspectmode = "cube",
    camera = list(eye = list(z = 2.5))
  ),
  scene4 = list(
    domain = list(x = c(0.5, 1), y = c(0, 0.5)),
    aspectmode = "cube",
    camera = list(eye = list(z = 2.5))
  )
)
```

```{r, eval=os&&!is_cran, echo=FALSE, results='asis'}
cat("(The actual graphic here is only rendered on the pkgdown site: please visit https://mlr3spatiotempcv.mlr-org.com.)")
```

```{r, eval=!os, results='asis', echo=FALSE}
cat("(The Cluto method does not work on macOS: please visit https://mlr3spatiotempcv.mlr-org.com to see the rendered plot.)")
```

Subplot titles can unfortunately not created dynamically.
However, there is also a manual workaround via [annotations](https://plotly.com/r/reference/#layout-annotations) show in this [RPubs post](https://rpubs.com/bcd/subplot-titles).
