\name{PlotLayout}
\alias{PlotLayout}
\title{
Arrange and Fill Multi-Pannel Layouts With Optional Colour Bar
}
\description{
This function takes an array or list of arrays and loops over each of them to plot all the sub-arrays they contain on an automatically generated multi-pannel layout. A different plot function (not necessarily from s2dverification) can be applied over each of the provided arrays. The input dimensions of each of the functions have to be specified, either with the names or the indices of the corresponding input dimensions. It is possible to draw a common colour bar at any of the sides of the multi-pannel for all the s2dverification plots that use a colour bar. Common plotting arguments for all the arrays in 'var' can be specified via the '...' parameter, and specific plotting arguments for each array can be fully adjusted via 'special_args'. It is possible to draw titles for each of the figures, layout rows, layout columns and for the whole figure. A number of parameters is provided in order to adjust the position, size and colour of the components. Blank cells can be forced to appear and later be filled in manually with customized plots.
This function pops up a blank new device and fills it in, so it cannot be nested in complex layouts.
}
\usage{
PlotLayout(fun, plot_dims, var, ..., special_args = NULL,
           nrow = NULL, ncol = NULL, toptitle = NULL,
           row_titles = NULL, col_titles = NULL, bar_scale = 1,
           title_scale = 1, title_margin_scale = 1,
           title_left_shift_scale = 1,
           subtitle_scale = 1, subtitle_margin_scale = 1,
           brks = NULL, cols = NULL, drawleg = 'S', titles = NULL,
           subsampleg = NULL, bar_limits = NULL,
           triangle_ends = NULL, col_inf = NULL, col_sup = NULL,
           color_fun = clim.colors,
           draw_bar_ticks = TRUE, draw_separators = FALSE,
           triangle_ends_scale = 1, bar_extra_labels = NULL,
           units = NULL, units_scale = 1, bar_label_scale = 1,
           bar_tick_scale = 1, bar_extra_margin = rep(0, 4),
           bar_left_shift_scale = 1, bar_label_digits = 4,
           extra_margin = rep(0, 4),
           fileout = NULL, width = NULL, height = NULL,
           size_units = 'in', res = 100, close_device = TRUE)
}
\arguments{
  \item{fun}{
Plot function (or name of the function) to be called on the arrays provided in 'var'. If multiple arrays are provided in 'var', a vector of as many function names (character strings!) can be provided in 'fun', one for each array in 'var'.
  }
  \item{plot_dims}{
Numeric or character string vector with identifiers of the input plot dimensions of the plot function specified in 'fun'. If character labels are provided, names(dim(var)) or attr('dimensions', var) will be checked to locate the dimensions. As many plots as prod(dim(var)[-plot_dims]) will be generated. If multiple arrays are provided in 'var', 'plot_dims' can be sent a list with a vector of plot dimensions for each. If a single vector is provided, it will be used for all the arrays in 'var'.
  }
  \item{var}{
Multi-dimensional array with at least the dimensions expected by the specified plot function in 'fun'. The dimensions reqired by the function must be specified in 'plot_dims'. The dimensions can be disordered and will be reordered automatically. Dimensions can optionally be labelled in order to refer to them with names in 'plot_dims'. All the available plottable sub-arrays will be automatically plotted and arranged in consecutive cells of an automatically arranged layout. A list of multiple (super-)arrays can be specified. The process will be repeated for each of them, by default applying the same plot function to all of them or, if properly specified in 'fun', a different plot function will be applied to each of them. NAs can be passed to the list: a NA will yield a blank cell in the layout, which can be populated after (see .SwitchToFigure).
  }
  \item{\dots}{
Parameters to be sent to the plotting function 'fun'. If multiple arrays are provided in 'var' and multiple functions are provided in 'fun', the parameters provided through \dots will be sent to all the plot functions, as common parameters. To specify concrete arguments for each of the plot functions see parameter 'special_args'.
  }
  \item{special_args}{
List of sub-lists, each sub-list having extra arguments for each of the plot functions provided in 'fun'.
  }
  \item{nrow}{
Numeric value to force the number of rows in the automatically generated layout. If higher than the required, this will yield blank cells in the layout (which can then be populated). If lower than the required the function will stop. By default it is configured to arrange the layout in a shape as square as possible. Blank cells can be manually populated after with customized plots (see SwitchTofigure).
  }
  \item{ncol}{
Numeric value to force the number of columns in the automatically generated layout. If higher than the required, this will yield blank cells in the layout (which can then be populated). If lower than the required the function will stop. By default it is configured to arrange the layout in a shape as square as possible. Blank cells can be manually populated after with customized plots (see SwitchTofigure).
  }
  \item{toptitle}{
Topt title for the multi-pannel. Blank by default.
  }
  \item{row_titles}{
Character string vector with titles for each of the rows in the layout. Blank by default.
  }
  \item{col_titles}{
Character string vector with titles for each of the columns in the layout. Blank by default.
  }
  \item{bar_scale}{
Scale factor for the common colour bar. Takes 1 by default.
  }
  \item{title_scale}{
Scale factor for the multi-pannel title. Takes 1 by default.
  }
  \item{title_margin_scale}{
Scale factor for the margins surrounding the top title. Takes 1 by default.
  }
  \item{title_left_shift_scale}{
When plotting row titles, a shift is added to the horizontal positioning of the top title in order to center it to the region of the figures (without taking row titles into account). This shift can be reduced. A value of 0 will remove the shift completely, centering the title to the total width of the device. This parameter will be disregarded if no 'row_titles' are provided.
  }
  \item{subtitle_scale}{
Scale factor for the row titles and column titles (specified in 'row_titles' and 'col_titles'). Takes 1 by default.
  }
  \item{subtitle_margin_scale}{
Scale factor for the margins surrounding the subtitles. Takes 1 by default.
  }
  \item{units}{
Title at the top of the colour bar, most commonly the units of the variable provided in parameter 'var'.
  }
  \item{brks,cols,bar_limits,triangle_ends}{
Usually only providing 'brks' is enough to generate the desired colour bar. These parameters allow to define n breaks that define n - 1 intervals to classify each of the values in 'var'. The corresponding grid cell of a given value in 'var' will be coloured in function of the interval it belongs to. These parameters are sent to \code{ColorBar()} to generate the breaks and colours. Additional colours for values beyond the limits of the colour bar are also generated and applied to the plot if 'bar_limits' or 'brks' and 'triangle_ends' are properly provided to do so. See ?ColorBar for a full explanation.\cr
  }
  \item{col_inf,col_sup}{
Colour identifiers to colour the values in 'var' that go beyond the extremes of the colour bar and to colour NA values, respectively. 'colNA' takes 'white' by default. 'col_inf' and 'col_sup' will take the value of 'colNA' if not specified. See ?ColorBar for a full explanation on 'col_inf' and 'col_sup'.
  }
  \item{color_fun,subsampleg,bar_extra_labels,draw_bar_ticks,draw_separators,triangle_ends_scale,bar_label_digits,bar_label_scale,units_scale,bar_tick_scale,bar_extra_margin}{
Set of parameters to control the visual aspect of the drawn colour bar. See ?ColorBar for a full explanation.
  }
  \item{drawleg}{
Where to draw the common colour bar. Can take values TRUE, FALSE or:\cr
  'up', 'u', 'U', 'top', 't', 'T', 'north', 'n', 'N'\cr
  'down', 'd', 'D', 'bottom', 'b', 'B', 'south', 's', 'S' (default)\cr
  'right', 'r', 'R', 'east', 'e', 'E'\cr
  'left', 'l', 'L', 'west', 'w', 'W'
  }
  \item{titles}{
Character string vector with titles for each of the figures in the multi-pannel, from top-left to bottom-right. Blank by default.
  }
  \item{bar_left_shift_scale}{
When plotting row titles, a shift is added to the horizontal positioning of the colour bar in order to center it to the region of the figures (without taking row titles into account). This shift can be reduced. A value of 0 will remove the shift completely, centering the colour bar to the total width of the device. This parameter will be disregarded if no 'row_titles' are provided.
  }
  \item{extra_margin}{
Extra margins to be added around the layout, in the format c(y1, x1, y2, x2). The units are margin lines. Takes rep(0, 4) by default.
  }
  \item{fileout}{
File where to save the plot. If not specified (default) a graphics device will pop up. Extensions allowed: eps/ps, jpeg, png, pdf, bmp and tiff. \cr
  }
  \item{width}{
Width in inches of the multi-pannel. 7 by default, or 11 if 'fielout' has been specified.
  }
  \item{height}{
Height in inches of the multi-pannel. 7 by default, or 11 if 'fileout' has been specified.
  }
  \item{size_units}{
Units of the size of the device (file or window) to plot in. Inches ('in') by default. See ?Devices and the creator function of the corresponding device.
  }
  \item{res}{ 
Resolution of the device (file or window) to plot in. See ?Devices and the creator function of the corresponding device.
  }
  \item{close_device}{
Whether to close the graphics device after plotting the layout and a 'fileout' has been specified. This is useful to avoid closing the device when saving the layout into a file and willing to add extra elements or figures. Takes TRUE by default. Disregarded if no 'fileout' has been specified.
  }
}
\value{
  \item{brks}{
Breaks used for colouring the map (and legend if drawleg = TRUE).
  }
  \item{cols}{
Colours used for colouring the map (and legend if drawleg = TRUE). Always of length length(brks) - 1.
  }
  \item{col_inf}{
Colour used to draw the lower triangle end in the colour bar (NULL if not drawn at all).
  }
  \item{col_sup}{
Colour used to draw the upper triangle end in the colour bar (NULL if not drawn at all).
  }
  \item{layout_matrix}{
Underlying matrix of the layout. Useful to later set any of the layout cells as current figure to add plot elements. See .SwitchToFigure.
  }
}
\examples{
# See examples on Load() to understand the first lines in this example
  \dontrun{
data_path <- system.file('sample_data', package = 's2dverification')
expA <- list(name = 'experiment', path = file.path(data_path,
             'model/$EXP_NAME$/$STORE_FREQ$_mean/$VAR_NAME$_3hourly',
             '$VAR_NAME$_$START_DATE$.nc'))
obsX <- list(name = 'observation', path = file.path(data_path,
             '$OBS_NAME$/$STORE_FREQ$_mean/$VAR_NAME$',
             '$VAR_NAME$_$YEAR$$MONTH$.nc'))

# Now we are ready to use Load().
startDates <- c('19851101', '19901101', '19951101', '20001101', '20051101')
sampleData <- Load('tos', list(expA), list(obsX), startDates,
                   leadtimemin = 1, leadtimemax = 4, output = 'lonlat',
                   latmin = 27, latmax = 48, lonmin = -12, lonmax = 40)
  }
  \dontshow{
startDates <- c('19851101', '19901101', '19951101', '20001101', '20051101')
sampleData <- s2dverification:::.LoadSampleData('tos', c('experiment'),
                                                c('observation'), startDates,
                                                leadtimemin = 1,
                                                leadtimemax = 4,
                                                output = 'lonlat',
                                                latmin = 27, latmax = 48,
                                                lonmin = -12, lonmax = 40)
  }
PlotLayout(PlotEquiMap, c('lat', 'lon'), sampleData$mod[1, , 1, 1, , ], 
           sampleData$lon, sampleData$lat,
           toptitle = 'Predicted tos for Nov 1960 from 1st Nov',
           titles = paste('Member', 1:15))
}
\author{
  History:
  0.1  -  2016-08  (N. Manubens, \email{nicolau.manubens at bsc.es})  -  Original code
}
\keyword{dynamic}

