---
author: "Nicolau Manubens"
date: "`r Sys.Date()`"
output: html_document
vignette: >
  %\VignetteEngine{R.rsp::md}
  %\VignetteIndexEntry{Visualisation}
  %\usepackage[utf8]{inputenc}
---
Visualisation
=============

s2dverification contains a set of functions to plot data at every stage of the 
verification process, most based directly on R graphics plotting tools.
These functions are essential to:
 - Quickly inspect the results of a newly produced experiment, i.e. to check 
the physical consistency of the results.
 - Assess the added value of a new prediction system, i.e. to compare new 
results with a reference (observation, reconstruction or other experiment).
 - Assess visually the significance of results, i.e. to display in a 
user-friendly way confidence intervals and other statistics.

The visualisation functions, most with a name following the pattern 
`Plot*()`, can be grouped as a function of the kind of plot they provide: 
 - [**Plotting time series**](#time_series): `PlotClim()`, `PlotAno()`, 
`PlotVsLtime()`, `Plot2VarsVsLTime()`, `PlotBoxWhisker()` and `PlotACC()`.
 - [**Plotting maps**](#maps): `PlotEquiMap()`, 
`PlotStereoMap()`, `AnimateMap()`, `PlotLayout()` and `PlotSection()`.

To master these functions it is convenient to have in mind the common array 
dimension structure used throughout in s2dverification and how it evolves as 
the data objects go through the statistics and verification stages. For that 
you can review the introduction in [**Data retrieval**](data_retrieval.md) and 
the sections [**Statistics**](statistics.md) and 
[**Verification**](verification.md).

Next an explanation of which situations they fit the best, details of the 
options they provide and short examples of usage. The data used hereunder will
be the same as in [**Data retrieval**](data_retrieval.md):
```r
library(s2dverification)
expA <- list(name = 'experimentA',
             path = file.path('/path/to/experiments/$EXP_NAME$/monthly_mean',
                              '$VAR_NAME$/$VAR_NAME$_$START_DATE$.nc'))
expB <- list(name = 'experimentB',
             path = file.path('/path/to/experiments/$EXP_NAME$/monthly_mean',
                              '$VAR_NAME$/$VAR_NAME$_$START_DATE$.nc'))
obsX <- list(name = 'observationX',
             path = file.path('/path/to/observations/$OBS_NAME$/monthly_mean',
                              '$VAR_NAME$/$VAR_NAME$_$YEAR$$MONTH$.nc'))
sdates <- paste0(1991:2000, '1101')
data <- Load('tas', list(expA, expB), list(obsX),
             sdates = sdates,
             leadtimemin = 2, leadtimemax = 13,
             latmin = -10, latmax = 60,
             lonmin = 100, lonmax = 250,
             output = 'areave', grid = 't106grid',
             method = 'distance-weighted')
ano <- Ano_CrossValid(data$mod, data$obs, memb = FALSE)
```

Plotting time series<a name="time_series"></a>
--------------------

All the functions devoted to plotting time series have some common traits and
parameters:
 - Aimed to plot monthly, seasonal or yearly time series, adjustable via the 
parameter `freq`.
 - All of them generate plots and save them to PostScript files the path and 
file name of which you have to provide to the `fileout` parameter. Can plot in
a presentation oriented style or in a paper oriented style, adjustable with the
parameter `biglab`.
 - Can plot a legend automatically, adjustable via the parameters `leg`, 
`listexp` and `listobs`/`listvar` in `PlotVsLTime()`, `Plot2VarVsLtime()` and 
`PlotClim()` or via the parameter `legends` in `PlotAno()` and `PlotACC()`.
 - Accept any additional parameters via the parameter `...` to be sent to 
the underlying R graphics `plot()` function for a fine tuning.

**Note:** A general purpose time-series plotting function, `PlotTimeSeries()`, 
is currently being developed. This function will agglomerate all the 
functionality required to generate the plots resulting from all the currently 
available functions in `s2dverification` and will be based on the `ggplot2` 
package. The current functions will be kept  as they are but will simply be an 
interface to `PlotTimeSeries()`. See 
[**this report**](https://earth.bsc.es/gitlab/es/s2dverification/blob/develop-PlotTimeSeries/inst/doc/PlotTimeSeries/PlotTimeSeries.pdf) 
for an extended explanation and examples of the new 
time-series plotting function.

### Plotting climatologies

`PlotClim()` takes as inputs an experimental and an observational array of 2 
to 3 dimensions each:
```r
  c(n. of datasets, n. of members, n. of forecast times)
```
the second one being optional. This means that the latitude and longitude 
dimensions must have been removed either because working on area-averages or
because working on a single grid point and that the starting dates dimension
must have also been removed either because willing to plot data of a single
starting date or because working on averages across starting dates, i.e. 
climatologies (see [**Statistics**](statistics.md)).

A curve is plotted for each member of each experiment or observation. The 
members of a same experiment or observation are equally coloured whereas the 
different experiments and observations are plotted with different colours.  
`PlotClim()` assumes by default that the provided climatologies start in 
January. Otherwise the initial month can be specified with the parameter 
`monini`:

```r
clim <- Clim(data$mod, data$obs)
PlotClim(clim$clim_exp, clim$clim_obs, monini = 12,
         toptitle = "Per-pair 'tas' climatologies, North Pacific",
         ytitle = "K",
         listexp = c('Experiment A', 'Experiment B'),
         listobs = c('Observation X'),
         fileout = "vis_clim_expA_expB_obsX.png")
```
<img src="vis_clim_expA_expB_obsX.png" width="600" />

### Plotting multi-member raw data or anomalies

`PlotAno()` takes also two data arrays as inputs with 4 dimensions each:
```r
  c(n. of datasets, n. of members, n. of starting dates, n. of forecast times)
```
all being mandatory. It means that if willing to plot single member data or
data from a single starting date, the corresponding dimensions still have to
be present in the provided arrays; `InsertDim()` helps in that.

The data in the provided arrays can be raw data, anomalies or any other kind
of data, as long as it is arranged with the required dimensions.  
For each run of a model (i.e. for each group of members of a same starting 
date from one experiment) a thick curve with the ensemble mean is plotted 
together with a finer curve for each ensemble member, unless any of these are 
disabled with `ensmean` or `memb`, respectively. The area delimited by the 
minimum and maximum ensemble values at each forecast time is filled in with a 
different colour for each starting date, unless disabled with `fill`.  
A fine black curve is plotted with the observational data alongside each 
starting date.  
A separate new plot is created for each experimental dataset provided in the
experimental data array.

The starting dates the provided data corresponds to must be provided with the
parameter `sdates` for them to be plotted accordingly along the x axis. 

`linezero` draws a line at y = 0 to help perceiving whether the anomaly is 
positive or negative, `vlines` draws vertical lines at any specified abscissae
and `points` will draw all the curves in pointed style.

```r
selected_sdates <- gsub('1101', '1201', sdates)
PlotAno(data$mod, data$obs, selected_sdates,
        toptitle = paste0(c("Experiment A", "Experiment B"),
                          ": Raw 'tas' over North Pacific"),
        ytitle = c("K", "K"),
        fileout = paste0("vis_raw_exp", c("A", "B"), "_obsX.png"))
```
<img src="vis_raw_expA_obsX.png" width="600" />
<img src="vis_raw_expB_obsX.png" width="600" />

### Plotting statistics and scores

The functions `PlotVsLTime()`, `Plot2VarsVsLTime()` and `PlotACC()` serve to
plot time series of variables obtained with the 
[**Statistics**](statistics.md) or [**Verification**](verification) modules 
that yield forecast time series of indices or scores that usually come 
together with confidence intervals and significance levels.

`PlotVsLTime()` takes as main input an array of data with the following 
dimensions:
```r
  c(n. of experiments, n. of observational datasets, 3 or 4, n. of forecast times)
```
the second one being optional and the third one corresponding to the lower 
limit of a confidence interval, the measurement or index or score, the upper
limit of a confidence interval and, optionally, a significance level. This
dimension format requires that the index or score to be plotted is computed
along the actual time (starting dates) and over the average of the ensemble 
members, either at a single grid point or from an area average.

A curve is drawn for each pair of (experiment, observation) with a different 
colour and line style. The scores or indices that correspond to a same 
experiment are coloured equally but a different line style is used for each 
observation that experiment has been compared to when computing the index or 
score. The confidence intervals are plotted with a finer line of the same
colour and line style, unless disabled with `show_conf`. To plot the 
signification level instead the parameter `siglev` can be set to `TRUE`.

As in `PlotClim()`, each curve is defined along the forecast times and is
assumed to start at January. Otherwise it can be adjusted via `monini`. 
Additionally the number of ticks along the x axis can be adjusted with 
`nticks` and any number of horizontal lines can be drawn by specifying the 
target ordinates to `hlines`. 

`PlotVsLTime()` can be useful in the following situations:
 - To plot `Trend()` or `Regression()` fitted coefficients of ensemble averages 
of data at a single grid cell or averaged over a region:

```r
trend_exp <- Trend(Mean1Dim(ano$ano_exp, 2))
trend_obs <- Trend(Mean1Dim(ano$ano_obs, 2))
PlotVsLTime(trend_exp$trend,
            toptitle = "Slopes of trends of 'tas' over North Pacific",
            ytitle = "K/year",
            monini = 12, freq = 1,
            listexp = c('Experiment A', 'Experiment B'),
            fileout = 'vis_trend_expA_expB.png')
```
```r
ano_expA_Y <- Regression(Mean1Dim(plyr::take(ano$ano_exp, 1, 1), 2),
                         Mean1Dim(plyr::take(ano$ano_exp, 1, 2), 2))
PlotVsLTime(ano_expA_Y$regression,
            toptitle = "Regr. slopes of exp. A with exp. B, N. Pacific",
            ytitle = "K/year",
            monini = 12, freq = 1, leg = FALSE,
            fileout = 'vis_regression_expA_expB.png')
```
<img src="vis_trend_expA_expB.png" width="600" />
<img src="vis_regression_expA_expB.png" width="600" />
 - To plot the `Spread()` across ensemble members and starting dates of area 
averaged data (interquartile range, maximum minus minimum, standard deviation
or median absolute deviation):

```r
spread <- Spread(ano$ano_exp, posdim = c(2, 3))
PlotVsLTime(spread$iqr,
            toptitle = "IQR across members and starting dates over North Pacific",
            ytitle = "K", sizetit = 0.7,
            monini = 12, freq = 1,
            listexp = c('Experiment A', 'Experiment B'),
            fileout = 'vis_iqr_expA_expB.png')
PlotVsLTime(spread$maxmin,
            toptitle = "Max.-min. across members and s. dates over North Pacific",
            ytitle = "K", sizetit = 0.7,
            monini = 12, freq = 1,
            listexp = c('Experiment A', 'Experiment B'),
            fileout = 'vis_maxmin_expA_expB.png')
PlotVsLTime(spread$sd,
            toptitle = "S. deviation across members and s. dates over North Pacific",
            ytitle = "K", sizetit = 0.7,
            monini = 12, freq = 1,
            listexp = c('Experiment A', 'Experiment B'),
            fileout = 'vis_sd_expA_expB.png')
PlotVsLTime(spread$iqr,
            toptitle = "MAD across members and starting dates over North Pacific",
            ytitle = "K", sizetit = 0.7,
            monini = 12, freq = 1,
            listexp = c('Experiment A', 'Experiment B'),
            fileout = 'vis_mad_expA_expB.png')
```
<img src="vis_iqr_expA_expB.png" width="600" />
<img src="vis_maxmin_expA_expB.png" width="600" />
<img src="vis_sd_expA_expB.png" width="600" />
<img src="vis_mad_expA_expB.png" width="600" />
 - To plot the correlation (`Corr()`) and RMSE (`RMS()`) between experiments 
(averaged across ensemble members) and observations:

```r
corr <- Corr(Mean1Dim(ano$ano_exp, 2), Mean1Dim(ano$ano_obs, 2))
PlotVsLTime(corr,
            toptitle = "Time correlation with observation X, over North Pacific",
            ytitle = "K", sizetit = 0.7,
            monini = 12, freq = 1,
            listexp = c('Experiment A', 'Experiment B'),
            fileout = 'vis_corr_expA_expB_obsX.png')
```
```r
rms <- RMS(Mean1Dim(ano$ano_exp, 2), Mean1Dim(ano$ano_obs, 2))
PlotVsLTime(rms,
            toptitle = "RMSE with observation X, over North Pacific",
            ytitle = "K", sizetit = 0.7,
            monini = 12, freq = 1,
            listexp = c('Experiment A', 'Experiment B'),
            fileout = 'vis_rms_expA_expB_obsX.png')
```
<img src="vis_corr_expA_expB_obsX.png" width="600" />
<img src="vis_rms_expA_expB_obsX.png" width="600" />
 - To plot the ratio between the RMSE of the ensemble mean of two experiments 
with a same observation at a single grid point or area averaged:

```r
ratio_rms <- RatioRMS(Mean1Dim(ano$ano_exp[1, , , ], 1),
                      Mean1Dim(ano$ano_exp[2, , , ], 1),
                      ano$ano_obs[1, 1, , ])
ratio_rms2 <- array(dim = c(1, 4, dim(ratio_rms)[2]))
ratio_rms2[1, c(2, 4), ] <- ratio_rms
PlotVsLTime(ratio_rms2,
            toptitle = "RMSE exp. A / RMSE exp. B (against obs. X), over N. Pacific",
            ytitle = "K", sizetit = 0.7,
            monini = 12, freq = 1, siglev = TRUE, leg = FALSE,
            fileout = 'vis_ratiorms_expA_expB_obsX.png')
```
<img src="vis_ratiorms_expA_expB_obsX.png" width="600" />
 - To plot the ratio between the ensemble spread of the experiments and their 
RMSE against the observations (`RatioSDRMS()`) at a single grid point or area
averaged:

```r
ratio_sdrms <- RatioSDRMS(ano$ano_exp, ano$ano_obs)
ratio_sdrms2 <- array(dim = c(dim(ratio_sdrms)[1:2], 4, dim(ratio_sdrms)[4]))
ratio_sdrms2[, , c(2, 4), ] <- ratio_sdrms
PlotVsLTime(ratio_sdrms2,
            toptitle = "S. dev. over members and s. dates / RMSE, over North Pacific",
            ytitle = "K", sizetit = 0.7,
            monini = 12, freq = 1, siglev = TRUE,
            listexp = c('Experiment A', 'Experiment B'),
            fileout = 'vis_ratiosdrms_expA_expB_obsX.png')
```
<img src="vis_ratiosdrms_expA_expB_obsX.png" width="600" />

In this example, the ratio SD / RMS is calculated for the experiment A only 
but against two observational datasets:

```r
ratio_sdrms <- RatioSDRMS(plyr::take(ano$ano_exp, 1, 1),
                          abind::abind(ano$ano_obs, 
                                       ano$ano_obs + rnorm(length(ano$ano_obs), 0, 0.1), 
                                       along = 1))
ratio_sdrms2 <- array(dim = c(dim(ratio_sdrms)[1:2], 4, dim(ratio_sdrms)[4]))
ratio_sdrms2[, , c(2, 4), ] <- ratio_sdrms
PlotVsLTime(ratio_sdrms2,
            toptitle = "S. dev. over members and s. dates / RMSE, over North Pacific",
            ytitle = "K", sizetit = 0.7,
            monini = 12, freq = 1, siglev = TRUE,
            listexp = c('Experiment A'),
            listobs = c('Observation X', 'Observation X + rnorm(n, 0, 0.1)'),
            fileout = 'vis_ratiosdrms_expA_obsX_obsXrnorm.png')
```
<img src="vis_ratiosdrms_expA_obsX_obsXrnorm.png" width="600" />
 - To plot `RMSSS()` of ensemble mean at a single grid point or area averaged:

```r
rmsss <- RMSSS(Mean1Dim(ano$ano_exp, 2), Mean1Dim(ano$ano_obs, 2))
rmsss2 <- array(dim = c(dim(rmsss)[1:2], 4, dim(rmsss)[4]))
rmsss2[, , c(2, 4), ] <- rmsss
PlotVsLTime(rmsss2,
            toptitle = "RMSSS with observation X, over North Pacific",
            ytitle = "K", sizetit = 0.7,
            monini = 12, freq = 1, siglev = TRUE,
            listexp = c('Experiment A', 'Experiment B'),
            fileout = 'vis_rmsss_expA_expB_obsX.png')
```
<img src="vis_rmsss_expA_expB_obsX.png" width="600" />
 - To plot effective number of independent data (`Eno()`):

```r
eno <- Eno(Mean1Dim(ano$ano_exp, 2), posdim = 2)
eno2 <- array(dim = c(dim(eno)[1], 4, dim(eno)[2]))
eno2[, 2, ] <- eno
PlotVsLTime(eno2,
            toptitle = "Effective n. of independent data, over North Pacific",
            sizetit = 0.7,
            monini = 12, freq = 1, siglev = FALSE, show_conf = FALSE,
            listexp = c('Experiment A', 'Experiment B'),
            fileout = 'vis_eno_expA_expB.png')
``` 
<img src="vis_eno_expA_expB.png" width="600" />

`Plot2VarsVsLTime()` allows to plot two indices or scores at a time on the same
plot, each with its confidence intervals. It accepts as inputs arrays of only 
3 dimensions:
```r
  c(n. of experiments, 3/4, n. of forecast times)
```
i.e., it accepts only indices or scores from a set of experimental datasets 
against a single observation.
Its options are identical to the ones of `PlotVsLTime()` except that the 
parameter for specifying legends for observations (`listobs`) is replaced by a 
parameter to put a legend to distinguish the plotted variables, `listvars`.
```
Plot2VarsVsLTime(corr[, 1, 1:3, ], rms[, 1, , ],
                 toptitle = "Time correlation and RMSE with obs. X, over North Pacific",
                 ytitle = "K", sizetit = 0.7,
                 monini = 12, freq = 1,
                 listexp = c('Experiment A', 'Experiment B'),
                 listvars = c('Corr', 'RMSE'),
                 fileout = 'vis_corr_rms_expA_expB_obsX.png')
```
<img src="vis_corr_rms_expA_expB_obsX.png" width="600" />

`PlotACC()`, in contrast to `PlotVsLTime()`, accepts an additional dimension
for the starting dates in the input and the dimension of the confidence 
intervals is positioned at the end in place of the latitudes and longitudes, 
as provided by `ACC()`:
```r
  c(n. of experiments, n. of observational datasets, n. of starting dates, n. of forecast times, 4)
```
The ACCs and confidence intervals of all forecast times and starting dates of 
all experiments are plotted. In contrast to `PlotAno()`, the consecutive 
starting dates are overlapped so as to make it easy to compare their behaviour
overall.

All the starting dates of an experiment are painted with the same colour. 
There are two possible styles, switchable via the parameter `points`:
 - Drawing curves along forecast times, as in `PlotVsLTime()`. In that case 
`fill` can enable filling the area limited by the confidence intervals.
 - Drawing a point for each forecast time, with vertical lines joined to the
extremes of the confidence interval, limited with notches (default).
Besides, `linezero` draws a line at ordinate 0 and `vlines` draws vertical
lines at any specified set of abscissae.

```r
map_data <- Load('tas', list(expA, expB), list(obsX),
                 sdates = sdates,
                 leadtimemin = 2, leadtimemax = 13,
                 latmin = -30, latmax = 60,
                 lonmin = -90, lonmax = 20,
                 output = 'lonlat', grid = 't106grid',
                 method = 'distance-weighted')
ano <- Ano_CrossValid(map_data$mod, map_data$obs, memb = FALSE)
acc <- ACC(ano$ano_exp, ano$ano_obs)
PlotACC(acc$ACC, selected_sdates, 
        toptitle = "Spatial anomaly corr. coeff. with obs X over Atlantic",
        ytitle = "K", sizetit = 0.7, freq = 1,
        legends = c('Experiment A', 'Experiment B'),
        fileout = 'vis_acc_expA_expB_obsX.png')
```
<img src="vis_acc_expA_expB_obsX.png" width="600" />

`PlotBoxWhisker()`

PlotTimeSeries
-------------
**Note:**  PlotTimeSeries is currently still under development, but a beta-version can be downloaded from the s2dverification gitlab page, from the develop-PlotTimeSeries branch.

The function, `PlotTimeSeries`, is an agglomerate of the time series plotting functions from previous versions of `s2dverification`, with enhanced functionality. The function is still evolving, to ensure that it is compatible with the common R data structure which is currently being discussed within the QA4Seas project. 

In brief, the `PlotTimeSeries` function takes common data model (CDM) objects or arrays of any number of (named) dimensions and creates scatter plots or draws curves along them, as well as plotting their means and max/mins. The inputted data can include metadata that is automatically incorporated into the plot, such as the name of the plotted variable, the start dates of a set of provided seasonal forecasts, the date at each forecast time step or the names of the members. The user can manually specify which dimensions to colour or style along, but the function is designed to anticipate the user's requirements. The advantages of the new function are its increased ease-of-use and versatility, as well as the improved quality of the final plots due to the use of the `ggplot2` package. 

### Plotting anomalies and climatologies

`PlotTimeSeries` takes CDM objects or arrays as input, with the following dimensions: 

```r
c(dataset, member, start dates, forecast times).
```
Objects with different numbers of dimensions, or different orderings can also be handled by the function, by appropriate specification of the `curves_along`, `mean_along`, and `colour_along` parameters. When a CDM is inputted, the default setting is for the function to calculate the multi-member means for each dataset and start date and plot them in different colours, and shade between the min/max.

```r
library(s2dverification)
PlotTimeSeries(ano_exp) + PlotTimeSeries(ano_obs, add = T)
```

<a name="time_series"></a>
<img src="vis_ano_exp_obs.png" width="600" />
--------------------

The `PlotTimeSeries` function has read the x- and y- axis labels, the title and the legend from the metadata automatically. By default, a horizontal line is plotted along `y = 0`, and this line can be shifted or removed with `intercept`. Layers can be added by selecting `add = TRUE`, as in the above example, where the dataset of observations have been added to the plot.  The user can plot the geometric objects (the mean, confidence intervals, curves etc.) along any of the dimensions, as well as adding points, changing the linestyles and removing any of the objects.  For example the curves for the individual members can be replaced with points, with different shapes for the different members, and the shading between the minimum and maximum can be removed as follows.

```r
PlotTimeSeries(ano_exp, minmax_along = NA, points = T, shape_along = 2, curves_along = NA)
```

<a name="time_series_2"></a>
<img src="vis_ano_exp_points.png" width="600" />


### Plotting scores and sample statistics

If the input to the function is a CDM object containing sample statistics, e.g. the correlation, then a plot of these statistics and their associated confidence intervals (if availble) will automatically be plotted as error bars. Alternatively, the user can specify the confidence intervals to be plotted as dashed lines (and the sample statistic as a solid line) with `interval_type`.

```r                
PlotTimeSeries(Corr)
PlotTimeSeries(Corr, interval_type = "line")
```
<a name="confidence_intervals"></a>

<img src="vis_error_bar.png" width="600" />
<img src="vis_conf_interval_exp.png" width="600" />


### Conclusions

The use of the R package `ggplot2` in `PlotTimeSeries` results in high quality time series plots, as well as simplifying the creation of sophisticated graphics. Another benefit of the `ggplot2` package is that the user can easily modify the output of `PlotTimeSeries` to configure the plot title, axis labels and legends. 

The function is being refined to accommodate a wide range of user requirements. This work is being conducted alongside changes currently being made to the `s2dverification` and `downscaleR` packages to ensure a common R data structure. 


Plotting maps<a name="maps"></a>
-------------

This group of functions allows to plot grid data (i.e. defined over latitudes 
and longitudes) on a rectangular equidistant projection or on a stereographic 
projection (as of s2dverification v2.5.0) as well as depth sections (i.e. 
defined over latitudes/longitudes and depth levels).

Regarding the functions to plot maps, by default each grid point is drawn on a 
world map with a colour as a function of the magnitude of the provided field, 
index or score at that point. While `PlotEquiMap()` and `PlotStereoMap()` plot 
data of a single forecast time, `AnimateMap()` creates an animation with the 
plotted maps of all forecast times obtained with one of the previous functions at 
choice.

`PlotEquiMap()` and `PlotStereoMap()` share some traits:
 - Both expect a data matrix in the parameter `var` of dimensions 
`c(n. of latitudes, n. of longitudes)`, `lat` with a vector with the latitudes 
of the centers of the grid cells and `lon`, a vector with the longitudes. 
`Load()` already provides these in the correct format, through the components 
`$lon` and `$lat`.
 - The N colours to paint the grid cells with (via `cols`) as well as the N +
1 threshold magnitudes (via `brks`) that will allow to assign each grid cell 
value one of the N colours. The colour for any missing values can be adjusted 
with `colNA`.
 - Whether to fill the map continents or only draw coast wires can be adjusted
with `filled.continents`.
 - A matrix of `dots` can be plotted over the drawn map to, e.g., highlight 
cells where a skill has been greatest or most significant.
 - A legend can be drawn (unless disabled with `drawleg`) and the amount of 
ticks on that legend can be adjusted with `subsampleg`.
 - They accept any additional parameters via the parameter `...` to be sent to
the underlying R graphics `image()` function for a fine tuning.

### PlotEquiMap()

Next some examples of maps obtained with `PlotEquiMap()`:
```r
PlotEquiMap(Mean1Dim(map_data$mod, 2)[1, 1, 1, , ], map_data$lon, map_data$lat,
            toptitle = "Exp. A 'tas', s. date: 1990-11-01, f. time: 1 month", 
            units = "K", fileout = 'vis_equimap_raw_expA.png')

PlotEquiMap(Mean1Dim(map_data$obs, 2)[1, 1, 1, , ], map_data$lon, map_data$lat,
            toptitle = "Obs. X: 'tas', 1990-12-01", 
            units = "K", filled.continents = FALSE, fileout = 'vis_equimap_raw_obsX.png')
```
<img src="vis_equimap_raw_expA.png" width="600" />
<img src="vis_equimap_raw_obsX.png" width="600" />

```r
PlotEquiMap(Mean1Dim(map_data$mod, 2)[1, 1, 1, , ], map_data$lon, map_data$lat,
            toptitle = "Exp. A 'tas', s. date: 1990-11-01, f. time: 1 month", 
            units = "K", brks = 100, bar_limits = c(255, 300),
            filled.continents = 'black',
            fileout = 'vis_equimap_cols_raw_expA.png')

PlotEquiMap(Mean1Dim(map_data$obs, 2)[1, 1, 1, , ], map_data$lon, map_data$lat,
            toptitle = "Obs. X 'tas', 1990-12-01", 
            units = "K", brks = 100, bar_limits = c(255, 300),
            filled.continents = FALSE, 
            fileout = 'vis_equimap_cols_raw_obsX.png')
```
<img src="vis_equimap_cols_raw_expA.png" width="600" />
<img src="vis_equimap_cols_raw_obsX.png" width="600" />


Or, as seen in the example from [**Snippet 2**](snippets.md#snippet2):<a name="snippet2"></a>

<img src="snip2_equimap_corr_raw_expA_obsX.png" width="600" />
<img src="snip2_equimap_corr_raw_expB_obsX.png" width="600" />


`PlotEquiMap()` has some other additional features:
 - Drawing contour lines: `square` allows to smooth the borders of each 
coloured region and draws contour lines and figures. The contours can be 
adjusted by providing a matrix to `contours` with dimensions 
`c(n. of longitudes, n. of latitudes)`. The contours of the data in that 
matrix will be drawn over the map, using the thresholds provided in `brks2`.
This is useful to plot the contours of the original data without border 
smoothing, to plot only some of the default contours or to plot other contours 
defined by another field.  

```r
PlotEquiMap(Mean1Dim(map_data$mod, 2)[1, 1, 1, , ], map_data$lon, map_data$lat,
            toptitle = "Exp. A 'tas', s. date: 1990-11-01, f. time: 1 month", 
            units = "K", brks = 100, bar_limits = c(255, 300), square = FALSE,
            fileout = 'vis_equimap_contour_raw_expA.png')

PlotEquiMap(Mean1Dim(map_data$obs, 2)[1, 1, 1, , ], map_data$lon, map_data$lat,
            toptitle = "Obs. X 'tas', 1990-12-01", 
            units = "K", brks = 100, bar_limits = c(255, 300), 
            square = FALSE, contour_lty = 2,
            fileout = 'vis_equimap_contour_raw_obsX.png')
```

<img src="vis_equimap_contour_raw_expA.png" width="600" />
<img src="vis_equimap_contour_raw_obsX.png" width="600" />

 - Drawing boxes on the map: `boxlim`, `boxcol` and `boxlwd` allow to 
specify the position of the corners, colour and thickness of a box to be drawn 
on the map. 

```r
PlotEquiMap(Mean1Dim(map_data$obs, 2)[1, 1, 1, , ], map_data$lon, map_data$lat,
            toptitle = "Obs. X 'tas', 1990-12-01", 
            units = "K", brks = 100, bar_limits = c(255, 300),
            boxlim = list(c(-62, -22, -23, 15), c(-30, 10, 0, 32)), 
            boxcol = c('purple', 'blue'), boxlwd = c(8, 4),
            coast_color = 'black',
            fileout = 'vis_equimap_box_expA.png')
```

<img src="vis_equimap_box_expA.png" width="600" />

 - Ticks on the longitude/latitude axes can be adjusted with `axelab`, `labW`, 
`intylat` and `intxlon`.
 - `numbfig` allows to specify the number of figures in the final layout in 
order to adjust some spacing parameters.

### PlotStereoMap()

`PlotStereoMap()` can be called almost identically to `PlotEquiMap()`, except
that it requires the `latlims` parameter to specify which range of latitudes to
be plotted on the stereographic projection map.  
The only special parameter is the `intlat`, to set the interval in degrees 
between consecutive latitude circles on the plot.

Next a couple of examples:

```r
## Loading data over the entire globe
world_data <- Load('tas', list(expA, expB), list(obsX),
                    sdates = sdates[1],
                    leadtimemin = 2, leadtimemax = 13,
                    latmin = -90, latmax = 90,
                    lonmin = 0, lonmax = 360,
                    output = 'lonlat', grid = 't106grid',
                    method = 'distance-weighted')
PlotStereoMap(Mean1Dim(world_data$mod, 2)[1, 1, 1, , ], 
              world_data$lon, world_data$lat, c(40, 90),
              brks = 100, bar_limits = c(240, 290),
              toptitle = "Exp. A 'tas', s. date: 1990-11-01, f. time: 1 month",
              title_scale = 0.5,
              units = "K", filled.continents = 'black',
              fileout = 'vis_stereomap_raw_expA.png')

PlotStereoMap(Mean1Dim(world_data$obs, 2)[1, 1, 10, , ], 
              world_data$lon, world_data$lat, c(-90, -60), intlat = 10, 
              brks = 100, bar_limits = c(240, 290),
              boxlim = list(c(0, -85, 135, -70)),
              toptitle = "Obs. X 'tas', 1990-12-01",
              title_scale = 0.5,
              units = "K", fileout = 'vis_stereomap_raw_obsX.png')
```

<img src="vis_stereomap_raw_expA.png" width="600" />
<img src="vis_stereomap_raw_obsX.png" width="600" />

### AnimateMap()

`AnimateMap()` generates animations of maps from `PlotEquiMap()` or 
`PlotStereoMap()` and saves them in GIF files at the paths specified in the
parameter `fileout`. It receives as main parameter, similarly as 
`PlotVsLTimes()`, an array with the dimensions:
```r
  c(n. of experiments/observations, n. of observations, 3, n. of forecast times, n. of latitudes, n. of longitudes)
```
the first 3 being optional and the 3rd dimension corresponding to the lower 
confidence interval, the actual value and the upper confidence interval. This 
means it can plot maps of a field of one or multiple experimental or 
observational datasets, averaged across ensemble members and starting dates 
(climatologies) or indices or scores computed across starting dates against 
one or more observations. The confidence intervals, if provided, are used to 
draw black dots on grid cells that reach a 95% significance level, if 
requested via `msk95lev`.

The provided data is assumed to be in a monthly frequency and to start at 
January. Otherwise it can be adjusted with `monini` and `freq`.

Whether to plot with a equidistant rectangular projection or a stereographic 
projection can be chosen with the parameter `equi`. The plot can be limited to 
a sub-region of the provided data via the parameters `lonmin`, `lonmax`, 
`latmin` and `latmax`.

`AnimateMap()` allows for the typical adjustments in the map plotting 
functions: specifying the palette colors and breaks (`col` and `brk`),
displaying or not a legend (`drawleg`, `subsampleg`), selecting a color for
the NA values (`colNA`) and filling or not the continents 
(`filled.continents`).

Further title and axis tick adjustments can be achieved with `toptitle`, 
`sizetit`, `units`, `intlon` and `intlat`.
brk col drawleg subsampleg colNA filled.continents

Next a few examples:

```r
map_clim <- Clim(map_data$mod, map_data$obs, memb = FALSE)

cols <- clim.colors(50)

data_min <- min(map_data$mod, map_data$obs, na.rm = TRUE)
data_max <- max(map_data$mod, map_data$obs, na.rm = TRUE)
brks <- round(seq(data_min, data_max, length.out = length(cols) + 1), 2)

AnimateMap(Subset(map_clim$clim_exp, 'dataset', 1), 
           map_data$lon, map_data$lat, monini = 12, 
           toptitle = "Exp. A climatologies.", 
           units = "K", brks = brks, cols = cols,
           fileout = "vis_anim_clim_expA.gif")
```
<img src="vis_anim_clim_expA.gif" width="600" />

And, as seen in [**Snippet 2**](snippets.md#snippet2), the animations of the 
actual time correlations of Experiment A and B against Observation X over the 
Atlantic, with black dots on values that reach a 95% significance level:

<img src="snip2_anim_corr_expA_obsX.gif" width="600" />

<img src="snip2_anim_corr_expB_obsX.gif" width="600" />

Also the entire globe and stereographic projection maps can be animated:

```r
world_clim <- Clim(world_data$mod, world_data$obs, memb = FALSE)
AnimateMap(Subset(world_clim$clim_exp, 'dataset', 1), 
           world_data$lon, world_data$lat, 
           filled.continents = FALSE, monini = 12,
           toptitle = "Exp. A climatologies.", units = "K",
           brks = brks, cols = cols, 
           fileout = 'vis_anim_clim_expA_world.gif')
AnimateMap(world_clim$clim_obs, 
           world_data$lon, world_data$lat, equi = FALSE,
           latmin = 60, latmax = 90, monini = 12,
           toptitle = "Obs. X climatologies.", 
           units = "K", brks = brks, cols = cols,
           fileout = "vis_anim_clim_obsX_world.gif")
```

<img src="vis_anim_clim_expA_world.gif" width="600" />

<img src="vis_anim_clim_obsX_world.gif" width="600" />

### PlotLayout()

This function allows to easily combine plots from any R plot function in 
layouts. The input data can be provided in multiple data arrays, and a common
colour bar can be set for the multi-panel.

A common use case is to plot the ensemble members at a given time step:

```r
PlotLayout(PlotEquiMap, c('lat', 'lon'),
           Subset(map_data$mod, 
                  list('dataset', 'sdate', 'ftime'), 
                  list(1, 1, 1)), 
           map_data$lon, map_data$lat, units = 'K',
           toptitle = "Exp. A 'tas', s. date: 1990-11-01, f.time: 1 month",
           titles = paste("Member", 1:dim(map_data$mod)[2]),
           brks = 50, bar_limits = c(250, 300), coast_color = 'black',
           fileout = "vis_layout_equimap_expA.png") 
```

<img src="vis_layout_equimap_expA.png" width="600" />

But really complex layouts can be achieved thanks to the great number of
available parameters:

```r
ens_mean <- Subset(world_data$mod, 
                   list('dataset', 'sdate', 'ftime'), 
                   list(1, 1, 1))
layout <- PlotLayout(fun = c('PlotEquiMap', 'plot', 'plot', 'PlotStereoMap'),
                     plot_dims = c('lat', 'lon'), 
                     var = list(ens_mean, array(1:10), 
                                array(10:1), ens_mean), 
                     lon = world_data$lon, lat = world_data$lat, 
                     fill = 'black', sizetit = 0.5, axes_label_scale = 0.6, 
                     coast_color = 'yellow',
                     titles = paste('Fig.', 1:12), toptitle = 'Multipanel', 
                     row_titles = paste('Row', 1:3), col_titles = paste('Col', 1:4), 
                     drawleg = 'E', units = 'K', units_scale = 2, 
                     bar_limits = c(275, 300), brks = 26, 
                     bar_extra_labels = 281:284, 
                     width = 12, height = 10, res = 200, 
                     fileout = 'vis_layout_complex.png')
```

<img src="vis_layout_complex.png" width="800" />

### PlotSection()


