diff --git a/DESCRIPTION b/DESCRIPTION index 8c9a2ba0..2ac06412 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -30,14 +30,12 @@ Imports: Depends: R (>= 3.5) Encoding: UTF-8 -RoxygenNote: 7.1.1 +RoxygenNote: 7.1.2 Roxygen: list(markdown = TRUE) -LazyData: true Suggests: knitr, rmarkdown, testthat (>= 2.1.0), - pander, gridExtra VignetteBuilder: knitr Collate: diff --git a/R/aaa-utilities.R b/R/aaa-utilities.R index b186115c..0978e05d 100644 --- a/R/aaa-utilities.R +++ b/R/aaa-utilities.R @@ -87,7 +87,7 @@ parseUpdateAestheticProperty <- function(aestheticProperty, plotConfigurationPro ',aesthetic = "', aestheticProperty, '"))' )), # remove the legend of aesthetic if default unmapped aesthetic - parse(text = paste0("if(isIncluded(", aestheticProperty, 'Variable, "legendLabels")){plotObject <- plotObject + ggplot2::guides(', aestheticProperty, " = FALSE)}")) + parse(text = paste0("if(isIncluded(", aestheticProperty, 'Variable, "legendLabels")){plotObject <- plotObject + ggplot2::guides(', aestheticProperty, " = 'none')}")) ) } diff --git a/R/aggregation-input.R b/R/aggregation-input.R index c31dddef..f303ac5a 100644 --- a/R/aggregation-input.R +++ b/R/aggregation-input.R @@ -14,17 +14,17 @@ AggregationInput <- R6::R6Class( #' @field aggregationDimension dimension of aggregation output aggregationDimension = NULL, - #' @description Create a new \code{AggregationInput} object + #' @description Create a new `AggregationInput` object #' @param aggregationFunction list of functions to use for aggregation #' @param aggregationFunctionName vector of function names #' that will be used as variable name of the aggregation #' @param aggregationUnit unit of aggregation output #' @param aggregationDimension dimension of aggregation output - #' @return A new \code{AggregationInput} object + #' @return A new `AggregationInput` object initialize = function(aggregationFunction = NULL, - aggregationFunctionName = NULL, - aggregationUnit = NULL, - aggregationDimension = NULL) { + aggregationFunctionName = NULL, + aggregationUnit = NULL, + aggregationDimension = NULL) { self$aggregationFunction <- aggregationFunction self$aggregationFunctionName <- aggregationFunctionName self$aggregationUnit <- aggregationUnit @@ -36,7 +36,7 @@ AggregationInput <- R6::R6Class( predefinedPercentiles <- c(0, 1, 2.5, 5, 10, 15, 20, 25, 50, 75, 80, 85, 90, 95, 97.5, 99, 100) #' @title tlfStatFunctions #' @description -#' Bank of predifined functions ready to use by Aggregation methods. Bank defined as Enum. +#' Bank of predefined functions ready to use by Aggregation methods. Bank defined as Enum. #' To access the function from its name, use match.fun: e.g. testFun <- match.fun("mean-1.96sd") #' @include enum.R #' @export diff --git a/R/aggregation-summary.R b/R/aggregation-summary.R index 7738db23..2628e5bc 100644 --- a/R/aggregation-summary.R +++ b/R/aggregation-summary.R @@ -1,9 +1,9 @@ #' @title AggregationSummary #' @description R6 class to split a data.frame data into subsets defined by unique combinations of elements -#' in the columns \code{xColumnNames} and \code{groupingColumnNames}. -#' Applies functions defined in \code{aggregationFunctionsVector} to column \code{yColumnNames.} -#' Returns a list of data.frame, one data.frame for each function listed in \code{aggregationFunctionsVector}. -#' Each data.frame in list element is named after the function's corresponding string in \code{aggregationFunctionNames}. +#' in the columns `xColumnNames` and `groupingColumnNames`. +#' Applies functions defined in `aggregationFunctionsVector` to column `yColumnNames.` +#' Returns a list of data.frame, one data.frame for each function listed in `aggregationFunctionsVector`. +#' Each data.frame in list element is named after the function's corresponding string in `aggregationFunctionNames`. #' The summary statistic column name in each data.frame is the same as the name of the data.frame in the returned list. #' @export AggregationSummary <- R6::R6Class( @@ -11,7 +11,7 @@ AggregationSummary <- R6::R6Class( public = list( #' @field data data.frame data = NULL, - #' @field metaData list of information on \code{data} + #' @field metaData list of information on `data` metaData = NULL, #' @field xColumnNames character names of grouping variables xColumnNames = NULL, @@ -19,7 +19,7 @@ AggregationSummary <- R6::R6Class( groupingColumnNames = NULL, #' @field yColumnNames character names of dependent variables (that are grouped) yColumnNames = NULL, - #' @field aggregationInputsVector list of R6 class \code{AggregationInput} objects + #' @field aggregationInputsVector list of R6 class `AggregationInput` objects aggregationInputsVector = NULL, #' @field aggregationFunctionsVector list of functions to use for aggregation aggregationFunctionsVector = NULL, @@ -31,31 +31,31 @@ AggregationSummary <- R6::R6Class( aggregationDimensionsVector = NULL, #' @field dfHelper data.frame of aggregated values dfHelper = NULL, - #' @field metaDataHelper list of information on \code{dfHelper} + #' @field metaDataHelper list of information on `dfHelper` metaDataHelper = NULL, - #' @description Create a new \code{AggregationSummary} object + #' @description Create a new `AggregationSummary` object #' @param data data.frame - #' @param metaData list of information on \code{data} + #' @param metaData list of information on `data` #' @param xColumnNames character names of grouping variables #' @param groupingColumnNames character names of grouping variables #' @param yColumnNames character names of dependent variables (that are grouped) - #' @param aggregationInputsVector list of R6 class \code{AggregationInput} objects + #' @param aggregationInputsVector list of R6 class `AggregationInput` objects #' @param aggregationFunctionsVector list of functions to use for aggregation #' @param aggregationFunctionNames vector of function names that will be used as variable name of the aggregation #' @param aggregationUnitsVector character vector of units of aggregation output #' @param aggregationDimensionsVector character vector of dimensions of aggregation output - #' @return A new \code{AggregationSummary} object + #' @return A new `AggregationSummary` object initialize = function(data, - metaData = NULL, - xColumnNames = NULL, - groupingColumnNames = NULL, - yColumnNames = NULL, - aggregationInputsVector = NULL, - aggregationFunctionsVector = NULL, - aggregationFunctionNames = NULL, - aggregationUnitsVector = NULL, - aggregationDimensionsVector = NULL) { + metaData = NULL, + xColumnNames = NULL, + groupingColumnNames = NULL, + yColumnNames = NULL, + aggregationInputsVector = NULL, + aggregationFunctionsVector = NULL, + aggregationFunctionNames = NULL, + aggregationUnitsVector = NULL, + aggregationDimensionsVector = NULL) { self$data <- data self$metaData <- metaData self$xColumnNames <- xColumnNames @@ -71,8 +71,7 @@ AggregationSummary <- R6::R6Class( self$aggregationUnitsVector <- append(self$aggregationUnitsVector, aggregationInputValue$aggregationUnit) self$aggregationDimensionsVector <- append(self$aggregationDimensionsVector, aggregationInputValue$aggregationDimension) } - } - else { + } else { self$aggregationFunctionsVector <- c(aggregationFunctionsVector) self$aggregationFunctionNames <- aggregationFunctionNames self$aggregationUnitsVector <- aggregationUnitsVector @@ -81,7 +80,7 @@ AggregationSummary <- R6::R6Class( self$generateAggregatedValues() }, - #' @description Apply aggregation functions on \code{x} + #' @description Apply aggregation functions on `x` #' @param x numeric vector #' @return A list or vector of aggregated values applyAggregationFunctions = function(x) { @@ -99,15 +98,15 @@ AggregationSummary <- R6::R6Class( xGroupingCols <- self$data[xGroupingColNames] # Extract grouping columns from dataframe and group them into a list called xGroupingCols - yValuesCol <- self$data[ self$yColumnNames ] # Extract column of values from dataframe + yValuesCol <- self$data[self$yColumnNames] # Extract column of values from dataframe aggSummaries <- aggregate(yValuesCol, xGroupingCols, function(x) { res <- self$applyAggregationFunctions(x) return(res) }) - summaryMatrix <- matrix(aggSummaries[[ self$yColumnNames ]], ncol = length(self$aggregationFunctionsVector)) - self$dfHelper <- aggSummaries[ xGroupingColNames ] + summaryMatrix <- matrix(aggSummaries[[self$yColumnNames]], ncol = length(self$aggregationFunctionsVector)) + self$dfHelper <- aggSummaries[xGroupingColNames] self$metaDataHelper <- self$metaData[xGroupingColNames] for (n in seq(1, length(self$aggregationFunctionNames))) { @@ -115,7 +114,7 @@ AggregationSummary <- R6::R6Class( colnames(dF)[1] <- self$aggregationFunctionNames[n] self$dfHelper <- cbind(self$dfHelper, dF) - self$metaDataHelper [[self$aggregationFunctionNames[n]]] <- list(unit = self$aggregationUnitsVector[n], dimension = self$aggregationDimensionsVector[n]) + self$metaDataHelper[[self$aggregationFunctionNames[n]]] <- list(unit = self$aggregationUnitsVector[n], dimension = self$aggregationDimensionsVector[n]) } } ) diff --git a/R/atom-plots.R b/R/atom-plots.R index e8feeed4..683c7457 100644 --- a/R/atom-plots.R +++ b/R/atom-plots.R @@ -2,11 +2,11 @@ #' @title initializePlot #' @param plotConfiguration -#' \code{PlotConfiguration} objecct defining labels, grid, background and watermark -#' This parameter is optional: the \code{tlf} library provides a default configuration according to the current theme +#' `PlotConfiguration` objecct defining labels, grid, background and watermark +#' This parameter is optional: the `tlf` library provides a default configuration according to the current theme #' @description -#' Initialize a \code{ggplot} object and set the labels, grid, background and watermark -#' @return A \code{ggplot} graphical object +#' Initialize a `ggplot` object and set the labels, grid, background and watermark +#' @return A `ggplot` graphical object #' @export #' @examples #' # Initialize an empty plot @@ -34,13 +34,13 @@ initializePlot <- function(plotConfiguration = NULL) { #' @title addScatter #' @param data data.frame containing the scatter points to be plotted -#' @param metaData list of information on \code{data} such as \code{dimension} and \code{unit} of their variables +#' @param metaData list of information on `data` such as `dimension` and `unit` of their variables #' @param x Mapping for x values. -#' If \code{data} is NULL or not input, \code{x} numeric values will be used as is for the plot. +#' If `data` is NULL or not input, `x` numeric values will be used as is for the plot. #' @param y Mapping for y values. -#' If \code{data} is NULL or not input, \code{y} numeric values will be used as is for the plot. -#' @param dataMapping \code{XYGDataMapping} class or subclass object -#' mapping x, y and aesthetic variables to the variable names of \code{data}. +#' If `data` is NULL or not input, `y` numeric values will be used as is for the plot. +#' @param dataMapping `XYGDataMapping` class or subclass object +#' mapping x, y and aesthetic variables to the variable names of `data`. #' @param caption vector of character strings defining the legend captions. #' This parameter is optional: default value `NULL` creates caption labels "data 1", "data 2" ... #' @param color vector of character strings defining the color of the scatter points. @@ -51,15 +51,15 @@ initializePlot <- function(plotConfiguration = NULL) { #' This parameter is optional: default value `NULL` will choose sizes according to the current theme. #' @param linetype vector of character strings defining the linetype linking the scatter points. #' This parameter is optional: default value `NULL` won't provide lines. -#' @param plotConfiguration \code{PlotConfiguration} object defining the labels, axes, background and legend properties of the plot. -#' @param plotObject \code{ggplot} graphical object to which the line layer is added -#' This parameter is optional: the \code{tlf} library will initialize an empty plot if the parameter is NULL or not provided +#' @param plotConfiguration `PlotConfiguration` object defining the labels, axes, background and legend properties of the plot. +#' @param plotObject `ggplot` graphical object to which the line layer is added +#' This parameter is optional: the `tlf` library will initialize an empty plot if the parameter is NULL or not provided #' @description -#' Add a scatter plot layer to a \code{ggplot} graphical object. -#' Use optional argument \code{caption} to set legend caption. -#' Since \code{ggplot} manage aesthetic properties across all layers, -#' aesthetic properties defined in \code{plotConfiguration} will apply across all layers. -#' @return A \code{ggplot} graphical object +#' Add a scatter plot layer to a `ggplot` graphical object. +#' Use optional argument `caption` to set legend caption. +#' Since `ggplot` manage aesthetic properties across all layers, +#' aesthetic properties defined in `plotConfiguration` will apply across all layers. +#' @return A `ggplot` graphical object #' @export #' @examples #' # Add scatter using x and y @@ -169,15 +169,15 @@ addScatter <- function(data = NULL, #' @title addLine #' @param data data.frame containing the line endpoints to be plotted -#' @param metaData list of information on \code{data} such as \code{dimension} and \code{unit} of their variables +#' @param metaData list of information on `data` such as `dimension` and `unit` of their variables #' @param x Mapping for x values. -#' If \code{data} is NULL or not input, \code{x} numeric values will be used as is for the plot. -#' In case there is no \code{y} mapping, \code{x} are the x-values of vertical lines. +#' If `data` is NULL or not input, `x` numeric values will be used as is for the plot. +#' In case there is no `y` mapping, `x` are the x-values of vertical lines. #' @param y Mapping for y values. -#' If \code{data} is NULL or not input, \code{y} numeric values will be used as is for the plot. -#' In case there is no \code{x} mapping, \code{y} are the y-values of horizontal lines. -#' @param dataMapping \code{XYGDataMapping} class or subclass -#' mapping x, y and aesthetic variables to the variable names of \code{data}. +#' If `data` is NULL or not input, `y` numeric values will be used as is for the plot. +#' In case there is no `x` mapping, `y` are the y-values of horizontal lines. +#' @param dataMapping `XYGDataMapping` class or subclass +#' mapping x, y and aesthetic variables to the variable names of `data`. #' @param caption vector of character strings defining the legend captions. #' This parameter is optional: default value is NULL. #' @param color vector of character strings defining the color of the scatter points. @@ -188,15 +188,15 @@ addScatter <- function(data = NULL, #' This parameter is optional: default value `NULL` will choose sizes according to the current theme. #' @param linetype vector of character strings defining the linetype linking the scatter points. #' This parameter is optional: default value `NULL` won't provide lines. -#' @param plotConfiguration \code{PlotConfiguration} object defining the label and background properties of the plot. -#' @param plotObject \code{ggplot} graphical object to which the line layer is added -#' This parameter is optional: the \code{tlf} library will initialize an empty plot if the parameter is NULL or not provided +#' @param plotConfiguration `PlotConfiguration` object defining the label and background properties of the plot. +#' @param plotObject `ggplot` graphical object to which the line layer is added +#' This parameter is optional: the `tlf` library will initialize an empty plot if the parameter is NULL or not provided #' @description -#' Add a line layer to a \code{ggplot} graphical object. -#' Use optional argument \code{caption} to set legend caption. -#' Since \code{ggplot} manage aesthetic properties across all layers, -#' aesthetic properties defined in \code{plotConfiguration} will apply across all layers. -#' @return A \code{ggplot} graphical object +#' Add a line layer to a `ggplot` graphical object. +#' Use optional argument `caption` to set legend caption. +#' Since `ggplot` manage aesthetic properties across all layers, +#' aesthetic properties defined in `plotConfiguration` will apply across all layers. +#' @return A `ggplot` graphical object #' @export #' @examples #' # Add vertical line at x = 2 @@ -355,19 +355,19 @@ addLine <- function(data = NULL, #' @title addRibbon #' @param data data.frame containing the ribbon endpoints to be plotted. -#' @param metaData list of information on \code{data} such as \code{dimension} and \code{unit} of their variables +#' @param metaData list of information on `data` such as `dimension` and `unit` of their variables #' @param x Mapping for x values. -#' If \code{data} is NULL or not input, \code{x} numeric values will be used as is for the plot. +#' If `data` is NULL or not input, `x` numeric values will be used as is for the plot. #' @param ymin Mapping for ymin values. -#' If \code{data} is NULL or not input, \code{ymin} numeric values will be used as is for the plot. -#' In case there is no \code{x} mapping, \code{ymin} are the y-values of horizontal lines. -#' In case there is no \code{ymax} mapping, a value of 0 is assumed for \code{ymax}. +#' If `data` is NULL or not input, `ymin` numeric values will be used as is for the plot. +#' In case there is no `x` mapping, `ymin` are the y-values of horizontal lines. +#' In case there is no `ymax` mapping, a value of 0 is assumed for `ymax`. #' @param ymax Mapping for ymax values. -#' If \code{data} is NULL or not input, \code{ymax} numeric values will be used as is for the plot. -#' In case there is no \code{x} mapping, \code{ymax} are the y-values of horizontal lines. -#' In case there is no \code{ymin} mapping, a value of 0 is assumed for \code{ymin}. -#' @param dataMapping \code{XYGDataMapping} class or subclass -#' mapping x, y and aesthetic variables to the variable names of \code{data}. +#' If `data` is NULL or not input, `ymax` numeric values will be used as is for the plot. +#' In case there is no `x` mapping, `ymax` are the y-values of horizontal lines. +#' In case there is no `ymin` mapping, a value of 0 is assumed for `ymin`. +#' @param dataMapping `XYGDataMapping` class or subclass +#' mapping x, y and aesthetic variables to the variable names of `data`. #' @param caption vector of character strings defining the legend captions. #' This parameter is optional: default value is NULL. #' @param fill vector of character strings defining the color of the scatter points. @@ -380,16 +380,16 @@ addLine <- function(data = NULL, #' This parameter is optional: default value `NULL` won't provide lines. #' @param alpha transparency of the ribbon. #' Numeric value between 0 and 1. Value of 0, the plot is transparent. Value of 1, the plot is opaque. -#' Default value for \code{alpha} is 0.8. -#' @param plotConfiguration \code{PlotConfiguration} object defining the label and background properties of the plot. -#' @param plotObject \code{ggplot} graphical object to which the line layer is added -#' This parameter is optional: the \code{tlf} library will initialize an empty plot if the parameter is NULL or not provided +#' Default value for `alpha` is 0.8. +#' @param plotConfiguration `PlotConfiguration` object defining the label and background properties of the plot. +#' @param plotObject `ggplot` graphical object to which the line layer is added +#' This parameter is optional: the `tlf` library will initialize an empty plot if the parameter is NULL or not provided #' @description -#' Add a ribbon layer to a \code{ggplot} graphical object. -#' Use optional argument \code{caption} to set legend caption. -#' Since \code{ggplot} manage aesthetic properties across all layers, -#' aesthetic properties defined in \code{plotConfiguration} will apply across all layers. -#' @return A \code{ggplot} graphical object +#' Add a ribbon layer to a `ggplot` graphical object. +#' Use optional argument `caption` to set legend caption. +#' Since `ggplot` manage aesthetic properties across all layers, +#' aesthetic properties defined in `plotConfiguration` will apply across all layers. +#' @return A `ggplot` graphical object #' @export #' @examples #' # Add a horizontal ribbon to a previous plot @@ -504,13 +504,13 @@ addRibbon <- function(data = NULL, #' @title addErrorbar #' @param data data.frame containing the errorbar endpoints to be plotted -#' @param metaData list of information on \code{data} such as \code{dimension} and \code{unit} of their variables +#' @param metaData list of information on `data` such as `dimension` and `unit` of their variables #' @param x Mapping for x values. -#' If \code{data} is NULL or not input, \code{x} numeric values will be used as is for the plot. +#' If `data` is NULL or not input, `x` numeric values will be used as is for the plot. #' @param ymin Mapping for ymin values. -#' If \code{data} is NULL or not input, \code{ymin} numeric values will be used as is for the plot. +#' If `data` is NULL or not input, `ymin` numeric values will be used as is for the plot. #' @param ymax Mapping for ymin values. -#' If \code{data} is NULL or not input, \code{ymax} numeric values will be used as is for the plot. +#' If `data` is NULL or not input, `ymax` numeric values will be used as is for the plot. #' @param caption vector of character strings defining the legend captions. #' This parameter is optional: default value is NULL. #' @param color vector of character strings defining the color of the scatter points. @@ -520,18 +520,18 @@ addRibbon <- function(data = NULL, #' @param linetype vector of character strings defining the linetype linking the scatter points. #' This parameter is optional: default value `NULL` won't provide lines. #' @param includeCap logical setting if error bars include caps at their ends. -#' @param dataMapping \code{RangeDataMapping} class or subclass -#' mapping x, ymin, ymax and aesthetic variables to the variable names of \code{data}. -#' @param plotConfiguration \code{PlotConfiguration} object defining the label and background properties of the plot. -#' @param plotObject \code{ggplot} graphical object to which the line layer is added -#' This parameter is optional: the \code{tlf} library will initialize an empty plot if the parameter is NULL or not provided +#' @param dataMapping `RangeDataMapping` class or subclass +#' mapping x, ymin, ymax and aesthetic variables to the variable names of `data`. +#' @param plotConfiguration `PlotConfiguration` object defining the label and background properties of the plot. +#' @param plotObject `ggplot` graphical object to which the line layer is added +#' This parameter is optional: the `tlf` library will initialize an empty plot if the parameter is NULL or not provided #' @description -#' Add a errorbar plot layer to a \code{ggplot} graphical object. -#' Use optional argument \code{caption} to set legend caption. -#' Since \code{ggplot} manage aesthetic properties across all layers, -#' aesthetic properties defined in \code{plotConfiguration} will apply across all layers. +#' Add a errorbar plot layer to a `ggplot` graphical object. +#' Use optional argument `caption` to set legend caption. +#' Since `ggplot` manage aesthetic properties across all layers, +#' aesthetic properties defined in `plotConfiguration` will apply across all layers. #' If caption is the same as a previous scatter plot layer, the legend will merge their caption and aesthetic properties -#' @return A \code{ggplot} graphical object +#' @return A `ggplot` graphical object #' @export addErrorbar <- function(data = NULL, metaData = NULL, diff --git a/R/boxwhisker-datamapping.R b/R/boxwhisker-datamapping.R index 015d5fbe..183b5739 100644 --- a/R/boxwhisker-datamapping.R +++ b/R/boxwhisker-datamapping.R @@ -1,18 +1,18 @@ #' @title BoxWhiskerDataMapping -#' @description R6 class for mapping \code{y}, \code{GroupMapping}, \code{boxWhiskerLimits} and \code{outlierLimits} to \code{data} +#' @description R6 class for mapping `y`, `GroupMapping`, `boxWhiskerLimits` and `outlierLimits` to `data` #' @export BoxWhiskerDataMapping <- R6::R6Class( "BoxWhiskerDataMapping", inherit = XYGDataMapping, public = list( #' @field outlierLimits List of `minOutlierLimit` and `maxOutlierLimit` functions - #' outside which \code{data} is flagged as outlier + #' outside which `data` is flagged as outlier outlierLimits = NULL, #' @field boxWhiskerLimits List of `ymin`, `lower`, `middle`, `upper` and `ymax` functions - #' calculated on \code{data} to obtain box whiskers + #' calculated on `data` to obtain box whiskers boxWhiskerLimits = NULL, - #' @description Create a new \code{BoxWhiskerDataMapping} object + #' @description Create a new `BoxWhiskerDataMapping` object #' @param x Name of x variable to map #' Default value is NULL in case of a unique box in the boxplot. #' @param y Name of y variable to map @@ -30,18 +30,18 @@ BoxWhiskerDataMapping <- R6::R6Class( #' Default value is `Percentile25-1.5IQR%`. #' @param maxOutlierLimit Name of function used for calculating upper outlier limit #' Default value is `Percentile75+1.5IQR%`. - #' @param ... parameters inherited from \code{XYGDataMapping} - #' @return A new \code{BoxWhiskerDataMapping} object + #' @param ... parameters inherited from `XYGDataMapping` + #' @return A new `BoxWhiskerDataMapping` object initialize = function(x = NULL, - y, - ymin = tlfStatFunctions$`Percentile5%`, - lower = tlfStatFunctions$`Percentile25%`, - middle = tlfStatFunctions$`Percentile50%`, - upper = tlfStatFunctions$`Percentile75%`, - ymax = tlfStatFunctions$`Percentile95%`, - minOutlierLimit = tlfStatFunctions$`Percentile25%-1.5IQR`, - maxOutlierLimit = tlfStatFunctions$`Percentile75%+1.5IQR`, - ...) { + y, + ymin = tlfStatFunctions$`Percentile5%`, + lower = tlfStatFunctions$`Percentile25%`, + middle = tlfStatFunctions$`Percentile50%`, + upper = tlfStatFunctions$`Percentile75%`, + ymax = tlfStatFunctions$`Percentile95%`, + minOutlierLimit = tlfStatFunctions$`Percentile25%-1.5IQR`, + maxOutlierLimit = tlfStatFunctions$`Percentile75%+1.5IQR`, + ...) { super$initialize(x = x, y = y, ...) self$groupMapping$color <- self$groupMapping$color %||% self$groupMapping$fill diff --git a/R/boxwhisker-plotconfiguration.R b/R/boxwhisker-plotconfiguration.R index 7f8e4e37..73cda827 100644 --- a/R/boxwhisker-plotconfiguration.R +++ b/R/boxwhisker-plotconfiguration.R @@ -1,20 +1,20 @@ #' @title BoxWhiskerPlotConfiguration -#' @description R6 class defining the configuration of a \code{ggplot} object +#' @description R6 class defining the configuration of a `ggplot` object #' @export BoxWhiskerPlotConfiguration <- R6::R6Class( "BoxWhiskerPlotConfiguration", inherit = PlotConfiguration, public = list( - #' @description Create a new \code{PKRatioPlotConfiguration} object + #' @description Create a new `PKRatioPlotConfiguration` object #' @param ribbons `ThemeAestheticSelections` object defining properties for boxes of boxplot #' @param points `ThemeAestheticSelections` object defining properties for outlier scatter points #' @param outliers logical defining if outliers should be included in boxplot - #' @param ... parameters inherited from \code{PlotConfiguration} - #' @return A new \code{PKRatioPlotConfiguration} object + #' @param ... parameters inherited from `PlotConfiguration` + #' @return A new `PKRatioPlotConfiguration` object initialize = function(outliers = TRUE, - ribbons = NULL, - points = NULL, - ...) { + ribbons = NULL, + points = NULL, + ...) { super$initialize(...) validateIsOfType(ribbons, "ThemeAestheticSelections", nullAllowed = TRUE) diff --git a/R/datamapping-grouping.R b/R/datamapping-grouping.R index 021e3655..83b1538e 100644 --- a/R/datamapping-grouping.R +++ b/R/datamapping-grouping.R @@ -1,18 +1,18 @@ #' @title Grouping -#' @description R6 class for mapping a \code{group} of variable(s) and their \code{label} to \code{data} +#' @description R6 class for mapping a `group` of variable(s) and their `label` to `data` #' @export Grouping <- R6::R6Class( "Grouping", public = list( #' @field group data.frame or character defining the groups or group variables to group by group = NULL, - #' @field label character printed name of the \code{grouping} + #' @field label character printed name of the `grouping` label = NULL, - #' @description Create a new \code{Grouping} object + #' @description Create a new `Grouping` object #' @param group data.frame or character vector of groups - #' @param label character name of the \code{group} - #' @return A new \code{Grouping} object + #' @param label character name of the `group` + #' @return A new `Grouping` object initialize = function(group, label = NULL) { validateIsOfType(group, c("data.frame", "character"), nullAllowed = TRUE) @@ -29,10 +29,10 @@ Grouping <- R6::R6Class( self$label <- label %||% self$label }, - #' @description Get the caption associated to each \code{group} + #' @description Get the caption associated to each `group` #' @param data data.frame to map - #' @param metaData list of information on the \code{data} - #' @return A vector of characters containing the captions associated to each \code{group} of \code{data} + #' @param metaData list of information on the `data` + #' @return A vector of characters containing the captions associated to each `group` of `data` getCaptions = function(data, metaData = NULL) { validateIsOfType(self$group, c("data.frame", "character"), nullAllowed = TRUE) diff --git a/R/datamapping-groupmapping.R b/R/datamapping-groupmapping.R index 4f8b95d9..3072783d 100644 --- a/R/datamapping-groupmapping.R +++ b/R/datamapping-groupmapping.R @@ -1,32 +1,32 @@ #' @title GroupMapping -#' @description R6 class for mapping \code{Grouping} variables to \code{data} +#' @description R6 class for mapping `Grouping` variables to `data` #' @export GroupMapping <- R6::R6Class( "GroupMapping", public = list( - #' @field color R6 class \code{Grouping} object + #' @field color R6 class `Grouping` object color = NULL, - #' @field fill R6 class \code{Grouping} object + #' @field fill R6 class `Grouping` object fill = NULL, - #' @field linetype R6 class \code{Grouping} object + #' @field linetype R6 class `Grouping` object linetype = NULL, - #' @field shape R6 class \code{Grouping} object + #' @field shape R6 class `Grouping` object shape = NULL, - #' @field size R6 class \code{Grouping} object + #' @field size R6 class `Grouping` object size = NULL, - #' @description Create a new \code{GroupMapping} object - #' @param color R6 class \code{Grouping} object or its input - #' @param fill R6 class \code{Grouping} object or its input - #' @param linetype R6 class \code{Grouping} object or its input - #' @param shape R6 class \code{Grouping} object or its input - #' @param size R6 class \code{Grouping} object or its input - #' @return A new \code{GroupMapping} object + #' @description Create a new `GroupMapping` object + #' @param color R6 class `Grouping` object or its input + #' @param fill R6 class `Grouping` object or its input + #' @param linetype R6 class `Grouping` object or its input + #' @param shape R6 class `Grouping` object or its input + #' @param size R6 class `Grouping` object or its input + #' @return A new `GroupMapping` object initialize = function(color = NULL, - fill = NULL, - linetype = NULL, - shape = NULL, - size = NULL) { + fill = NULL, + linetype = NULL, + shape = NULL, + size = NULL) { # If mappings are not of type Grouping, they are assumed as Grouping inputs groupingInputs <- c("color", "fill", "linetype", "shape", "size") eval(parse(text = paste0( diff --git a/R/datamapping-range.R b/R/datamapping-range.R index e70f0b82..dfdfa4fa 100644 --- a/R/datamapping-range.R +++ b/R/datamapping-range.R @@ -1,5 +1,5 @@ #' @title RangeDataMapping -#' @description R6 class for mapping \code{x}, \code{ymin} and \code{ymax} variable to \code{data} +#' @description R6 class for mapping `x`, `ymin` and `ymax` variable to `data` #' @export RangeDataMapping <- R6::R6Class( "RangeDataMapping", @@ -10,28 +10,28 @@ RangeDataMapping <- R6::R6Class( #' @field ymax Name of ymax variable to map ymax = NULL, - #' @description Create a new \code{RangeDataMapping} object + #' @description Create a new `RangeDataMapping` object #' @param x Name of x variable to map #' @param ymin Name of ymin variable to map #' @param ymax Name of ymax variable to map - #' @param groupMapping R6 class \code{GroupMapping} object - #' @param color R6 class \code{Grouping} object or its input - #' @param fill R6 class \code{Grouping} object or its input - #' @param linetype R6 class \code{Grouping} object or its input - #' @param shape R6 class \code{Grouping} object or its input - #' @param size R6 class \code{Grouping} object or its input - #' @param data data.frame to map used by \code{smartMapping} - #' @return A new \code{RangeDataMapping} object + #' @param groupMapping R6 class `GroupMapping` object + #' @param color R6 class `Grouping` object or its input + #' @param fill R6 class `Grouping` object or its input + #' @param linetype R6 class `Grouping` object or its input + #' @param shape R6 class `Grouping` object or its input + #' @param size R6 class `Grouping` object or its input + #' @param data data.frame to map used by `smartMapping` + #' @return A new `RangeDataMapping` object initialize = function(x = NULL, - ymin = NULL, - ymax = NULL, - groupMapping = NULL, - color = NULL, - fill = NULL, - linetype = NULL, - shape = NULL, - size = NULL, - data = NULL) { + ymin = NULL, + ymax = NULL, + groupMapping = NULL, + color = NULL, + fill = NULL, + linetype = NULL, + shape = NULL, + size = NULL, + data = NULL) { # smartMapping is available in utilities-mapping.R smartMap <- smartMapping(data) @@ -45,11 +45,11 @@ RangeDataMapping <- R6::R6Class( self$ymax <- ymax %||% smartMap$ymax }, - #' @description Check that \code{data} variables include map variables + #' @description Check that `data` variables include map variables #' @param data data.frame to check - #' @param metaData list containing information on \code{data} - #' @return A data.frame with map and \code{legendLabels} variables. - #' Dummy variable \code{legendLabels} is necessary to allow further modification of plots. + #' @param metaData list containing information on `data` + #' @return A data.frame with map and `legendLabels` variables. + #' Dummy variable `legendLabels` is necessary to allow further modification of plots. checkMapData = function(data, metaData = NULL) { validateMapping(self$x, data, nullAllowed = TRUE) if (isOfType(self$ymin, "character")) { diff --git a/R/datamapping-xy.R b/R/datamapping-xy.R index 2a16e4ee..9ec86f51 100644 --- a/R/datamapping-xy.R +++ b/R/datamapping-xy.R @@ -1,5 +1,5 @@ #' @title XYDataMapping -#' @description R6 class for mapping \code{x} and \code{y} variable to \code{data} +#' @description R6 class for mapping `x` and `y` variable to `data` #' @export XYDataMapping <- R6::R6Class( "XYDataMapping", @@ -11,12 +11,12 @@ XYDataMapping <- R6::R6Class( #' @field data data.frame used for mapping data = NULL, - #' @description Create a new \code{XYDataMapping} object + #' @description Create a new `XYDataMapping` object #' @param x Name of x variable to map #' @param y Name of y variable to map - #' @return A new \code{XYDataMapping} object + #' @return A new `XYDataMapping` object initialize = function(x, - y = NULL) { + y = NULL) { if (isOfType(x, "numeric")) { warning(paste("'x' is a numeric, dataMapping will select the column of indice", x, "in data")) } @@ -28,11 +28,11 @@ XYDataMapping <- R6::R6Class( self$y <- y }, - #' @description Check that \code{data} variables include map variables + #' @description Check that `data` variables include map variables #' @param data data.frame to check - #' @param metaData list containing information on \code{data} - #' @return A data.frame with map and \code{defaultAes} variables. - #' Dummy variable \code{defaultAes} is necessary to allow further modification of plots. + #' @param metaData list containing information on `data` + #' @return A data.frame with map and `defaultAes` variables. + #' Dummy variable `defaultAes` is necessary to allow further modification of plots. checkMapData = function(data, metaData = NULL) { if (isOfType(self$x, "character")) { validateMapping(self$x, data) diff --git a/R/datamapping-xygroup.R b/R/datamapping-xygroup.R index 87a8d6e0..c6c3fd6f 100644 --- a/R/datamapping-xygroup.R +++ b/R/datamapping-xygroup.R @@ -1,33 +1,33 @@ #' @title XYGDataMapping -#' @description R6 class for mapping \code{x}, \code{y} and \code{GroupMapping} variables to \code{data} +#' @description R6 class for mapping `x`, `y` and `GroupMapping` variables to `data` #' @export XYGDataMapping <- R6::R6Class( "XYGDataMapping", inherit = XYDataMapping, public = list( - #' @field groupMapping R6 class \code{GroupMapping} object + #' @field groupMapping R6 class `GroupMapping` object groupMapping = NULL, - #' @description Create a new \code{XYGDataMapping} object + #' @description Create a new `XYGDataMapping` object #' @param x Name of x variable to map #' @param y Name of y variable to map - #' @param groupMapping R6 class \code{GroupMapping} object - #' @param color R6 class \code{Grouping} object or its input - #' @param fill R6 class \code{Grouping} object or its input - #' @param linetype R6 class \code{Grouping} object or its input - #' @param shape R6 class \code{Grouping} object or its input - #' @param size R6 class \code{Grouping} object or its input - #' @param data data.frame to map used by \code{smartMapping} - #' @return A new \code{XYGDataMapping} object + #' @param groupMapping R6 class `GroupMapping` object + #' @param color R6 class `Grouping` object or its input + #' @param fill R6 class `Grouping` object or its input + #' @param linetype R6 class `Grouping` object or its input + #' @param shape R6 class `Grouping` object or its input + #' @param size R6 class `Grouping` object or its input + #' @param data data.frame to map used by `smartMapping` + #' @return A new `XYGDataMapping` object initialize = function(x = NULL, - y = NULL, - groupMapping = NULL, - color = NULL, - fill = NULL, - linetype = NULL, - shape = NULL, - size = NULL, - data = NULL) { + y = NULL, + groupMapping = NULL, + color = NULL, + fill = NULL, + linetype = NULL, + shape = NULL, + size = NULL, + data = NULL) { # smartMapping is available in utilities-mapping.R smartMap <- smartMapping(data) @@ -50,11 +50,11 @@ XYGDataMapping <- R6::R6Class( ) }, - #' @description Check that \code{data} variables include map variables + #' @description Check that `data` variables include map variables #' @param data data.frame to check - #' @param metaData list containing information on \code{data} - #' @return A data.frame with map and \code{defaultAes} variables. - #' Dummy variable \code{defaultAes} is necessary to allow further modification of plots. + #' @param metaData list containing information on `data` + #' @return A data.frame with map and `defaultAes` variables. + #' Dummy variable `defaultAes` is necessary to allow further modification of plots. checkMapData = function(data, metaData = NULL) { validateMapping(self$x, data, nullAllowed = TRUE) validateMapping(self$y, data, nullAllowed = TRUE) diff --git a/R/ddiratio-datamapping.R b/R/ddiratio-datamapping.R index f49225a7..312d793b 100644 --- a/R/ddiratio-datamapping.R +++ b/R/ddiratio-datamapping.R @@ -1,27 +1,26 @@ #' @title DDIRatioDataMapping -#' @description R6 class for mapping \code{x}, \code{y}, \code{GroupMapping} and \code{ddiRatioLines} variables to \code{data} +#' @description R6 class for mapping `x`, `y`, `GroupMapping` and `ddiRatioLines` variables to `data` #' @export DDIRatioDataMapping <- R6::R6Class( "DDIRatioDataMapping", inherit = PKRatioDataMapping, - public = list( #' @field minRange Mininmum range for guest and ratio lines minRange = NULL, #' @field deltaGuest Value of `delta` in Guest et al. equation deltaGuest = NULL, - #' @description Create a new \code{DDIRatioDataMapping} object + #' @description Create a new `DDIRatioDataMapping` object #' @param deltaGuest Value of parameter `delta` in Guest et al. equation. #' Default value is 1. #' @param minRange Mininmum range for guest lines #' @param lines list of ratio limits to plot as diagonal lines - #' @param ... parameters inherited from \code{PKRatioDataMapping} - #' @return A new \code{DDIRatioDataMapping} object + #' @param ... parameters inherited from `PKRatioDataMapping` + #' @return A new `DDIRatioDataMapping` object initialize = function(deltaGuest = 1, - minRange = c(1e-2, 1e2), - lines = DefaultDataMappingValues$ddiRatio, - ...) { + minRange = c(1e-2, 1e2), + lines = DefaultDataMappingValues$ddiRatio, + ...) { super$initialize(...) # Apply log10 transformation to lines because # plot is log scaled in by default and geom_abline diff --git a/R/ddiratio-plotconfiguration.R b/R/ddiratio-plotconfiguration.R index c4d66bf6..77358ab2 100644 --- a/R/ddiratio-plotconfiguration.R +++ b/R/ddiratio-plotconfiguration.R @@ -1,5 +1,5 @@ #' @title DDIRatioPlotConfiguration -#' @description R6 class defining the configuration of a \code{ggplot} object for DDI Ratio plots +#' @description R6 class defining the configuration of a `ggplot` object for DDI Ratio plots #' @export DDIRatioPlotConfiguration <- R6::R6Class( "DDIRatioPlotConfiguration", diff --git a/R/enum.R b/R/enum.R index 8bf2f1bd..90bfca96 100644 --- a/R/enum.R +++ b/R/enum.R @@ -1,4 +1,4 @@ -#' Create an enumeration to be used instead of arbitraty values in code. +#' Create an enumeration to be used instead of arbitrary values in code. #' #' @param enumValues Values to use for the enum #' diff --git a/R/font.R b/R/font.R index d3745bc6..81580c72 100644 --- a/R/font.R +++ b/R/font.R @@ -15,7 +15,7 @@ Font <- R6::R6Class( fontFace = "plain", angle = 0, - #' @description Create a new \code{Font} object. + #' @description Create a new `Font` object. #' Default font properties are defined directly in the object field, #' so `NULL` input is allowed will lead to default properties. #' @param size numeric defining the size of font @@ -23,12 +23,12 @@ Font <- R6::R6Class( #' @param fontFamily character defining the family of font #' @param fontFace character defining the face of font #' @param angle numeric defining the angle of font - #' @return A new \code{Font} object + #' @return A new `Font` object initialize = function(size = NULL, - color = NULL, - fontFamily = NULL, - fontFace = NULL, - angle = NULL) { + color = NULL, + fontFamily = NULL, + fontFace = NULL, + angle = NULL) { validateIsString(c(color, fontFamily, fontFace), nullAllowed = TRUE) validateIsNumeric(c(size, angle), nullAllowed = TRUE) eval(parseVariableToObject("self", c("size", "color", "fontFace", "fontFamily", "angle"), keepIfNull = TRUE)) diff --git a/R/histogram-datamapping.R b/R/histogram-datamapping.R index 54b8f924..18c8ec4e 100644 --- a/R/histogram-datamapping.R +++ b/R/histogram-datamapping.R @@ -1,6 +1,6 @@ #' @title HistogramDataMapping -#' @description R6 class for mapping \code{x}, \code{verticalLineGroupings}, -#' \code{verticalLineFunctionNames} and \code{verticalLineFunctions} variables to \code{data} +#' @description R6 class for mapping `x`, `verticalLineGroupings`, +#' `verticalLineFunctionNames` and `verticalLineFunctions` variables to `data` #' @export HistogramDataMapping <- R6::R6Class( "HistogramDataMapping", @@ -17,20 +17,20 @@ HistogramDataMapping <- R6::R6Class( #' @field fitDensity logical defining if a density distribution function should be fitted fitDensity = NULL, - #' @description Create a new \code{HistogramDataMapping} object + #' @description Create a new `HistogramDataMapping` object #' @param stack logical defining if histogram bars should be stacked #' @param bins argument passed on `ggplot2::geom_histogram` #' @param lines values or functions to define vertical lines #' @param fitNormalDist logical defining if a normal distribution should be fitted #' @param fitDensity logical defining if a density distribution should be fitted - #' @param ... parameters inherited from \code{XYGDataMapping} - #' @return A new \code{HistogramDataMapping} object + #' @param ... parameters inherited from `XYGDataMapping` + #' @return A new `HistogramDataMapping` object initialize = function(stack = FALSE, - bins = NULL, - lines = DefaultDataMappingValues$histogram, - fitNormalDist = FALSE, - fitDensity = FALSE, - ...) { + bins = NULL, + lines = DefaultDataMappingValues$histogram, + fitNormalDist = FALSE, + fitDensity = FALSE, + ...) { super$initialize(...) validateIsLogical(stack) validateIsLogical(fitNormalDist) diff --git a/R/histogram-plotconfiguration.R b/R/histogram-plotconfiguration.R index c10ab84b..af1458b4 100644 --- a/R/histogram-plotconfiguration.R +++ b/R/histogram-plotconfiguration.R @@ -1,22 +1,21 @@ #' @title HistogramPlotConfiguration -#' @description R6 class defining the configuration of a \code{ggplot} object for histograms +#' @description R6 class defining the configuration of a `ggplot` object for histograms #' @export HistogramPlotConfiguration <- R6::R6Class( "HistogramPlotConfiguration", inherit = PlotConfiguration, - public = list( - #' @description Create a new \code{HistogramPlotConfiguration} object + #' @description Create a new `HistogramPlotConfiguration` object #' @param lines `ThemeAestheticSelections` object defining properties for vertical lines #' @param ribbons `ThemeAestheticSelections` object defining properties for histogram #' @param ylabel Histograms default display is "Count" - #' @param ... parameters inherited from \code{PlotConfiguration} - #' @return A new \code{TimeProfilePlotConfiguration} object + #' @param ... parameters inherited from `PlotConfiguration` + #' @return A new `TimeProfilePlotConfiguration` object initialize = function(lines = NULL, - ribbons = NULL, - ylabel = "Count", - ...) { + ribbons = NULL, + ylabel = "Count", + ...) { super$initialize(ylabel = ylabel, ...) validateIsOfType(lines, "ThemeAestheticSelections", nullAllowed = TRUE) @@ -26,12 +25,12 @@ HistogramPlotConfiguration <- R6::R6Class( private$.ribbons <- ribbons %||% asThemeAestheticSelections(currentTheme$plotConfigurations$plotHistogram$ribbons) }, - #' @description Add statistics as line layer to a \code{ggplot} object - #' @param plotObject \code{ggplot} object + #' @description Add statistics as line layer to a `ggplot` object + #' @param plotObject `ggplot` object #' @param data data.frame - #' @param metaData list of information on \code{data} - #' @param dataMapping R6 class \code{HistogramDataMapping} - #' @return A \code{ggplot} object + #' @param metaData list of information on `data` + #' @param dataMapping R6 class `HistogramDataMapping` + #' @return A `ggplot` object addVerticalLines = function(plotObject, data, metaData, dataMapping) { if (!is.null(dataMapping$verticalLineFunctions)) { fillVec <- tlfEnv$currentTheme$aesProperties$fill @@ -66,7 +65,7 @@ HistogramPlotConfiguration <- R6::R6Class( aes_string(xintercept = "value", color = "summaryCaptions", linetype = "summaryCaptions"), size = 1 ) + scale_colour_manual( name = "Summary", - values = fillVec[ rep(seq(1, numHistograms), each = numVerticalLineFunctions) ], + values = fillVec[rep(seq(1, numHistograms), each = numVerticalLineFunctions)], labels = legendLabels ) + scale_linetype_manual( name = "Summary", diff --git a/R/label.R b/R/label.R index aa727cfa..1a798df1 100644 --- a/R/label.R +++ b/R/label.R @@ -1,25 +1,25 @@ #' @title Label -#' @description R6 class defining \code{text} and \code{font} of label +#' @description R6 class defining `text` and `font` of label #' @export Label <- R6::R6Class( "Label", public = list( - #' @description Create a new \code{Label} object. - #' @param text character text of the \code{Label} object - #' @param font \code{Font} object defining the font of the `Label` object + #' @description Create a new `Label` object. + #' @param text character text of the `Label` object + #' @param font `Font` object defining the font of the `Label` object #' @param size numeric defining the size of the `Label` object #' @param color character defining the color of the `Label` object #' @param fontFamily character defining the font family of the `Label` object #' @param fontFace character defining the font face of the `Label` object #' @param angle numeric defining the angle of the `Label` object - #' @return A new \code{Label} object + #' @return A new `Label` object initialize = function(text = "", - font = NULL, - color = NULL, - size = NULL, - fontFace = NULL, - fontFamily = NULL, - angle = NULL) { + font = NULL, + color = NULL, + size = NULL, + fontFace = NULL, + fontFamily = NULL, + angle = NULL) { validateIsNumeric(c(as.numeric(angle), as.numeric(size)), nullAllowed = TRUE) validateIsString(c(color, fontFace, fontFamily), nullAllowed = TRUE) validateIsOfType(font, "Font", nullAllowed = TRUE) @@ -49,7 +49,7 @@ Label <- R6::R6Class( private$.text <- value return(invisible()) }, - #' @field font \code{Font} object + #' @field font `Font` object font = function(value) { if (missing(value)) { return(private$.font) diff --git a/R/messages.R b/R/messages.R index 212807c3..9518a454 100644 --- a/R/messages.R +++ b/R/messages.R @@ -11,7 +11,6 @@ messages <- list( "' is of type '", type, "', but expected '", expectedTypeMsg, "'!", optionalMessage ) }, - errorDifferentLength = function(objectNames, optionalMessage = NULL) { # Name of the calling function callingFunctions <- sys.calls() @@ -22,7 +21,6 @@ messages <- list( "' must have the same length, but they don't!", optionalMessage ) }, - errorWrongLength = function(object, nbElements, optionalMessage = NULL) { # Name of the calling function callingFunctions <- sys.calls() @@ -31,28 +29,22 @@ messages <- list( callingFunction, ": Object should be of length '", nbElements, "', but is of length '", length(object), "' instead. ", optionalMessage ) }, - errorEnumNotAllNames = "The enumValues has some but not all names assigned. They must be all assigned or none assigned", - errorValueNotInEnum = function(enum, value) { paste0("Value '", value, "' is not in defined enumeration values: '", paste0(names(enum), collapse = ", "), "'.") }, - errorNotIncluded = function(values, parentValues) { paste0("Values '", paste0(values, collapse = ", "), "' are not in included in parent values: '", paste0(parentValues, collapse = ", "), "'.") }, - errorExceedLength = function(values, parentLengths) { paste0("Values '", paste0(values, collapse = ", "), "' exceed variable length : '", paste0(parentLengths, collapse = ", "), "'.") }, - errorConflictingInput = function(eitherInput, orInput) { paste0( "Conflicting inputs provided. Inputs '", paste0(eitherInput, collapse = ", "), "' and '", paste0(orInput, collapse = ", "), "' can't be provided at the same time." ) }, - errorNrowData = function(plotName) { paste0("nrow(data)=0. ", plotName, " layer could not be added.") } diff --git a/R/obs-vs-pred-datamapping.R b/R/obs-vs-pred-datamapping.R index 9af97fcc..1f0b6819 100644 --- a/R/obs-vs-pred-datamapping.R +++ b/R/obs-vs-pred-datamapping.R @@ -8,15 +8,15 @@ ObsVsPredDataMapping <- R6::R6Class( #' @field smoother regression function name smoother = NULL, - #' @description Create a new \code{ObsVsPredDataMapping} object + #' @description Create a new `ObsVsPredDataMapping` object #' @param lines list of lines to plot #' @param smoother smoother function or parameter #' To map a loess smoother to the plot, use `smoother`="loess" - #' @param ... parameters inherited from \code{XYGDataMapping} - #' @return A new \code{ObsVsPredDataMapping} object + #' @param ... parameters inherited from `XYGDataMapping` + #' @return A new `ObsVsPredDataMapping` object initialize = function(lines = DefaultDataMappingValues$obsVsPred, - smoother = NULL, - ...) { + smoother = NULL, + ...) { validateIsIncluded(smoother, c("lm", "loess"), nullAllowed = TRUE) super$initialize(...) diff --git a/R/obs-vs-pred-plotconfiguration.R b/R/obs-vs-pred-plotconfiguration.R index 9c1c251f..7cea1199 100644 --- a/R/obs-vs-pred-plotconfiguration.R +++ b/R/obs-vs-pred-plotconfiguration.R @@ -1,20 +1,20 @@ #' @title ObsVsPredPlotConfiguration -#' @description R6 class defining the configuration of a \code{ggplot} object for Obs vs Pred plots +#' @description R6 class defining the configuration of a `ggplot` object for Obs vs Pred plots #' @export ObsVsPredPlotConfiguration <- R6::R6Class( "ObsVsPredPlotConfiguration", inherit = PlotConfiguration, public = list( - #' @description Create a new \code{ObsVsPredPlotConfiguration} object + #' @description Create a new `ObsVsPredPlotConfiguration` object #' @param lines `ThemeAestheticSelections` object defining properties for lines #' @param points `ThemeAestheticSelections` object defining properties for scatter points #' @param errorbars `ThemeAestheticSelections` object defining properties for error bars - #' @param ... parameters inherited from \code{PlotConfiguration} - #' @return A new \code{ObsVsPredPlotConfiguration} object + #' @param ... parameters inherited from `PlotConfiguration` + #' @return A new `ObsVsPredPlotConfiguration` object initialize = function(lines = NULL, - points = NULL, - errorbars = NULL, - ...) { + points = NULL, + errorbars = NULL, + ...) { super$initialize(...) validateIsOfType(lines, "ThemeAestheticSelections", nullAllowed = TRUE) @@ -29,7 +29,7 @@ ObsVsPredPlotConfiguration <- R6::R6Class( ) #' @title ResVsPredPlotConfiguration -#' @description R6 class defining the configuration of a \code{ggplot} object for Res vs Pred/Time plots +#' @description R6 class defining the configuration of a `ggplot` object for Res vs Pred/Time plots #' @export ResVsPredPlotConfiguration <- R6::R6Class( "ResVsPredPlotConfiguration", diff --git a/R/observed-data-mapping.R b/R/observed-data-mapping.R index 3ba9a767..86ac3cd6 100644 --- a/R/observed-data-mapping.R +++ b/R/observed-data-mapping.R @@ -1,5 +1,5 @@ #' @title ObservedDataMapping -#' @description R6 class for mapping \code{x}, \code{y}, of observed data for a time profile plot +#' @description R6 class for mapping `x`, `y`, of observed data for a time profile plot #' @export ObservedDataMapping <- R6::R6Class( "ObservedDataMapping", @@ -16,16 +16,16 @@ ObservedDataMapping <- R6::R6Class( #' @field ymax mapping error bars around scatter points ymax = "ymax", - #' @description Create a new \code{PKRatioDataMapping} object + #' @description Create a new `PKRatioDataMapping` object #' @param lloq mapping lower limit of quantitation variable #' @param uncertainty mapping error bars around scatter points #' @param mdv mapping missing dependent variable - #' @param ... parameters inherited from \code{XYGDataMapping} - #' @return A new \code{PKRatioDataMapping} object + #' @param ... parameters inherited from `XYGDataMapping` + #' @return A new `PKRatioDataMapping` object initialize = function(lloq = NULL, - uncertainty = NULL, - mdv = NULL, - ...) { + uncertainty = NULL, + mdv = NULL, + ...) { validateIsString(lloq, nullAllowed = TRUE) validateIsString(uncertainty, nullAllowed = TRUE) validateIsString(mdv, nullAllowed = TRUE) @@ -35,11 +35,11 @@ ObservedDataMapping <- R6::R6Class( self$mdv <- mdv }, - #' @description Check that \code{data} variables include map variables + #' @description Check that `data` variables include map variables #' @param data data.frame to check - #' @param metaData list containing information on \code{data} - #' @return A data.frame with map and \code{defaultAes} variables. - #' Dummy variable \code{defaultAes} is necessary to allow further modification of plots. + #' @param metaData list containing information on `data` + #' @return A data.frame with map and `defaultAes` variables. + #' Dummy variable `defaultAes` is necessary to allow further modification of plots. checkMapData = function(data, metaData = NULL) { validateIsOfType(data, "data.frame") validateIsIncluded(self$uncertainty, names(data), nullAllowed = TRUE) diff --git a/R/pkratio-datamapping.R b/R/pkratio-datamapping.R index 0cab8d39..87979629 100644 --- a/R/pkratio-datamapping.R +++ b/R/pkratio-datamapping.R @@ -1,5 +1,5 @@ #' @title PKRatioDataMapping -#' @description R6 class for mapping \code{x}, \code{y}, \code{GroupMapping} and pkRatio \code{lines} variables to \code{data} +#' @description R6 class for mapping `x`, `y`, `GroupMapping` and pkRatio `lines` variables to `data` #' @export PKRatioDataMapping <- R6::R6Class( "PKRatioDataMapping", @@ -10,25 +10,25 @@ PKRatioDataMapping <- R6::R6Class( #' @field uncertainty mapping error bars around scatter points uncertainty = NULL, - #' @description Create a new \code{PKRatioDataMapping} object + #' @description Create a new `PKRatioDataMapping` object #' @param lines list of ratio limits to plot as horizontal lines #' @param uncertainty mapping error bars around scatter points - #' @param ... parameters inherited from \code{XYGDataMapping} - #' @return A new \code{PKRatioDataMapping} object + #' @param ... parameters inherited from `XYGDataMapping` + #' @return A new `PKRatioDataMapping` object initialize = function(lines = DefaultDataMappingValues$pkRatio, - uncertainty = NULL, - ...) { + uncertainty = NULL, + ...) { validateIsString(uncertainty, nullAllowed = TRUE) super$initialize(...) self$lines <- lines self$uncertainty <- uncertainty }, - #' @description Check that \code{data} variables include map variables + #' @description Check that `data` variables include map variables #' @param data data.frame to check - #' @param metaData list containing information on \code{data} - #' @return A data.frame with map and \code{defaultAes} variables. - #' Dummy variable \code{defaultAes} is necessary to allow further modification of plots. + #' @param metaData list containing information on `data` + #' @return A data.frame with map and `defaultAes` variables. + #' Dummy variable `defaultAes` is necessary to allow further modification of plots. checkMapData = function(data, metaData = NULL) { validateIsOfType(data, "data.frame") validateMapping(self$uncertainty, data, nullAllowed = TRUE) diff --git a/R/pkratio-plotconfiguration.R b/R/pkratio-plotconfiguration.R index 66ee5eec..accf220f 100644 --- a/R/pkratio-plotconfiguration.R +++ b/R/pkratio-plotconfiguration.R @@ -1,21 +1,21 @@ #' @title PKRatioPlotConfiguration -#' @description R6 class defining the configuration of a \code{ggplot} object for PK ratio plots +#' @description R6 class defining the configuration of a `ggplot` object for PK ratio plots #' @export PKRatioPlotConfiguration <- R6::R6Class( "PKRatioPlotConfiguration", inherit = PlotConfiguration, public = list( - #' @description Create a new \code{PKRatioPlotConfiguration} object + #' @description Create a new `PKRatioPlotConfiguration` object #' @param lines `ThemeAestheticSelections` object defining properties for PK ratio horizontal lines #' @param points `ThemeAestheticSelections` object defining properties for PK ratio scatter points #' @param errorbars `ThemeAestheticSelections` object defining properties for PK ratio error bars - #' @param ... parameters inherited from \code{PlotConfiguration} - #' @return A new \code{PKRatioPlotConfiguration} object + #' @param ... parameters inherited from `PlotConfiguration` + #' @return A new `PKRatioPlotConfiguration` object initialize = function(lines = NULL, - points = NULL, - errorbars = NULL, - ...) { + points = NULL, + errorbars = NULL, + ...) { super$initialize(...) validateIsOfType(lines, "ThemeAestheticSelections", nullAllowed = TRUE) diff --git a/R/plot-boxwhisker.R b/R/plot-boxwhisker.R index 85396792..1b5307a8 100644 --- a/R/plot-boxwhisker.R +++ b/R/plot-boxwhisker.R @@ -54,13 +54,13 @@ plotBoxWhisker <- function(data, } #' @title addBoxWhisker -#' @description Add layer of boxes and whiskers to a \code{ggplot} object +#' @description Add layer of boxes and whiskers to a `ggplot` object #' @param data data.frame -#' @param metaData list of information on \code{data} -#' @param dataMapping \code{BoxWhiskerDataMapping} object -#' @param plotConfiguration \code{BoxWhiskerPlotConfiguration} object -#' @param plotObject a \code{ggplot} object -#' @return A \code{ggplot} object +#' @param metaData list of information on `data` +#' @param dataMapping `BoxWhiskerDataMapping` object +#' @param plotConfiguration `BoxWhiskerPlotConfiguration` object +#' @param plotObject a `ggplot` object +#' @return A `ggplot` object addBoxWhisker <- function(data, metaData, dataMapping, plotConfiguration, plotObject) { # Get the box plot quantiles from dataMapping @@ -100,22 +100,22 @@ addBoxWhisker <- function(data, metaData, dataMapping, plotConfiguration, plotOb # If variable is legendLabel, remove it from legend if (isIncluded(fillVariable, "legendLabels")) { - plotObject <- plotObject + ggplot2::guides(fill = FALSE) + plotObject <- plotObject + ggplot2::guides(fill = "none") } if (isIncluded(colorVariable, "legendLabels")) { - plotObject <- plotObject + ggplot2::guides(color = FALSE) + plotObject <- plotObject + ggplot2::guides(color = "none") } return(plotObject) } #' @title addOutliers -#' @description Add a outlier points layer to a \code{ggplot} object +#' @description Add a outlier points layer to a `ggplot` object #' @param data data.frame -#' @param metaData list of information on \code{data} -#' @param dataMapping \code{BoxWhiskerDataMapping} object -#' @param plotConfiguration \code{BoxWhiskerPlotConfiguration} object -#' @param plotObject a \code{ggplot} object -#' @return A \code{ggplot} object +#' @param metaData list of information on `data` +#' @param dataMapping `BoxWhiskerDataMapping` object +#' @param plotConfiguration `BoxWhiskerPlotConfiguration` object +#' @param plotObject a `ggplot` object +#' @return A `ggplot` object addOutliers <- function(data, metaData, dataMapping, plotConfiguration, plotObject) { mapData <- dataMapping$getOutliers(data) # Convert the mapping into characters usable by aes_string diff --git a/R/plot-ddiratio.R b/R/plot-ddiratio.R index 721533c1..40d03679 100644 --- a/R/plot-ddiratio.R +++ b/R/plot-ddiratio.R @@ -5,13 +5,13 @@ #' This parameter is optional. #' @param dataMapping A `DDIRatioDataMapping` object #' @param plotConfiguration A `DDIRatioPlotConfiguration` object -#' @param plotObject \code{ggplot} graphical object to which the PK Ratio plot layer is added -#' This parameter is optional: the \code{tlf} library will initialize an empty plot if the parameter is NULL or not provided +#' @param plotObject `ggplot` graphical object to which the PK Ratio plot layer is added +#' This parameter is optional: the `tlf` library will initialize an empty plot if the parameter is NULL or not provided #' @description -#' Add DDI Ratio plot layers to a \code{ggplot} graphical object. +#' Add DDI Ratio plot layers to a `ggplot` graphical object. #' Inclcuding Guest et al. limits, DDI Ratio limits as diagonal lines and #' DDI Ratios as a scatter plot. -#' @return A \code{ggplot} graphical object +#' @return A `ggplot` graphical object #' @export plotDDIRatio <- function(data, metaData = NULL, diff --git a/R/plot-histogram.R b/R/plot-histogram.R index 3f8fdc14..87361d92 100644 --- a/R/plot-histogram.R +++ b/R/plot-histogram.R @@ -115,7 +115,7 @@ plotHistogram <- function(data, # If variable is legendLabel, remove it from legend if (isIncluded(fillVariable, "legendLabels")) { - plotObject <- plotObject + ggplot2::guides(fill = FALSE) + plotObject <- plotObject + ggplot2::guides(fill = "none") } # dataMapping$smoother return(plotObject) diff --git a/R/plot-obs-vs-pred.R b/R/plot-obs-vs-pred.R index 78c9bafb..c0def05e 100644 --- a/R/plot-obs-vs-pred.R +++ b/R/plot-obs-vs-pred.R @@ -4,20 +4,20 @@ #' containing complementary information to data (e.g. their unit and dimension). #' This parameter is optional. #' @param dataMapping -#' \code{ObsVsPredDataMapping} class or subclass mapping x and y variables to \code{data} variable names. -#' \code{dataMapping} provides also the values of the identity and fold errors lines. -#' This parameter is optional: the \code{tlf} library provides a smart mapping if only \code{data} is provided +#' `ObsVsPredDataMapping` class or subclass mapping x and y variables to `data` variable names. +#' `dataMapping` provides also the values of the identity and fold errors lines. +#' This parameter is optional: the `tlf` library provides a smart mapping if only `data` is provided #' and default values of the identity and fold errors lines. #' @param plotConfiguration -#' \code{ObsVsPredConfiguration} class or subclass defining labels, grid, background and watermark -#' This parameter is optional: the \code{tlf} library provides a default configuration according to the current theme +#' `ObsVsPredConfiguration` class or subclass defining labels, grid, background and watermark +#' This parameter is optional: the `tlf` library provides a default configuration according to the current theme #' @param smoother smoother Name of smoother function: "loess" or "lm" -#' @param plotObject \code{ggplot} graphical object to which the Observations vs Predictions plot layer is added -#' This parameter is optional: the \code{tlf} library will initialize an empty plot if the parameter is NULL or not provided +#' @param plotObject `ggplot` graphical object to which the Observations vs Predictions plot layer is added +#' This parameter is optional: the `tlf` library will initialize an empty plot if the parameter is NULL or not provided #' @description -#' Add Observations vs Predictions plot layers to a \code{ggplot} graphical object. +#' Add Observations vs Predictions plot layers to a `ggplot` graphical object. #' Observations vs Predictions are plotted as a scatter plot. -#' @return A \code{ggplot} graphical object +#' @return A `ggplot` graphical object #' @export plotObsVsPred <- function(data, metaData = NULL, diff --git a/R/plot-pkratio.R b/R/plot-pkratio.R index 61932b6f..1c547d9f 100644 --- a/R/plot-pkratio.R +++ b/R/plot-pkratio.R @@ -4,20 +4,20 @@ #' containing complementary information to data (e.g. their unit and dimension). #' This parameter is optional. #' @param dataMapping -#' \code{PKRatioDataMapping} class or subclass mapping x and y variables to \code{data} variable names. -#' \code{dataMapping} provides also the values of the PK Ratio limits plotted as horizontal lines. -#' This parameter is optional: the \code{tlf} library provides a smart mapping if only \code{data} is provided +#' `PKRatioDataMapping` class or subclass mapping x and y variables to `data` variable names. +#' `dataMapping` provides also the values of the PK Ratio limits plotted as horizontal lines. +#' This parameter is optional: the `tlf` library provides a smart mapping if only `data` is provided #' and default values of the PK Ratio limits. #' @param plotConfiguration -#' \code{PKRatioPlotConfiguration} class or subclass defining labels, grid, background and watermark -#' This parameter is optional: the \code{tlf} library provides a default configuration according to the current theme -#' @param plotObject \code{ggplot} graphical object to which the PK Ratio plot layer is added -#' This parameter is optional: the \code{tlf} library will initialize an empty plot if the parameter is NULL or not provided +#' `PKRatioPlotConfiguration` class or subclass defining labels, grid, background and watermark +#' This parameter is optional: the `tlf` library provides a default configuration according to the current theme +#' @param plotObject `ggplot` graphical object to which the PK Ratio plot layer is added +#' This parameter is optional: the `tlf` library will initialize an empty plot if the parameter is NULL or not provided #' @description -#' Add PK Ratio plot layers to a \code{ggplot} graphical object. +#' Add PK Ratio plot layers to a `ggplot` graphical object. #' PK Ratio limits are plotted as horizontal lines. #' PK Ratios are plotted as a scatter plot. -#' @return A \code{ggplot} graphical object +#' @return A `ggplot` graphical object #' @export plotPKRatio <- function(data, metaData = NULL, diff --git a/R/plot-res-vs-pred.R b/R/plot-res-vs-pred.R index 792a490d..8db55c2d 100644 --- a/R/plot-res-vs-pred.R +++ b/R/plot-res-vs-pred.R @@ -1,9 +1,9 @@ #' @title plotResVsPred #' @inheritParams plotObsVsPred #' @description -#' Add Residuals vs Predictions / Time plot layers to a \code{ggplot} graphical object. +#' Add Residuals vs Predictions / Time plot layers to a `ggplot` graphical object. #' Residuals vs Predictions are plotted as a scatter plot. -#' @return A \code{ggplot} graphical object +#' @return A `ggplot` graphical object #' @export plotResVsPred <- function(data, metaData = NULL, @@ -16,9 +16,9 @@ plotResVsPred <- function(data, dataMapping$smoother <- smoother %||% dataMapping$smoother mapData <- dataMapping$checkMapData(data) mapLabels <- getAesStringMapping(dataMapping) - + plotObject <- plotObject %||% initializePlot(plotConfiguration) - + for (lineIndex in seq_along(dataMapping$lines)) { eval(parseAddLineLayer("horizontal", dataMapping$lines[[lineIndex]], lineIndex - 1)) } @@ -52,7 +52,7 @@ plotResVsPred <- function(data, size = getAestheticValues(n = 1, selectionKey = plotConfiguration$lines$size, position = lineIndex, aesthetic = "size") ) } - + # If uncertainty is defined, add error bars if (!isOfLength(dataMapping$uncertainty, 0)) { eval(parseAddUncertaintyLayer()) diff --git a/R/plot-tornado.R b/R/plot-tornado.R index 3cac543a..1fc4d9dd 100644 --- a/R/plot-tornado.R +++ b/R/plot-tornado.R @@ -4,28 +4,28 @@ #' containing complementary information to data (e.g. their unit and dimension). #' This parameter is optional. #' @param x Mapping for x (values of tornado plot) -#' If \code{data} is NULL or not input, \code{x} numeric values will be used as is for the plot. +#' If `data` is NULL or not input, `x` numeric values will be used as is for the plot. #' @param y Mapping for y (labels of tornado plot) -#' If \code{data} is NULL or not input, \code{y} character values will be used as is for the plot. -#' @param sorted logical indicating if values should be sorted if \code{dataMapping} is not input. +#' If `data` is NULL or not input, `y` character values will be used as is for the plot. +#' @param sorted logical indicating if values should be sorted if `dataMapping` is not input. #' By default, values are sorted by their absolute values #' @param colorPalette Define a `ggplot2` colorPalette (e.g `colorPalette`="Spectral") #' @param bar logical setting tornado as bar plot #' @param dataMapping -#' \code{TornadoDataMapping} class or subclass mapping x and y variables to \code{data} variable names. -#' \code{dataMapping} provides also the values of the PK Ratio limits plotted as horizontal lines. -#' This parameter is optional: the \code{tlf} library provides a smart mapping if only \code{data} is provided +#' `TornadoDataMapping` class or subclass mapping x and y variables to `data` variable names. +#' `dataMapping` provides also the values of the PK Ratio limits plotted as horizontal lines. +#' This parameter is optional: the `tlf` library provides a smart mapping if only `data` is provided #' and default values of the PK Ratio limits. #' @param plotConfiguration -#' \code{TornadoPlotConfiguration} class or subclass defining labels, grid, background and watermark -#' This parameter is optional: the \code{tlf} library provides a default configuration according to the current theme -#' @param plotObject \code{ggplot} graphical object to which the tornado plot layer is added -#' This parameter is optional: the \code{tlf} library will initialize an empty plot if the parameter is NULL or not provided +#' `TornadoPlotConfiguration` class or subclass defining labels, grid, background and watermark +#' This parameter is optional: the `tlf` library provides a default configuration according to the current theme +#' @param plotObject `ggplot` graphical object to which the tornado plot layer is added +#' This parameter is optional: the `tlf` library will initialize an empty plot if the parameter is NULL or not provided #' @description -#' Add tornado plot layers to a \code{ggplot} graphical object. +#' Add tornado plot layers to a `ggplot` graphical object. #' Tornado limits are plotted as vertical lines. #' Tornado values are plotted as horizontal bars or point according to option `bar` -#' @return A \code{ggplot} graphical object +#' @return A `ggplot` graphical object #' @export plotTornado <- function(data = NULL, metaData = NULL, diff --git a/R/plotconfiguration-axis.R b/R/plotconfiguration-axis.R index 4f3ea21f..e37fa643 100644 --- a/R/plotconfiguration-axis.R +++ b/R/plotconfiguration-axis.R @@ -53,19 +53,19 @@ createPlotTicks <- function(ticks) { AxisConfiguration <- R6::R6Class( "AxisConfiguration", public = list( - #' @description Create a new \code{AxisConfiguration} object + #' @description Create a new `AxisConfiguration` object #' @param limits numeric vector of axis limits #' @param scale character defining axis scale #' Use enum `Scaling` to access predefined scales. #' @param ticks numeric vector or function defining where to position axis ticks #' @param ticklabels character vector or function defining what to print on axis ticks - #' @param font \code{Font} object defining the font of ticklabels - #' @return A new \code{AxisConfiguration} object + #' @param font `Font` object defining the font of ticklabels + #' @return A new `AxisConfiguration` object initialize = function(limits = NULL, - scale = Scaling$lin, - ticks = NULL, - ticklabels = NULL, - font = NULL) { + scale = Scaling$lin, + ticks = NULL, + ticklabels = NULL, + font = NULL) { validateIsNumeric(limits, nullAllowed = TRUE) validateIsOfType(font, "Font", nullAllowed = TRUE) private$.limits <- limits @@ -129,7 +129,7 @@ AxisConfiguration <- R6::R6Class( private$.ticklabels <- createPlotTicks(value) return(invisible()) }, - #' @field font \code{Font} object defining the font of the ticklabels + #' @field font `Font` object defining the font of the ticklabels font = function(value) { if (missing(value)) { return(private$.font) @@ -164,9 +164,9 @@ XAxisConfiguration <- R6::R6Class( "XAxisConfiguration", inherit = AxisConfiguration, public = list( - #' @description Update axis configuration on a \code{ggplot} object - #' @param plotObject \code{ggplot} object - #' @return A \code{ggplot} object with updated axis properties + #' @description Update axis configuration on a `ggplot` object + #' @param plotObject `ggplot` object + #' @return A `ggplot` object with updated axis properties updatePlot = function(plotObject) { validateIsOfType(plotObject, "ggplot") # Update font properties @@ -204,9 +204,9 @@ YAxisConfiguration <- R6::R6Class( #' @field position character poistion of the Y-axis position = NULL, # TO DO: find a way to include position in y axis, then scale position = "left" or "right" - #' @description Update axis configuration on a \code{ggplot} object - #' @param plotObject \code{ggplot} object - #' @return A \code{ggplot} object with updated axis properties + #' @description Update axis configuration on a `ggplot` object + #' @param plotObject `ggplot` object + #' @return A `ggplot` object with updated axis properties updatePlot = function(plotObject) { validateIsOfType(plotObject, "ggplot") # Update font properties diff --git a/R/plotconfiguration-background.R b/R/plotconfiguration-background.R index 35970760..f37bbd1f 100644 --- a/R/plotconfiguration-background.R +++ b/R/plotconfiguration-background.R @@ -4,22 +4,22 @@ BackgroundConfiguration <- R6::R6Class( "BackgroundConfiguration", public = list( - #' @description Create a new \code{BackgroundConfiguration} object - #' @param watermark \code{Label} object defining properties of watermark - #' @param plot \code{BackgroundElement} object defining oustide plot background properties - #' @param panel \code{BackgroundElement} object defining panel (inside of plot) background properties - #' @param xAxis \code{LineElement} object defining properties of x-axis - #' @param yAxis \code{LineElement} object defining properties of y-axis - #' @param xGrid \code{LineElement} object defining properties of x-grid - #' @param yGrid \code{LineElement} object defining properties of y-grid - #' @return A new \code{BackgroundConfiguration} object + #' @description Create a new `BackgroundConfiguration` object + #' @param watermark `Label` object defining properties of watermark + #' @param plot `BackgroundElement` object defining oustide plot background properties + #' @param panel `BackgroundElement` object defining panel (inside of plot) background properties + #' @param xAxis `LineElement` object defining properties of x-axis + #' @param yAxis `LineElement` object defining properties of y-axis + #' @param xGrid `LineElement` object defining properties of x-grid + #' @param yGrid `LineElement` object defining properties of y-grid + #' @return A new `BackgroundConfiguration` object initialize = function(watermark = NULL, - plot = NULL, - panel = NULL, - xAxis = NULL, - yAxis = NULL, - xGrid = NULL, - yGrid = NULL) { + plot = NULL, + panel = NULL, + xAxis = NULL, + yAxis = NULL, + xGrid = NULL, + yGrid = NULL) { validateIsOfType(watermark, c("character", "Label"), nullAllowed = TRUE) currentTheme <- tlfEnv$currentTheme$clone(deep = TRUE) watermark <- watermark %||% currentTheme$background$watermark @@ -43,9 +43,9 @@ BackgroundConfiguration <- R6::R6Class( eval(setLineExpression) }, - #' @description Update background a \code{ggplot} object from `BackgroundConfiguration` properties - #' @param plotObject a \code{ggplot} object - #' @return A \code{ggplot} object + #' @description Update background a `ggplot` object from `BackgroundConfiguration` properties + #' @param plotObject a `ggplot` object + #' @return A `ggplot` object updatePlot = function(plotObject) { plotObject <- plotObject + ggplot2::theme( plot.background = private$.plot$createPlotElement(), @@ -124,16 +124,16 @@ BackgroundElement <- R6::R6Class( size = NULL, linetype = NULL, - #' @description Create a new \code{BackgroundElement} object + #' @description Create a new `BackgroundElement` object #' @param fill character color filling of the background element #' @param color character color of the frame of the background element #' @param size character size of the frame of the background element #' @param linetype character linetype of the frame of the background element - #' @return A new \code{BackgroundElement} object + #' @return A new `BackgroundElement` object initialize = function(fill = NULL, - color = NULL, - size = NULL, - linetype = NULL) { + color = NULL, + size = NULL, + linetype = NULL) { validateIsString(c(fill, color, linetype), nullAllowed = TRUE) validateIsNumeric(size, nullAllowed = TRUE) diff --git a/R/plotconfiguration-export.R b/R/plotconfiguration-export.R index edab568b..7a5f3ca3 100644 --- a/R/plotconfiguration-export.R +++ b/R/plotconfiguration-export.R @@ -1,5 +1,5 @@ #' @title ExportConfiguration -#' @description R6 class defining the save configuration of a \code{ggplot} object +#' @description R6 class defining the save configuration of a `ggplot` object #' @export ExportConfiguration <- R6::R6Class( "ExportConfiguration", @@ -13,16 +13,16 @@ ExportConfiguration <- R6::R6Class( #' @field units character defining the unit of the saving dimension units = NULL, - #' @description Create a new \code{ExportConfiguration} object + #' @description Create a new `ExportConfiguration` object #' @param format character defining the format of the file to be saved. #' @param width numeric values defining the width in `units` of the plot dimensions after saving #' @param height numeric values defining the height in `units` of the plot dimensions after saving #' @param units character defining the unit of the saving dimension - #' @return A new \code{ExportConfiguration} object + #' @return A new `ExportConfiguration` object initialize = function(format = tlfEnv$defaultExportParameters$format, - width = tlfEnv$defaultExportParameters$width, - height = tlfEnv$defaultExportParameters$height, - units = tlfEnv$defaultExportParameters$units) { + width = tlfEnv$defaultExportParameters$width, + height = tlfEnv$defaultExportParameters$height, + units = tlfEnv$defaultExportParameters$units) { validateIsString(c(format, units)) validateIsNumeric(c(width, height)) diff --git a/R/plotconfiguration-label.R b/R/plotconfiguration-label.R index 2387bd6e..ac663e23 100644 --- a/R/plotconfiguration-label.R +++ b/R/plotconfiguration-label.R @@ -1,19 +1,19 @@ #' @title LabelConfiguration -#' @description R6 class defining the configuration of the labels of a \code{ggplot} object +#' @description R6 class defining the configuration of the labels of a `ggplot` object #' @export LabelConfiguration <- R6::R6Class( "LabelConfiguration", public = list( - #' @description Create a new \code{LabelConfiguration} object - #' @param title character or \code{Label} object defining title - #' @param subtitle character or \code{Label} object defining subtitle - #' @param xlabel character or \code{Label} object defining xlabel - #' @param ylabel character or \code{Label} object defining ylabel - #' @return A new \code{LabelConfiguration} object + #' @description Create a new `LabelConfiguration` object + #' @param title character or `Label` object defining title + #' @param subtitle character or `Label` object defining subtitle + #' @param xlabel character or `Label` object defining xlabel + #' @param ylabel character or `Label` object defining ylabel + #' @return A new `LabelConfiguration` object initialize = function(title = NULL, - subtitle = NULL, - xlabel = NULL, - ylabel = NULL) { + subtitle = NULL, + xlabel = NULL, + ylabel = NULL) { inputs <- c("title", "subtitle", "xlabel", "ylabel") validateExpressions <- parse(text = paste0("validateIsOfType(", inputs, ', c("Label", "character"), nullAllowed =TRUE)')) eval(validateExpressions) @@ -29,9 +29,9 @@ LabelConfiguration <- R6::R6Class( eval(associateExpressions) }, - #' @description Update labels of a \code{ggplot} object and their properties - #' @param plotObject a \code{ggplot} object - #' @return A \code{ggplot} object + #' @description Update labels of a `ggplot` object and their properties + #' @param plotObject a `ggplot` object + #' @return A `ggplot` object updatePlot = function(plotObject) { validateIsOfType(plotObject, "ggplot") # Update titles and axes labels @@ -51,7 +51,7 @@ LabelConfiguration <- R6::R6Class( } ), active = list( - #' @field title \code{Label} object defining the title of the plot + #' @field title `Label` object defining the title of the plot title = function(value) { if (missing(value)) { return(private$.title) @@ -60,7 +60,7 @@ LabelConfiguration <- R6::R6Class( private$.title <- asLabel(value) return(invisible()) }, - #' @field subtitle \code{Label} object defining the subtitle of the plot + #' @field subtitle `Label` object defining the subtitle of the plot subtitle = function(value) { if (missing(value)) { return(private$.subtitle) @@ -69,7 +69,7 @@ LabelConfiguration <- R6::R6Class( private$.subtitle <- asLabel(value) return(invisible()) }, - #' @field xlabel \code{Label} object defining the xlabel of the plot + #' @field xlabel `Label` object defining the xlabel of the plot xlabel = function(value) { if (missing(value)) { return(private$.xlabel) @@ -78,7 +78,7 @@ LabelConfiguration <- R6::R6Class( private$.xlabel <- asLabel(value) return(invisible()) }, - #' @field ylabel \code{Label} object defining the ylabel of the plot + #' @field ylabel `Label` object defining the ylabel of the plot ylabel = function(value) { if (missing(value)) { return(private$.ylabel) diff --git a/R/plotconfiguration-legend.R b/R/plotconfiguration-legend.R index c2237186..e2e19f3a 100644 --- a/R/plotconfiguration-legend.R +++ b/R/plotconfiguration-legend.R @@ -1,23 +1,23 @@ #' @title LegendConfiguration -#' @description R6 class defining the legend configuration of a \code{ggplot} object +#' @description R6 class defining the legend configuration of a `ggplot` object #' @export LegendConfiguration <- R6::R6Class( "LegendConfiguration", public = list( - #' @description Create a new \code{LegendConfiguration} object + #' @description Create a new `LegendConfiguration` object #' @param position position of the legend as defined by enum `LegendPositions` #' @param caption data.frame containing the properties of the legend caption #' @param title character title of the legend caption. A value of `NULL` removes the title. - #' @param titleFont \code{Font} object defining the font of the legend title - #' @param font \code{Font} object defining the font of the legend caption - #' @param background \code{BackgroundElement} object defining the background of the legend - #' @return A new \code{LegendConfiguration} object + #' @param titleFont `Font` object defining the font of the legend title + #' @param font `Font` object defining the font of the legend caption + #' @param background `BackgroundElement` object defining the background of the legend + #' @return A new `LegendConfiguration` object initialize = function(position = NULL, - caption = NULL, - title = NULL, - titleFont = NULL, - font = NULL, - background = NULL) { + caption = NULL, + title = NULL, + titleFont = NULL, + font = NULL, + background = NULL) { validateIsIncluded(position, LegendPositions, nullAllowed = TRUE) validateIsString(title, nullAllowed = TRUE) validateIsOfType(titleFont, "Font", nullAllowed = TRUE) @@ -34,9 +34,9 @@ LegendConfiguration <- R6::R6Class( private$.caption <- caption %||% data.frame() }, - #' @description Update legend configuration on a \code{ggplot} object - #' @param plotObject \code{ggplot} object - #' @return A \code{ggplot} object with updated axis properties + #' @description Update legend configuration on a `ggplot` object + #' @param plotObject `ggplot` object + #' @return A `ggplot` object with updated axis properties updatePlot = function(plotObject) { validateIsOfType(plotObject, "ggplot") # Update legend background, font and title font @@ -81,7 +81,7 @@ LegendConfiguration <- R6::R6Class( private$.position <- value return(invisible()) }, - #' @field font \code{Font} object defining the font of the legend + #' @field font `Font` object defining the font of the legend font = function(value) { if (missing(value)) { return(private$.font) @@ -91,7 +91,7 @@ LegendConfiguration <- R6::R6Class( private$.font <- value %||% currentTheme$fonts$legend return(invisible()) }, - #' @field titleFont \code{Font} object defining the font of the legend title + #' @field titleFont `Font` object defining the font of the legend title titleFont = function(value) { if (missing(value)) { return(private$.titleFont) @@ -101,7 +101,7 @@ LegendConfiguration <- R6::R6Class( private$.titleFont <- value %||% currentTheme$fonts$legendTitle return(invisible()) }, - #' @field background \code{Background} object defining the background of the legend + #' @field background `Background` object defining the background of the legend background = function(value) { if (missing(value)) { return(private$.background) diff --git a/R/plotconfiguration.R b/R/plotconfiguration.R index da3b7cbf..8382fd53 100644 --- a/R/plotconfiguration.R +++ b/R/plotconfiguration.R @@ -1,76 +1,76 @@ #' @title PlotConfiguration -#' @description R6 class defining the configuration of a \code{ggplot} object -#' @field export R6 class \code{ExportConfiguration} defining export properties +#' @description R6 class defining the configuration of a `ggplot` object +#' @field export R6 class `ExportConfiguration` defining export properties #' @export PlotConfiguration <- R6::R6Class( "PlotConfiguration", public = list( export = NULL, - #' @description Create a new \code{PlotConfiguration} object - #' @param title character or \code{Label} object defining plot title - #' @param subtitle character or \code{Label} object defining plot subtitle - #' @param xlabel character or \code{Label} object defining plot xlabel - #' @param ylabel character or \code{Label} object defining plot ylabel - #' @param legend \code{LegendConfiguration} object defining legend properties + #' @description Create a new `PlotConfiguration` object + #' @param title character or `Label` object defining plot title + #' @param subtitle character or `Label` object defining plot subtitle + #' @param xlabel character or `Label` object defining plot xlabel + #' @param ylabel character or `Label` object defining plot ylabel + #' @param legend `LegendConfiguration` object defining legend properties #' @param legendTitle character defining legend title #' @param legendPosition character defining legend position. #' Use Enum `LegendPositions` to get a list of available to legend positions. - #' @param xAxis \code{XAxisConfiguration} object defining x-axis properties + #' @param xAxis `XAxisConfiguration` object defining x-axis properties #' @param xScale name of X-axis scale. Use enum `Scaling` to access predefined scales. #' @param xLimits numeric vector of length 2 defining x-axis limits - #' @param yAxis \code{YAxisConfiguration} object defining y-axis properties + #' @param yAxis `YAxisConfiguration` object defining y-axis properties #' @param yScale name of y-axis scale. Use enum `Scaling` to access predefined scales. #' @param yLimits numeric vector of length 2 defining y-axis limits - #' @param background \code{BackgroundConfiguration} object defining background properties - #' @param plotArea \code{BackgroundElement} object defining properties of plot area - #' @param panelArea \code{BackgroundElement} object defining properties of panel area - #' @param xGrid \code{LineElement} object defining properties of x-grid background - #' @param yGrid \code{LineElement} object defining properties of y-grid background - #' @param watermark \code{Label} object defining watermark - #' @param export R6 class \code{SaveConfiguration} defining saving properties + #' @param background `BackgroundConfiguration` object defining background properties + #' @param plotArea `BackgroundElement` object defining properties of plot area + #' @param panelArea `BackgroundElement` object defining properties of panel area + #' @param xGrid `LineElement` object defining properties of x-grid background + #' @param yGrid `LineElement` object defining properties of y-grid background + #' @param watermark `Label` object defining watermark + #' @param export R6 class `SaveConfiguration` defining saving properties #' @param format character defining the format of the file to be saved #' @param width numeric values defining the width in `units` of the plot dimensions after saving #' @param height numeric values defining the height in `units` of the plot dimensions after saving #' @param units character defining the unit of the saving dimension - #' @param data data.frame used by \code{smartMapping} - #' @param metaData list of information on \code{data} - #' @param dataMapping R6 class or subclass \code{XYDataMapping} - #' @return A new \code{PlotConfiguration} object + #' @param data data.frame used by `smartMapping` + #' @param metaData list of information on `data` + #' @param dataMapping R6 class or subclass `XYDataMapping` + #' @return A new `PlotConfiguration` object initialize = function( # Label configuration - title = NULL, - subtitle = NULL, - xlabel = NULL, - ylabel = NULL, - # Legend Configuration - legend = NULL, - legendTitle = NULL, - legendPosition = NULL, - # X-Axis configuration - xAxis = NULL, - xScale = NULL, - xLimits = NULL, - # Y-Axis configuration - yAxis = NULL, - yScale = NULL, - yLimits = NULL, - # Background configuration - background = NULL, - plotArea = NULL, - panelArea = NULL, - xGrid = NULL, - yGrid = NULL, - watermark = NULL, - # Export configuration - export = NULL, - format = NULL, - width = NULL, - height = NULL, - units = NULL, - # Smart configuration using metaData - data = NULL, - metaData = NULL, - dataMapping = NULL) { + title = NULL, + subtitle = NULL, + xlabel = NULL, + ylabel = NULL, + # Legend Configuration + legend = NULL, + legendTitle = NULL, + legendPosition = NULL, + # X-Axis configuration + xAxis = NULL, + xScale = NULL, + xLimits = NULL, + # Y-Axis configuration + yAxis = NULL, + yScale = NULL, + yLimits = NULL, + # Background configuration + background = NULL, + plotArea = NULL, + panelArea = NULL, + xGrid = NULL, + yGrid = NULL, + watermark = NULL, + # Export configuration + export = NULL, + format = NULL, + width = NULL, + height = NULL, + units = NULL, + # Smart configuration using metaData + data = NULL, + metaData = NULL, + dataMapping = NULL) { # Label configuration # validation of the input is done within the creation of the object @@ -147,7 +147,7 @@ PlotConfiguration <- R6::R6Class( } ), active = list( - #' @field labels \code{LabelConfiguration} object defining properties of labels + #' @field labels `LabelConfiguration` object defining properties of labels labels = function(value) { if (missing(value)) { return(private$.labels) @@ -156,7 +156,7 @@ PlotConfiguration <- R6::R6Class( private$.labels <- value %||% private$.labels return(invisible()) }, - #' @field legend \code{LegendConfiguration} object defining properties of legend + #' @field legend `LegendConfiguration` object defining properties of legend legend = function(value) { if (missing(value)) { return(private$.legend) @@ -165,7 +165,7 @@ PlotConfiguration <- R6::R6Class( private$.legend <- value %||% private$.legend return(invisible()) }, - #' @field xAxis \code{XAxisConfiguration} object defining properties of x-axis + #' @field xAxis `XAxisConfiguration` object defining properties of x-axis xAxis = function(value) { if (missing(value)) { return(private$.xAxis) @@ -174,7 +174,7 @@ PlotConfiguration <- R6::R6Class( private$.xAxis <- value %||% private$.xAxis return(invisible()) }, - #' @field yAxis \code{YAxisConfiguration} object defining properties of x-axis + #' @field yAxis `YAxisConfiguration` object defining properties of x-axis yAxis = function(value) { if (missing(value)) { return(private$.yAxis) @@ -183,7 +183,7 @@ PlotConfiguration <- R6::R6Class( private$.yAxis <- value %||% private$.yAxis return(invisible()) }, - #' @field background \code{BackgroundConfiguration} object defining properties of x-axis + #' @field background `BackgroundConfiguration` object defining properties of x-axis background = function(value) { if (missing(value)) { return(private$.background) diff --git a/R/themes.R b/R/themes.R index f3b04d82..b3c6b549 100644 --- a/R/themes.R +++ b/R/themes.R @@ -2,15 +2,15 @@ #' @title ThemeFont #' @description R6 class defining theme font properties -#' @field title \code{Font} object for font properties title -#' @field subtitle \code{Font} object for font properties of subtitle -#' @field xlabel \code{Font} object for font properties of xlabel -#' @field ylabel \code{Font} object for font properties of ylabel -#' @field watermark \code{Font} object for font properties of watermark -#' @field legendTitle \code{Font} object for font properties of legend title -#' @field legend \code{Font} object for font properties of legend -#' @field xAxis \code{Font} object for font properties of xAxis -#' @field yAxis \code{Font} object for font properties of yAxis +#' @field title `Font` object for font properties title +#' @field subtitle `Font` object for font properties of subtitle +#' @field xlabel `Font` object for font properties of xlabel +#' @field ylabel `Font` object for font properties of ylabel +#' @field watermark `Font` object for font properties of watermark +#' @field legendTitle `Font` object for font properties of legend title +#' @field legend `Font` object for font properties of legend +#' @field xAxis `Font` object for font properties of xAxis +#' @field yAxis `Font` object for font properties of yAxis #' @export ThemeFont <- R6::R6Class( "ThemeFont", @@ -25,36 +25,36 @@ ThemeFont <- R6::R6Class( xAxis = NULL, yAxis = NULL, - #' @description Create a new \code{ThemeFont} object - #' @param title \code{Font} object or list for font properties title - #' @param subtitle \code{Font} object or list for font properties of subtitle - #' @param xlabel \code{Font} object or list for font properties of xlabel - #' @param ylabel \code{Font} object or list for font properties of ylabel - #' @param watermark \code{Font} object or list for font properties of watermark - #' @param legendTitle \code{Font} object or list for font properties of legend - #' @param legend \code{Font} object or list for font properties of legend - #' @param xAxis \code{Font} object or list for font properties of xAxis - #' @param yAxis \code{Font} object or list for font properties of yAxis + #' @description Create a new `ThemeFont` object + #' @param title `Font` object or list for font properties title + #' @param subtitle `Font` object or list for font properties of subtitle + #' @param xlabel `Font` object or list for font properties of xlabel + #' @param ylabel `Font` object or list for font properties of ylabel + #' @param watermark `Font` object or list for font properties of watermark + #' @param legendTitle `Font` object or list for font properties of legend + #' @param legend `Font` object or list for font properties of legend + #' @param xAxis `Font` object or list for font properties of xAxis + #' @param yAxis `Font` object or list for font properties of yAxis #' @param baseColor name of base color of undefined fonts. Default is black. #' @param baseSize base size of undefined fonts. Default is 12. #' @param baseFace name of base face of undefined fonts. Default is "plain". #' @param baseFamily name of base family of undefined fonts. Default is "". #' @param baseAngle base angle of undefined fonts. Default is 0 degree. - #' @return A new \code{ThemeFont} object + #' @return A new `ThemeFont` object initialize = function(title = NULL, - subtitle = NULL, - xlabel = NULL, - ylabel = NULL, - watermark = NULL, - legendTitle = NULL, - legend = NULL, - xAxis = NULL, - yAxis = NULL, - baseColor = "black", - baseSize = 12, - baseFace = "plain", - baseFamily = "", - baseAngle = 0) { + subtitle = NULL, + xlabel = NULL, + ylabel = NULL, + watermark = NULL, + legendTitle = NULL, + legend = NULL, + xAxis = NULL, + yAxis = NULL, + baseColor = "black", + baseSize = 12, + baseFace = "plain", + baseFamily = "", + baseAngle = 0) { # Validate necessary input validateIsString(baseColor) validateIsString(baseFace) @@ -65,10 +65,10 @@ ThemeFont <- R6::R6Class( # Create all field properties by parsing and evaluating their expression fieldNames <- c("title", "subtitle", "xlabel", "ylabel", "watermark", "legendTitle", "legend", "xAxis", "yAxis") setFontExpression <- parse(text = paste0("self$", fieldNames, " <- Font$new( - color = ", fieldNames, "$color %||% baseColor, - size = ", fieldNames, "$size %||% baseSize, - fontFace = ", fieldNames, "$fontFace %||% baseFace, - fontFamily = ", fieldNames, "$fontFamily %||% baseFamily, + color = ", fieldNames, "$color %||% baseColor, + size = ", fieldNames, "$size %||% baseSize, + fontFace = ", fieldNames, "$fontFace %||% baseFace, + fontFamily = ", fieldNames, "$fontFamily %||% baseFamily, angle = ", fieldNames, "$angle %||% baseAngle)")) eval(setFontExpression) }, @@ -79,10 +79,10 @@ ThemeFont <- R6::R6Class( jsonObject <- list() fieldNames <- c("title", "subtitle", "xlabel", "ylabel", "watermark", "legendTitle", "legend", "xAxis", "yAxis") setJsonExpression <- parse(text = paste0("jsonObject$", fieldNames, " <- list( - color = self$", fieldNames, "$color, - size = self$", fieldNames, "$size, - angle = self$", fieldNames, "$angle, - fontFace = self$", fieldNames, "$fontFace, + color = self$", fieldNames, "$color, + size = self$", fieldNames, "$size, + angle = self$", fieldNames, "$angle, + fontFace = self$", fieldNames, "$fontFace, fontFamily = self$", fieldNames, "$fontFamily)")) eval(setJsonExpression) return(jsonObject) @@ -94,13 +94,13 @@ ThemeFont <- R6::R6Class( #' @description R6 class defining theme background properties #' @field watermark character defining content of watermark #' @field legendPosition character defining where legend should usually be placed -#' @field plot \code{BackgroundElement} object for plot area properties (outside of panel) -#' @field panel \code{BackgroundElement} object for plot area properties (inside of panel) -#' @field xAxis \code{BackgroundElement} object for x axis properties -#' @field yAxis \code{BackgroundElement} object for y axis properties -#' @field xGrid \code{BackgroundElement} object for x grid properties -#' @field yGrid \code{BackgroundElement} object for y grid properties -#' @field legend \code{BackgroundElement} object for legend area properties +#' @field plot `BackgroundElement` object for plot area properties (outside of panel) +#' @field panel `BackgroundElement` object for plot area properties (inside of panel) +#' @field xAxis `BackgroundElement` object for x axis properties +#' @field yAxis `BackgroundElement` object for y axis properties +#' @field xGrid `BackgroundElement` object for x grid properties +#' @field yGrid `BackgroundElement` object for y grid properties +#' @field legend `BackgroundElement` object for legend area properties #' @export ThemeBackground <- R6::R6Class( "ThemeBackground", @@ -115,34 +115,34 @@ ThemeBackground <- R6::R6Class( yGrid = NULL, legend = NULL, - #' @description Create a new \code{ThemeBackground} object + #' @description Create a new `ThemeBackground` object #' @param watermark character defining content of watermark #' @param legendPosition character defining where legend should usually be placed - #' @param plot \code{BackgroundElement} object or list for plot area properties (outside of panel) - #' @param panel \code{BackgroundElement} object or list for plot area properties (inside of panel) - #' @param xAxis \code{BackgroundElement} object or list for x axis properties - #' @param yAxis \code{BackgroundElement} object or list for y axis properties - #' @param xGrid \code{BackgroundElement} object or list for x grid properties - #' @param yGrid \code{BackgroundElement} object or list for y grid properties - #' @param legend \code{BackgroundElement} object or list for legend area properties + #' @param plot `BackgroundElement` object or list for plot area properties (outside of panel) + #' @param panel `BackgroundElement` object or list for plot area properties (inside of panel) + #' @param xAxis `BackgroundElement` object or list for x axis properties + #' @param yAxis `BackgroundElement` object or list for y axis properties + #' @param xGrid `BackgroundElement` object or list for x grid properties + #' @param yGrid `BackgroundElement` object or list for y grid properties + #' @param legend `BackgroundElement` object or list for legend area properties #' @param baseFill name of base color fill of undefined background elements. Default is white. #' @param baseColor name of base color of undefined background elements. Default is black. #' @param baseSize name of base size of undefined background elements. Default is 0.5. #' @param baseLinetype name of base size of undefined background elements. Default is "solid". - #' @return A new \code{ThemeFont} object + #' @return A new `ThemeFont` object initialize = function(watermark = NULL, - legendPosition = NULL, - plot = NULL, - panel = NULL, - xAxis = NULL, - yAxis = NULL, - xGrid = NULL, - yGrid = NULL, - legend = NULL, - baseFill = "white", - baseColor = "black", - baseSize = 0.5, - baseLinetype = "solid") { + legendPosition = NULL, + plot = NULL, + panel = NULL, + xAxis = NULL, + yAxis = NULL, + xGrid = NULL, + yGrid = NULL, + legend = NULL, + baseFill = "white", + baseColor = "black", + baseSize = 0.5, + baseLinetype = "solid") { # Validate necessary input validateIsString(baseFill) validateIsString(baseColor) @@ -172,13 +172,13 @@ ThemeBackground <- R6::R6Class( lineFieldNames <- c("xAxis", "yAxis", "xGrid", "yGrid") setJsonAreaExpression <- parse(text = paste0("jsonObject$", areaFieldNames, " <- list( - fill = self$", areaFieldNames, "$fill, - color = self$", areaFieldNames, "$color, - size = self$", areaFieldNames, "$size, + fill = self$", areaFieldNames, "$fill, + color = self$", areaFieldNames, "$color, + size = self$", areaFieldNames, "$size, linetype = self$", areaFieldNames, "$linetype)")) setJsonLineExpression <- parse(text = paste0("jsonObject$", lineFieldNames, " <- list( - color = self$", lineFieldNames, "$color, - size = self$", lineFieldNames, "$size, + color = self$", lineFieldNames, "$color, + size = self$", lineFieldNames, "$size, linetype = self$", lineFieldNames, "$linetype)")) eval(setJsonAreaExpression) eval(setJsonLineExpression) @@ -206,20 +206,20 @@ ThemeAestheticMaps <- R6::R6Class( linetype = NULL, alpha = NULL, - #' @description Create a new \code{ThemeAestheticMaps} object + #' @description Create a new `ThemeAestheticMaps` object #' @param color color map as list, character or numeric vector #' @param fill fill map as list, character or numeric vector #' @param shape shape map as list, character or numeric vector #' @param size size map as list, character or numeric vector #' @param linetype linetype map as list, character or numeric vector #' @param alpha alpha map as list, character or numeric vector - #' @return A new \code{ThemeAestheticMaps} object + #' @return A new `ThemeAestheticMaps` object initialize = function(color = NULL, - fill = NULL, - shape = NULL, - size = NULL, - linetype = NULL, - alpha = NULL) { + fill = NULL, + shape = NULL, + size = NULL, + linetype = NULL, + alpha = NULL) { # Validate necessary input validateIsString(color, nullAllowed = TRUE) @@ -265,20 +265,20 @@ ThemeAestheticSelections <- R6::R6Class( inherit = ThemeAestheticMaps, public = list( - #' @description Create a new \code{ThemeAestheticSelections} object + #' @description Create a new `ThemeAestheticSelections` object #' @param color selection key or values for choice of color #' @param fill selection key or values for choice of fill #' @param shape selection key or values for choice of shape #' @param size selection key or values for choice of size #' @param linetype selection key or values for choice of linetype #' @param alpha selection key or values for choice of alpha - #' @return A new \code{ThemeAestheticSelections} object + #' @return A new `ThemeAestheticSelections` object initialize = function(color = NULL, - fill = NULL, - shape = NULL, - size = NULL, - linetype = NULL, - alpha = NULL) { + fill = NULL, + shape = NULL, + size = NULL, + linetype = NULL, + alpha = NULL) { # Associate to each field its value initializeExpression <- parse(text = paste0("self$", names(AestheticProperties), " <- ", names(AestheticProperties), " %||% 'first'")) @@ -327,7 +327,7 @@ ThemePlotConfigurations <- R6::R6Class( plotTornado = NULL, plotHistogram = NULL, - #' @description Create a new \code{ThemePlotConfigurations} object + #' @description Create a new `ThemePlotConfigurations` object #' @param addScatter theme properties for `PlotConfiguration` objects as used in function `addScatter()` #' @param addLine theme properties for `PlotConfiguration` objects as used in function `addLine()` #' @param addRibbon theme properties for `PlotConfiguration` objects as used in function `addRibbon()` @@ -339,18 +339,18 @@ ThemePlotConfigurations <- R6::R6Class( #' @param plotBoxWhisker theme properties for `PlotConfiguration` objects as used in function `plotBoxWhisker()` #' @param plotTornado theme properties for `PlotConfiguration` objects as used in function `plotTornado()` #' @param plotHistogram theme properties for `PlotConfiguration` objects as used in function `plotHistogram()` - #' @return A new \code{ThemePlotConfigurations} object + #' @return A new `ThemePlotConfigurations` object initialize = function(addScatter = NULL, - addLine = NULL, - addRibbon = NULL, - addErrorbar = NULL, - plotPKRatio = NULL, - plotDDIRatio = NULL, - plotTimeProfile = NULL, - plotObsVsPred = NULL, - plotBoxWhisker = NULL, - plotTornado = NULL, - plotHistogram = NULL) { + addLine = NULL, + addRibbon = NULL, + addErrorbar = NULL, + plotPKRatio = NULL, + plotDDIRatio = NULL, + plotTimeProfile = NULL, + plotObsVsPred = NULL, + plotBoxWhisker = NULL, + plotTornado = NULL, + plotHistogram = NULL) { # Validate necessary input atomPlotInputs <- c("addScatter", "addLine", "addRibbon", "addErrorbar") @@ -424,16 +424,16 @@ Theme <- R6::R6Class( "Theme", public = list( - #' @description Create a new \code{Theme} object + #' @description Create a new `Theme` object #' @param fonts `ThemeFont` object #' @param background `ThemeBackground` object #' @param aestheticMaps `ThemeAestheticMaps` object #' @param plotConfigurations `ThemePlotConfiguration` object - #' @return A new \code{Theme} object + #' @return A new `Theme` object initialize = function(fonts = NULL, - background = NULL, - aestheticMaps = NULL, - plotConfigurations = NULL) { + background = NULL, + aestheticMaps = NULL, + plotConfigurations = NULL) { validateIsOfType(fonts, "ThemeFont", nullAllowed = TRUE) validateIsOfType(background, "ThemeBackground", nullAllowed = TRUE) validateIsOfType(aestheticMaps, "ThemeAestheticMaps", nullAllowed = TRUE) @@ -507,7 +507,7 @@ Theme <- R6::R6Class( #' @description Load theme object from json file. #' A template of a json theme is available at system.file(package= "tlf", "theme-maker","theme-template.json") #' @param jsonFile path of json file -#' @return A \code{Theme} object +#' @return A `Theme` object #' @export #' @import jsonlite loadThemeFromJson <- function(jsonFile) { diff --git a/R/timeprofile-datamapping.R b/R/timeprofile-datamapping.R index b9d173ca..7212fb9c 100644 --- a/R/timeprofile-datamapping.R +++ b/R/timeprofile-datamapping.R @@ -1,34 +1,34 @@ #' @title TimeProfileDataMapping -#' @description R6 class defining the configuration of a \code{ggplot} object for time profile plot +#' @description R6 class defining the configuration of a `ggplot` object for time profile plot #' @export TimeProfileDataMapping <- R6::R6Class( "TimeProfileDataMapping", inherit = RangeDataMapping, public = list( - #' @description Create a new \code{TimeProfileDataMapping} object + #' @description Create a new `TimeProfileDataMapping` object #' @param x Name of x variable to map #' @param y Name of y variable to map #' @param ymin Name of ymin variable to map #' @param ymax Name of ymax variable to map - #' @param groupMapping R6 class \code{GroupMapping} object - #' @param color R6 class \code{Grouping} object or its input - #' @param fill R6 class \code{Grouping} object or its input - #' @param linetype R6 class \code{Grouping} object or its input - #' @param shape R6 class \code{Grouping} object or its input - #' @param size R6 class \code{Grouping} object or its input - #' @param data data.frame to map used by \code{smartMapping} - #' @return A new \code{RangeDataMapping} object + #' @param groupMapping R6 class `GroupMapping` object + #' @param color R6 class `Grouping` object or its input + #' @param fill R6 class `Grouping` object or its input + #' @param linetype R6 class `Grouping` object or its input + #' @param shape R6 class `Grouping` object or its input + #' @param size R6 class `Grouping` object or its input + #' @param data data.frame to map used by `smartMapping` + #' @return A new `RangeDataMapping` object initialize = function(x = NULL, - y = NULL, - ymin = NULL, - ymax = NULL, - groupMapping = NULL, - color = NULL, - fill = NULL, - linetype = NULL, - shape = NULL, - size = NULL, - data = NULL) { + y = NULL, + ymin = NULL, + ymax = NULL, + groupMapping = NULL, + color = NULL, + fill = NULL, + linetype = NULL, + shape = NULL, + size = NULL, + data = NULL) { # smartMapping is available in utilities-mapping.R smartMap <- smartMapping(data) @@ -43,11 +43,11 @@ TimeProfileDataMapping <- R6::R6Class( # super$initialize introduce a self$y which is NULL self$y <- y %||% smartMap$y }, - #' @description Check that \code{data} variables include map variables + #' @description Check that `data` variables include map variables #' @param data data.frame to check - #' @param metaData list containing information on \code{data} - #' @return A data.frame with map and \code{legendLabels} variables. - #' Dummy variable \code{legendLabels} is necessary to allow further modification of plots. + #' @param metaData list containing information on `data` + #' @return A data.frame with map and `legendLabels` variables. + #' Dummy variable `legendLabels` is necessary to allow further modification of plots. checkMapData = function(data, metaData = NULL) { validateIsOfType(data, "data.frame") validateMapping(self$y, data, nullAllowed = TRUE) diff --git a/R/timeprofile-helper.R b/R/timeprofile-helper.R index a4f1a3cb..6595c2e2 100644 --- a/R/timeprofile-helper.R +++ b/R/timeprofile-helper.R @@ -9,11 +9,11 @@ TimeProfileHelper <- R6::R6Class( aggregationFunctionNames = NULL, dfHelper = NULL, initialize = function(data, - timeColumnName, - groupingColumnNames = NULL, - valuesColumnNames = NULL, - aggregationFunctionsVector = NULL, - aggregationFunctionNames = NULL) { + timeColumnName, + groupingColumnNames = NULL, + valuesColumnNames = NULL, + aggregationFunctionsVector = NULL, + aggregationFunctionNames = NULL) { self$data <- data self$timeColumnName <- timeColumnName self$groupingColumnNames <- groupingColumnNames @@ -22,7 +22,6 @@ TimeProfileHelper <- R6::R6Class( self$aggregationFunctionNames <- aggregationFunctionNames self$generateAggregatedValues() }, - applyAggregationFunctions = function(x) { # input the vector of aggregated x into each aggregation function y and return the results in a vector res res <- sapply(self$aggregationFunctionsVector, function(y) { @@ -30,13 +29,12 @@ TimeProfileHelper <- R6::R6Class( }) return(res) }, - generateAggregatedValues = function() { xGroupingColNames <- c(self$timeColumnName, self$groupingColumnNames) # Get names of grouping columns and groups then into a vector xGroupingColNames xGroupingCols <- lapply(xGroupingColNames, function(x) { self$data[[x]] }) # Extract grouping columns from dataframe and group them into a list called xGroupingCols - yValuesCol <- self$data[ self$valuesColumnNames ] # Extract column of values from dataframe + yValuesCol <- self$data[self$valuesColumnNames] # Extract column of values from dataframe dfHelper <- aggregate(yValuesCol, xGroupingCols, function(x) { res <- self$applyAggregationFunctions(x) return(res) diff --git a/R/timeprofile-plotconfiguration.R b/R/timeprofile-plotconfiguration.R index fd4e95a8..45513cf6 100644 --- a/R/timeprofile-plotconfiguration.R +++ b/R/timeprofile-plotconfiguration.R @@ -1,23 +1,22 @@ #' @title TimeProfilePlotConfiguration -#' @description R6 class defining the configuration of a \code{ggplot} object for time profile plots +#' @description R6 class defining the configuration of a `ggplot` object for time profile plots #' @export TimeProfilePlotConfiguration <- R6::R6Class( "TimeProfilePlotConfiguration", inherit = PlotConfiguration, - public = list( - #' @description Create a new \code{TimeProfilePlotConfiguration} object + #' @description Create a new `TimeProfilePlotConfiguration` object #' @param lines `ThemeAestheticSelections` defining properties of lines #' @param ribbons `ThemeAestheticSelections` defining properties of ribbons #' @param points `ThemeAestheticSelections` defining properties of points #' @param errorbars `ThemeAestheticSelections` defining properties of error bars - #' @param ... parameters inherited from \code{PlotConfiguration} - #' @return A new \code{TimeProfilePlotConfiguration} object + #' @param ... parameters inherited from `PlotConfiguration` + #' @return A new `TimeProfilePlotConfiguration` object initialize = function(lines = NULL, - ribbons = NULL, - points = NULL, - errorbars = NULL, - ...) { + ribbons = NULL, + points = NULL, + errorbars = NULL, + ...) { super$initialize(...) validateIsOfType(lines, "ThemeAestheticSelections", nullAllowed = TRUE) validateIsOfType(ribbons, "ThemeAestheticSelections", nullAllowed = TRUE) diff --git a/R/tornado-datamapping.R b/R/tornado-datamapping.R index 87354333..00d97276 100644 --- a/R/tornado-datamapping.R +++ b/R/tornado-datamapping.R @@ -1,5 +1,5 @@ #' @title TornadoDataMapping -#' @description R6 class for mapping \code{values}, \code{labels} to \code{data} +#' @description R6 class for mapping `values`, `labels` to `data` #' @export TornadoDataMapping <- R6::R6Class( "TornadoDataMapping", @@ -10,18 +10,18 @@ TornadoDataMapping <- R6::R6Class( #' @field sorted logical indicating if values should be sorted sorted = NULL, - #' @description Create a new \code{TornadoDataMapping} object + #' @description Create a new `TornadoDataMapping` object #' @param lines numeric vector of limits to plot #' @param sorted logical indicating if values should be sorted #' @param x Variable including the values of tornado plot #' @param y Variable including the labels of tornado plot - #' @param ... parameters inherited from \code{XYGDataMapping} - #' @return A new \code{TornadoDataMapping} object + #' @param ... parameters inherited from `XYGDataMapping` + #' @return A new `TornadoDataMapping` object initialize = function(lines = DefaultDataMappingValues$tornado, - sorted = NULL, - x = NULL, - y = NULL, - ...) { + sorted = NULL, + x = NULL, + y = NULL, + ...) { validateIsNumeric(lines, nullAllowed = TRUE) validateIsLogical(sorted, nullAllowed = TRUE) super$initialize(x = x, y = y, ...) @@ -48,11 +48,11 @@ TornadoDataMapping <- R6::R6Class( self$sorted <- sorted %||% TRUE }, - #' @description Check that \code{data} variables include map variables + #' @description Check that `data` variables include map variables #' @param data data.frame to check - #' @param metaData list containing information on \code{data} - #' @return A data.frame with map and \code{defaultAes} variables. - #' Dummy variable \code{defaultAes} is necessary to allow further modification of plots. + #' @param metaData list containing information on `data` + #' @return A data.frame with map and `defaultAes` variables. + #' Dummy variable `defaultAes` is necessary to allow further modification of plots. checkMapData = function(data, metaData = NULL) { mapData <- super$checkMapData(data, metaData) # Enforce y to be a discrete variable preventing crashes from numerical values diff --git a/R/tornado-plotconfiguration.R b/R/tornado-plotconfiguration.R index cbebdcec..be53d3d3 100644 --- a/R/tornado-plotconfiguration.R +++ b/R/tornado-plotconfiguration.R @@ -1,5 +1,5 @@ #' @title TornadoPlotConfiguration -#' @description R6 class defining the configuration of a \code{ggplot} object for tornado plots +#' @description R6 class defining the configuration of a `ggplot` object for tornado plots #' @export TornadoPlotConfiguration <- R6::R6Class( "TornadoPlotConfiguration", @@ -13,22 +13,22 @@ TornadoPlotConfiguration <- R6::R6Class( dodge = NULL, - #' @description Create a new \code{TornadoPlotConfiguration} object + #' @description Create a new `TornadoPlotConfiguration` object #' @param bar logical setting if tornado is uses a bar plot instead of regular points #' @param colorPalette color palette property from `ggplot2` #' @param dodge space between the bars/points #' @param lines `ThemeAestheticSelections` object defining properties for Tornado vertical lines #' @param points `ThemeAestheticSelections` object defining properties for scatter points #' @param ribbons `ThemeAestheticSelections` object defining properties for bars - #' @param ... parameters inherited from \code{PlotConfiguration} - #' @return A new \code{TornadoPlotConfiguration} object + #' @param ... parameters inherited from `PlotConfiguration` + #' @return A new `TornadoPlotConfiguration` object initialize = function(bar = TRUE, - colorPalette = NULL, - dodge = 0.5, - lines = NULL, - points = NULL, - ribbons = NULL, - ...) { + colorPalette = NULL, + dodge = 0.5, + lines = NULL, + points = NULL, + ribbons = NULL, + ...) { validateIsLogical(bar) validateIsString(colorPalette, nullAllowed = TRUE) validateIsNumeric(dodge) diff --git a/R/utilities-background.R b/R/utilities-background.R index b471f0ea..06ab0b2d 100644 --- a/R/utilities-background.R +++ b/R/utilities-background.R @@ -192,10 +192,10 @@ setBackgroundPlotArea <- function(plotObject, #' @param angle Angle of the watermark label (in degree). #' @param alpha Transparency of the watermark label. #' Alpha is a numeric between 0 and 1: 0 label is totally transparent, 1 label is totally opaque. -#' @return \code{plotObject} ggplot object to which the watermark is added. +#' @return `plotObject` ggplot object to which the watermark is added. #' @description #' addWatermark creates a ggplot grob based on the label text and its font properties. -#' Then, adds the grob to the ggplot object input \code{plotObject} as a new layer using \code{ggplot2::annotation_custom}. +#' Then, adds the grob to the ggplot object input `plotObject` as a new layer using `ggplot2::annotation_custom`. #' @import ggplot2 #' @export #' @examples @@ -334,14 +334,15 @@ createWatermarkGrob <- function(label, alpha = NULL) { ) # Font size is in .pt within annonate and requires a conversion - watermark <- ggplot2::ggplot() + ggplot2::theme_void() + + watermark <- ggplot2::ggplot() + + ggplot2::theme_void() + ggplot2::annotate( geom = "text", x = 0, y = 0, label = label$text %||% "", - color = label$font$color, - fontface = label$font$fontFace, + color = label$font$color, + fontface = label$font$fontFace, size = label$font$size / ggplot2::.pt, angle = label$font$angle, alpha = alpha ) diff --git a/R/utilities-export.R b/R/utilities-export.R index ee718ef7..2581063d 100644 --- a/R/utilities-export.R +++ b/R/utilities-export.R @@ -186,7 +186,7 @@ exportPlotConfigurationCode <- function(plotConfiguration) { as.character(parseValueToObject(legendText, legendValue)) ) } - + classSpecificCode <- NULL if (plotConfigurationClass %in% "BoxWhiskerPlotConfiguration") { classSpecificCode <- c( diff --git a/R/utilities-legend.R b/R/utilities-legend.R index fc0cd562..3e0cceb6 100644 --- a/R/utilities-legend.R +++ b/R/utilities-legend.R @@ -5,7 +5,7 @@ #' @param title character or `Label` object #' @param font `Font` object defining legend font #' @param caption data.frame containing the caption properties of the legend -#' @return A \code{ggplot} object +#' @return A `ggplot` object #' @description #' Set legend position, title, font and/or caption #' @export @@ -107,10 +107,10 @@ setLegendTitle <- function(plotObject, } #' @title setLegendPosition -#' @param plotObject \code{ggplot} graphical object +#' @param plotObject `ggplot` graphical object #' @param position legend position. #' Use enum `LegendPositions` to access the list of legend positions. -#' @return A \code{ggplot} graphical object +#' @return A `ggplot` graphical object #' @description #' Set the legend position #' @export @@ -131,9 +131,9 @@ setLegendPosition <- function(plotObject, } #' @title setLegendCaption -#' @param plotObject \code{ggplot} graphical object +#' @param plotObject `ggplot` graphical object #' @param caption data.frame containing the caption properties of the legend -#' @return A \code{ggplot} graphical object +#' @return A `ggplot` graphical object #' @description #' Set the legend caption #' @export @@ -190,7 +190,7 @@ setLegendCaption <- function(plotObject, caption = NULL) { } #' @title getLegendCaption -#' @param plotObject \code{ggplot} graphical object +#' @param plotObject `ggplot` graphical object #' @return A data.frame corresponding to legend caption #' @description #' Get the legend caption @@ -208,10 +208,10 @@ getLegendCaption <- function(plotObject) { } #' @title setCaptionLabel -#' @param plotObject \code{ggplot} graphical object +#' @param plotObject `ggplot` graphical object #' @param label new labels of the legend caption #' @param name reference names in caption$name identifying the legend caption lines -#' @return A \code{ggplot} graphical object +#' @return A `ggplot` graphical object #' @description #' Set the legend caption labels #' @export @@ -229,10 +229,10 @@ setCaptionLabels <- function(plotObject, label, name = NULL) { } #' @title setCaptionVisibility -#' @param plotObject \code{ggplot} graphical object +#' @param plotObject `ggplot` graphical object #' @param visibility logical visibility of the legend caption labels #' @param name reference names in caption$name identifying the legend caption lines -#' @return A \code{ggplot} graphical object +#' @return A `ggplot` graphical object #' @description #' Set the visibility of the legend caption labels #' @export @@ -250,10 +250,10 @@ setCaptionVisibility <- function(plotObject, visibility, name = NULL) { } #' @title setCaptionOrder -#' @param plotObject \code{ggplot} graphical object +#' @param plotObject `ggplot` graphical object #' @param order numeric order of the legend ccaption labels #' @param name reference names in caption$name identifying the legend caption lines -#' @return A \code{ggplot} graphical object +#' @return A `ggplot` graphical object #' @description #' Set the order of the legend caption labels #' @export @@ -271,10 +271,10 @@ setCaptionOrder <- function(plotObject, order, name = NULL) { } #' @title setCaptionColor -#' @param plotObject \code{ggplot} graphical object +#' @param plotObject `ggplot` graphical object #' @param color colors of the data in plot and legend caption #' @param name reference names in caption$name identifying the legend caption lines -#' @return A \code{ggplot} graphical object +#' @return A `ggplot` graphical object #' @description #' Set the colors of the data in plot and legend caption #' @export @@ -292,10 +292,10 @@ setCaptionColor <- function(plotObject, color, name = NULL) { } #' @title setCaptionShape -#' @param plotObject \code{ggplot} graphical object +#' @param plotObject `ggplot` graphical object #' @param shape shapes of the data in plot and legend caption #' @param name reference names in caption$name identifying the legend caption lines -#' @return A \code{ggplot} graphical object +#' @return A `ggplot` graphical object #' @description #' Set the shapes of the data in plot and legend caption #' @export @@ -313,10 +313,10 @@ setCaptionShape <- function(plotObject, shape, name = NULL) { } #' @title setCaptionSize -#' @param plotObject \code{ggplot} graphical object +#' @param plotObject `ggplot` graphical object #' @param size sizes of the data in plot and legend caption #' @param name reference names in caption$name identifying the legend caption lines -#' @return A \code{ggplot} graphical object +#' @return A `ggplot` graphical object #' @description #' Set the sizes of the data in plot and legend caption #' @export @@ -334,10 +334,10 @@ setCaptionSize <- function(plotObject, size, name = NULL) { } #' @title setCaptionLinetype -#' @param plotObject \code{ggplot} graphical object +#' @param plotObject `ggplot` graphical object #' @param linetype linetypes of the data in plot and legend caption #' @param name reference names in caption$name identifying the legend caption lines -#' @return A \code{ggplot} graphical object +#' @return A `ggplot` graphical object #' @description #' Set the linetypes of the data in plot and legend caption #' @export @@ -355,10 +355,10 @@ setCaptionLinetype <- function(plotObject, linetype, name = NULL) { } #' @title setCaptionFill -#' @param plotObject \code{ggplot} graphical object +#' @param plotObject `ggplot` graphical object #' @param fill fills of the data in plot and legend caption #' @param name reference names in caption$name identifying the legend caption lines -#' @return A \code{ggplot} graphical object +#' @return A `ggplot` graphical object #' @description #' Set the fills of the data in plot and legend caption #' @export @@ -445,9 +445,9 @@ mergeLegend <- function(plotObject, newLabels, aestheticSelections) { # Associate new values of aesthetics based on theme aesthetic selections newCaptionExpression <- parse(text = paste0( - names(AestheticProperties), " <- getAestheticValues(n = newCaptionLength, - selectionKey = aestheticSelections$", names(AestheticProperties), ", - position = oldCaptionLength, + names(AestheticProperties), " <- getAestheticValues(n = newCaptionLength, + selectionKey = aestheticSelections$", names(AestheticProperties), ", + position = oldCaptionLength, aesthetic = '", names(AestheticProperties), "')" )) eval(newCaptionExpression) diff --git a/R/utilities-mapping.R b/R/utilities-mapping.R index 83743f94..02992249 100644 --- a/R/utilities-mapping.R +++ b/R/utilities-mapping.R @@ -14,14 +14,16 @@ binNumericCol <- function(binLimits, currentDataCol) { # function to iterate thr if (!(binLimits[2] > binLimits[1])) { # check that bin limits are in increasing order stop("Bin limits must be increasing.") } - dataPointsInGrp <- sapply(currentDataCol, function(x) return((x >= binLimits[1]) & (x <= binLimits[2]))) + dataPointsInGrp <- sapply(currentDataCol, function(x) { + return((x >= binLimits[1]) & (x <= binLimits[2])) + }) return(dataPointsInGrp) } findColumnEntriesInGroups <- function(dataDf, groupingDfRow) { - groupingDataColumns <- dataDf[ colnames(groupingDfRow) ] # get columns from dataDf corresponding to column headings in groupingDf (excluding the last column heading in groupingDf) + groupingDataColumns <- dataDf[colnames(groupingDfRow)] # get columns from dataDf corresponding to column headings in groupingDf (excluding the last column heading in groupingDf) logicMatrix <- matrix(rep(FALSE, nrow(dataDf) * ncol(groupingDfRow)), nrow(dataDf)) for (n in seq(1, ncol(groupingDfRow))) { # for each column of the groupingDf if (is.list(groupingDfRow[[n]])) { # case where a list is supplied for binning @@ -53,18 +55,18 @@ getCustomCaptions <- function(dataDf, groupingDf) { } newCol <- as.factor(rep(NA, nrow(dataDf))) # add a factor column of NA to the dataframe dataDF. For rows falling within the grouping, the NA will be modified to that grouping's caption. levels(newCol) <- groupingDf[[ncol(groupingDf)]] # Set factor levels of new column to be the captions of the grouping dataframe - newCol[ groupingFactorColumn != 0 ] <- groupingDf[[ncol(groupingDf)]][ groupingFactorColumn[groupingFactorColumn != 0 ] ] # Add the appropriate caption to each column entry that correspondinds to a dataDf row that falls within groupings in groupingDf + newCol[groupingFactorColumn != 0] <- groupingDf[[ncol(groupingDf)]][groupingFactorColumn[groupingFactorColumn != 0]] # Add the appropriate caption to each column entry that correspondinds to a dataDf row that falls within groupings in groupingDf return(newCol) } #' @title getDefaultCaptions #' @param data data.frame used for legend caption -#' @param metaData list of lists containing metaData on \code{data} +#' @param metaData list of lists containing metaData on `data` #' @param variableList ordered vector of variables used for specifying the caption #' @param sep characters separating variables in caption #' @description #' Creates default legend captions by concatenating the values of -#' the \code{data} and \code{metaData} of \code{variableList} variables from \code{data}. +#' the `data` and `metaData` of `variableList` variables from `data`. #' @return Factor levels corresponding to the legend captions #' @export #' @examples @@ -131,14 +133,14 @@ asLegendCaptionSubset <- function(data, metaData) { #' @title getAesStringMapping #' @param dataMapping DataMapping class or subclass object #' @description -#' Get the \code{dataMapping} elements and convert them into -#' character string usable by ggplot mapping function \code{aes_string}. -#' The conversion fixes any issue of special characters by wrapping the string by \code{``} +#' Get the `dataMapping` elements and convert them into +#' character string usable by ggplot mapping function `aes_string`. +#' The conversion fixes any issue of special characters by wrapping the string by ```` #' if not already used. #' -#' \code{dataMapping} unmapped aesthetic elements (e.g. \code{color}) are associated to -#' the dummy aesthetic variable \code{"defaultAes"} which allows further modification of the plot aesthetics. -#' @return A list of mappings that can be used as is by \code{aes_string}. +#' `dataMapping` unmapped aesthetic elements (e.g. `color`) are associated to +#' the dummy aesthetic variable `"defaultAes"` which allows further modification of the plot aesthetics. +#' @return A list of mappings that can be used as is by `aes_string`. #' @examples #' \dontrun{ #' dataMapping <- XYGDataMapping$new(x = "Time [h]", y = "Concentration [mol/L]", color = "Dose") @@ -182,12 +184,12 @@ getAesStringMapping <- function(dataMapping) { #' Get the mapping if variable names correspond to usual aesthetic or mapping names. #' Else return NULL for the mapping property. #' -#' If data has only one variable, it will be mapped as \code{x}. -#' If data has only 2 variables, they will be respectively mapped as \code{x} and \code{y}. +#' If data has only one variable, it will be mapped as `x`. +#' If data has only 2 variables, they will be respectively mapped as `x` and `y`. #' -#' Recognized names for the mapping are \code{x}, \code{y}, \code{ymin}, \code{ymax}, -#' \code{lower}, \code{middle}, \code{upper}, \code{color}, \code{shape}, \code{linetype}, -#' \code{size} and \code{fill} +#' Recognized names for the mapping are `x`, `y`, `ymin`, `ymax`, +#' `lower`, `middle`, `upper`, `color`, `shape`, `linetype`, +#' `size` and `fill` #' @return A list of usual mappings that can be guessed from data #' @examples #' \dontrun{ diff --git a/inst/plot-maker/app.R b/inst/plot-maker/app.R index a904ce71..8e0da451 100644 --- a/inst/plot-maker/app.R +++ b/inst/plot-maker/app.R @@ -193,8 +193,8 @@ ui <- fluidPage( #---------- Server ----------# server <- function(input, output) { - #---------- Reactive helpers ----------# - #---------- Data ----------# + #---------- Reactive helpers ----------# + #---------- Data ----------# getData <- reactive({ data <- data.frame(`No data` = NULL) if (isIncluded(input$dataType, "environment")) { @@ -244,7 +244,7 @@ server <- function(input, output) { utils::head(getData()) }) - #---------- Data Mapping ----------# + #---------- Data Mapping ----------# getVariableNames <- reactive({ data <- getData() return(c("none" = "none", sapply(names(data), identity))) @@ -333,7 +333,7 @@ server <- function(input, output) { return(dataMapping) }) - #---------- Plot Configuration ----------# + #---------- Plot Configuration ----------# #----- Use a theme updateTheme <- reactive({ if (length(input$loadTheme) == 0) { @@ -829,23 +829,25 @@ server <- function(input, output) { }) #---------- Analysis ----------# - output$pkRatioTable <- renderTable({ - data <- getData() - dataMapping <- getDataMapping() - getPKRatioMeasure(data = data, dataMapping = dataMapping) - }, - rownames = TRUE + output$pkRatioTable <- renderTable( + { + data <- getData() + dataMapping <- getDataMapping() + getPKRatioMeasure(data = data, dataMapping = dataMapping) + }, + rownames = TRUE ) - output$summaryTable <- renderTable({ - if (!isIncluded(input$selectedPlot, "plotBoxWhisker")) { - return() - } - data <- getData() - dataMapping <- getDataMapping() - getBoxWhiskerMeasure(data = data, dataMapping = dataMapping) - }, - rownames = TRUE + output$summaryTable <- renderTable( + { + if (!isIncluded(input$selectedPlot, "plotBoxWhisker")) { + return() + } + data <- getData() + dataMapping <- getDataMapping() + getBoxWhiskerMeasure(data = data, dataMapping = dataMapping) + }, + rownames = TRUE ) #---------- Save Plot ----------# diff --git a/inst/plot-maker/helpers.R b/inst/plot-maker/helpers.R index 0e3345fa..766732d4 100644 --- a/inst/plot-maker/helpers.R +++ b/inst/plot-maker/helpers.R @@ -20,26 +20,26 @@ listOfAvailablePlots <- c( ) #' @title parseFieldToObject -#' @description Create expressions to evaluate of type: `objectName$fieldName <- fieldName` +#' @description Create expressions to evaluate of type: `objectName$fieldName <- fieldName` #' or `objectName$fieldName <- fieldName %||% objectName$fieldName` depending on option `` #' @param fieldName Names of the field/variable to associate to the object `objectName` #' @param objectName Name of the object on which fields `fieldName` are associated #' @param nullCondition logical to use object field in case of null condition #' @return Expressions to eval -parseFieldToObject <- function(fieldName, objectName, nullCondition = FALSE){ - if(nullCondition){ +parseFieldToObject <- function(fieldName, objectName, nullCondition = FALSE) { + if (nullCondition) { parse(text = paste0(objectName, "$", fieldName, " <- ", fieldName, " %||% ", objectName, "$", fieldName)) } parse(text = paste0(objectName, "$", fieldName, " <- ", fieldName)) } #' @title parseFieldFromObject -#' @description Create expressions `fieldName <- objectName$fieldName` to evaluate +#' @description Create expressions `fieldName <- objectName$fieldName` to evaluate #' @param fieldName Names of the field/variable to associate to the object `object` #' @param objectName Name of the object on which fields `fieldName` are associated #' @return Expressions to eval -parseFieldFromObject <- function(fieldName, objectName){ - parse(text = paste0(fieldName," <- ", objectName, "$", fieldName)) +parseFieldFromObject <- function(fieldName, objectName) { + parse(text = paste0(fieldName, " <- ", objectName, "$", fieldName)) } #' @title %||% diff --git a/inst/theme-maker/app.R b/inst/theme-maker/app.R index 564b606a..0654665f 100644 --- a/inst/theme-maker/app.R +++ b/inst/theme-maker/app.R @@ -29,15 +29,18 @@ ui <- fluidPage( labelPanel("Subtitle"), labelPanel("Xlabel"), labelPanel("Ylabel"), - tabPanel("Watermark", - textInput("watermarkText", label = "Content", value = jsonTheme$background$watermark), - selectizeInput("watermarkColor", label = "Color", choices = grDevices:::colors(), - selected = jsonTheme$fonts$watermark$color, options = list(create=TRUE)), - numericInput("watermarkSize", label = "Size", min = 1, max = 48, value = jsonTheme$fonts$watermark$size, step = 0.5), - numericInput("watermarkAngle", label = "Angle", min = -180, max = 180, value = jsonTheme$fonts$watermark$angle, step = 1) - ) + tabPanel( + "Watermark", + textInput("watermarkText", label = "Content", value = jsonTheme$background$watermark), + selectizeInput("watermarkColor", + label = "Color", choices = grDevices:::colors(), + selected = jsonTheme$fonts$watermark$color, options = list(create = TRUE) + ), + numericInput("watermarkSize", label = "Size", min = 1, max = 48, value = jsonTheme$fonts$watermark$size, step = 0.5), + numericInput("watermarkAngle", label = "Angle", min = -180, max = 180, value = jsonTheme$fonts$watermark$angle, step = 1) ) - ), + ) + ), tabPanel( "Background", navlistPanel( @@ -45,8 +48,8 @@ ui <- fluidPage( backgroundPanel("Panel Area", "panel", includeFill = TRUE), backgroundPanel("XGrid", "xGrid", includeFill = FALSE), backgroundPanel("YGrid", "yGrid", includeFill = FALSE) - ) - ), + ) + ), tabPanel( "Axes", navlistPanel( @@ -54,41 +57,54 @@ ui <- fluidPage( backgroundPanel("YAxis", "yAxis", includeFill = FALSE), labelPanel("XTicks", "xAxis", "xAxisTicks"), labelPanel("YTicks", "yAxis", "yAxisTicks") - ) - ), + ) + ), tabPanel( "Legend", # TO DO: include legend title features in theme navlistPanel( - tabPanel("Position", - selectInput("legendPosition", label = "Position", choices = LegendPositions, selected = jsonTheme$background$legendPosition) - ), + tabPanel( + "Position", + selectInput("legendPosition", label = "Position", choices = LegendPositions, selected = jsonTheme$background$legendPosition) + ), labelPanel("Font", "legend", "legendFont"), backgroundPanel("Background", "legend", includeFill = TRUE) - ) - ), + ) + ), tabPanel( "Aesthetic Maps", navlistPanel( - tabPanel("Color", - numericInput("colorMapIndex", label = "Rank", min = 1, max = length(jsonTheme$aestheticMaps$color), value = 1, step = 1), - uiOutput("colorMapValue")), - tabPanel("Fill", - numericInput("fillMapIndex", label = "Rank", min = 1, max = length(jsonTheme$aestheticMaps$fill), value = 1, step = 1), - uiOutput("fillMapValue")), - tabPanel("Linetype", - numericInput("linetypeMapIndex", label = "Rank", min = 1, max = length(jsonTheme$aestheticMaps$linetype), value = 1, step = 1), - uiOutput("linetypeMapValue")), - tabPanel("Shape", - numericInput("shapeMapIndex", label = "Rank", min = 1, max = length(jsonTheme$aestheticMaps$shape), value = 1, step = 1), - uiOutput("shapeMapValue")), - tabPanel("Size", - numericInput("sizeMapIndex", label = "Rank", min = 1, max = length(jsonTheme$aestheticMaps$size), value = 1, step = 1), - uiOutput("sizeMapValue")), - tabPanel("Alpha", - numericInput("alphaMapIndex", label = "Rank", min = 1, max = length(jsonTheme$aestheticMaps$alpha), value = 1, step = 1), - uiOutput("alphaMapValue")) + tabPanel( + "Color", + numericInput("colorMapIndex", label = "Rank", min = 1, max = length(jsonTheme$aestheticMaps$color), value = 1, step = 1), + uiOutput("colorMapValue") + ), + tabPanel( + "Fill", + numericInput("fillMapIndex", label = "Rank", min = 1, max = length(jsonTheme$aestheticMaps$fill), value = 1, step = 1), + uiOutput("fillMapValue") + ), + tabPanel( + "Linetype", + numericInput("linetypeMapIndex", label = "Rank", min = 1, max = length(jsonTheme$aestheticMaps$linetype), value = 1, step = 1), + uiOutput("linetypeMapValue") + ), + tabPanel( + "Shape", + numericInput("shapeMapIndex", label = "Rank", min = 1, max = length(jsonTheme$aestheticMaps$shape), value = 1, step = 1), + uiOutput("shapeMapValue") + ), + tabPanel( + "Size", + numericInput("sizeMapIndex", label = "Rank", min = 1, max = length(jsonTheme$aestheticMaps$size), value = 1, step = 1), + uiOutput("sizeMapValue") + ), + tabPanel( + "Alpha", + numericInput("alphaMapIndex", label = "Rank", min = 1, max = length(jsonTheme$aestheticMaps$alpha), value = 1, step = 1), + uiOutput("alphaMapValue") ) + ) ), tabPanel( "Plot Configurations", @@ -104,10 +120,10 @@ ui <- fluidPage( tabPlotConfigurationPanel("plotPKRatio"), tabPlotConfigurationPanel("plotTimeProfile"), tabPlotConfigurationPanel("plotTornado") - ) ) ) - ), + ) + ), # Plot Column column( @@ -115,8 +131,8 @@ ui <- fluidPage( fluidRow( fileInput("loadTheme", "Load a Theme from Json", accept = ".json"), downloadButton("downloadJson", "Download theme .json") - ), - br(), + ), + br(), fluidRow( selectInput( inputId = "selectedSamplePlot", label = "Sample Plot", @@ -133,24 +149,48 @@ ui <- fluidPage( #---------- Server ----------# server <- function(input, output) { - + #---------- Interactive way of updating aesthetic map element ----------# - getColorMapValue <- reactive({jsonTheme$aestheticMaps$color[input$colorMapIndex]}) - getFillMapValue <- reactive({jsonTheme$aestheticMaps$fill[input$fillMapIndex]}) - getLinetypeMapValue <- reactive({jsonTheme$aestheticMaps$linetype[input$linetypeMapIndex]}) - getShapeMapValue <- reactive({jsonTheme$aestheticMaps$shape[input$shapeMapIndex]}) - getSizeMapValue <- reactive({jsonTheme$aestheticMaps$size[input$sizeMapIndex]}) - getAlphaMapValue <- reactive({jsonTheme$aestheticMaps$alpha[input$alphaMapIndex]}) - - output$colorMapValue <- renderUI({textInput("colorMapValue2", "value", getColorMapValue())}) - output$fillMapValue <- renderUI({textInput("fillMapValue2", "value", getFillMapValue())}) - output$linetypeMapValue <- renderUI({selectInput("linetypeMapValue2", "Value", choices = Linetypes, selected = getLinetypeMapValue())}) - output$shapeMapValue <- renderUI({selectInput("shapeMapValue2", "Value", choices = Shapes, selected = getShapeMapValue())}) - output$sizeMapValue <- renderUI({numericInput("sizeMapValue2", "Value", getSizeMapValue())}) - output$alphaMapValue <- renderUI({numericInput("alphaMapValue2", "Value", getAlphaMapValue())}) - + getColorMapValue <- reactive({ + jsonTheme$aestheticMaps$color[input$colorMapIndex] + }) + getFillMapValue <- reactive({ + jsonTheme$aestheticMaps$fill[input$fillMapIndex] + }) + getLinetypeMapValue <- reactive({ + jsonTheme$aestheticMaps$linetype[input$linetypeMapIndex] + }) + getShapeMapValue <- reactive({ + jsonTheme$aestheticMaps$shape[input$shapeMapIndex] + }) + getSizeMapValue <- reactive({ + jsonTheme$aestheticMaps$size[input$sizeMapIndex] + }) + getAlphaMapValue <- reactive({ + jsonTheme$aestheticMaps$alpha[input$alphaMapIndex] + }) + + output$colorMapValue <- renderUI({ + textInput("colorMapValue2", "value", getColorMapValue()) + }) + output$fillMapValue <- renderUI({ + textInput("fillMapValue2", "value", getFillMapValue()) + }) + output$linetypeMapValue <- renderUI({ + selectInput("linetypeMapValue2", "Value", choices = Linetypes, selected = getLinetypeMapValue()) + }) + output$shapeMapValue <- renderUI({ + selectInput("shapeMapValue2", "Value", choices = Shapes, selected = getShapeMapValue()) + }) + output$sizeMapValue <- renderUI({ + numericInput("sizeMapValue2", "Value", getSizeMapValue()) + }) + output$alphaMapValue <- renderUI({ + numericInput("alphaMapValue2", "Value", getAlphaMapValue()) + }) + #---------- Interactive way of updating plot configurations ----------# - + # Reactive function that updates theme R6 objects # The function uses expressions to prevent copy/paste of the code updateTheme <- reactive({ @@ -160,38 +200,38 @@ server <- function(input, output) { plotProperties <- c("title", "subtitle", "xlabel", "ylabel", "watermark", "xAxis", "yAxis", "legend") fontProperties <- c("Color", "Size", "Angle") updateFontExpression <- parse(text = paste0( - "jsonTheme$fonts$", rep(plotProperties, each = length(fontProperties)), + "jsonTheme$fonts$", rep(plotProperties, each = length(fontProperties)), "$", rep(tolower(fontProperties), length(plotProperties)), " <- input$", rep(inputPlotProperties, each = length(fontProperties)), rep(fontProperties, length(plotProperties)) )) eval(updateFontExpression) - + # TO DO: account for legend title ? # jsonTheme$fonts$legendTitle$color <- input$legendTitleColor # jsonTheme$fonts$legendTitle$size <- input$legendTitleSize # jsonTheme$fonts$legendTitle$angle <- input$legendTitleAngle - + #---------- Update Background elements ----------# # Each line will look like 'jsonTheme$background$plot$color <- input$plotColor' plotProperties <- c("plot", "panel", "xAxis", "yAxis", "xGrid", "yGrid", "legend") fontProperties <- c("Color", "Size", "Linetype") updateBackgroundExpression <- parse(text = paste0( - "jsonTheme$background$", rep(plotProperties, each = length(fontProperties)), + "jsonTheme$background$", rep(plotProperties, each = length(fontProperties)), "$", rep(tolower(fontProperties), length(plotProperties)), " <- input$", rep(plotProperties, each = length(fontProperties)), rep(fontProperties, length(plotProperties)) )) eval(updateBackgroundExpression) - + #---------- Update remaining fields not covered by expressions ----------# jsonTheme$background$legendPosition <- input$legendPosition jsonTheme$background$watermark <- input$watermarkText - + jsonTheme$background$plot$fill <- input$plotFill jsonTheme$background$panel$fill <- input$panelFill jsonTheme$background$legend$fill <- input$legendFill - + #---------- Aesthetic maps ----------# - # Each line will look like 'jsonTheme$aestheticMaps$color[input$colorMapIndex] <- + # Each line will look like 'jsonTheme$aestheticMaps$color[input$colorMapIndex] <- # tlfInput(input$colorMapValue2) %||% jsonTheme$aestheticMaps$color[input$colorMapIndex]' mapProperties <- c("color", "fill", "linetype", "size", "alpha") updateMapExpression <- parse(text = paste0( @@ -199,131 +239,131 @@ server <- function(input, output) { mapProperties, "MapValue2) %||% jsonTheme$aestheticMaps$", mapProperties, "[input$", mapProperties, "MapIndex]" )) eval(updateMapExpression) - + # Update remaining field not covered by expressions (as.numeric enforced) jsonTheme$aestheticMaps$shape[input$shapeMapIndex] <- tlfInput(as.numeric(input$shapeMapValue2)) %||% jsonTheme$aestheticMaps$shape[input$shapeMapIndex] - + #---------- Plot configurations ----------# #----- Atom plots - jsonTheme$plotConfigurations$addScatter$color <- selectInputFromKey(input$addScatterColor, input$addScatterColor2) - jsonTheme$plotConfigurations$addScatter$shape <- selectInputFromKey(input$addScatterShape, input$addScatterShape2) + jsonTheme$plotConfigurations$addScatter$color <- selectInputFromKey(input$addScatterColor, input$addScatterColor2) + jsonTheme$plotConfigurations$addScatter$shape <- selectInputFromKey(input$addScatterShape, input$addScatterShape2) jsonTheme$plotConfigurations$addScatter$size <- selectInputFromKey(input$addScatterSize, input$addScatterSize2) - - jsonTheme$plotConfigurations$addLine$color <- selectInputFromKey(input$addLineColor, input$addLineColor2) - jsonTheme$plotConfigurations$addLine$linetype <- selectInputFromKey(input$addLineLinetype, input$addLineLinetype2) + + jsonTheme$plotConfigurations$addLine$color <- selectInputFromKey(input$addLineColor, input$addLineColor2) + jsonTheme$plotConfigurations$addLine$linetype <- selectInputFromKey(input$addLineLinetype, input$addLineLinetype2) jsonTheme$plotConfigurations$addLine$size <- selectInputFromKey(input$addLineSize, input$addLineSize2) - - jsonTheme$plotConfigurations$addRibbon$fill <- selectInputFromKey(input$addRibbonFill, input$addRibbonFill2) + + jsonTheme$plotConfigurations$addRibbon$fill <- selectInputFromKey(input$addRibbonFill, input$addRibbonFill2) jsonTheme$plotConfigurations$addRibbon$alpha <- selectInputFromKey(input$addRibbonAlpha, input$addRibbonAlpha2) - jsonTheme$plotConfigurations$addRibbon$color <- selectInputFromKey(input$addRibbonColor, input$addRibbonColor2) - jsonTheme$plotConfigurations$addRibbon$linetype <- selectInputFromKey(input$addRibbonLinetype, input$addRibbonLinetype2) + jsonTheme$plotConfigurations$addRibbon$color <- selectInputFromKey(input$addRibbonColor, input$addRibbonColor2) + jsonTheme$plotConfigurations$addRibbon$linetype <- selectInputFromKey(input$addRibbonLinetype, input$addRibbonLinetype2) jsonTheme$plotConfigurations$addRibbon$size <- selectInputFromKey(input$addRibbonSize, input$addRibbonSize2) - - jsonTheme$plotConfigurations$addErrorbar$color <- selectInputFromKey(input$addErrorbarColor, input$addErrorbarColor2) - jsonTheme$plotConfigurations$addErrorbar$linetype <- selectInputFromKey(input$addErrorbarLinetype, input$addErrorbarLinetype2) + + jsonTheme$plotConfigurations$addErrorbar$color <- selectInputFromKey(input$addErrorbarColor, input$addErrorbarColor2) + jsonTheme$plotConfigurations$addErrorbar$linetype <- selectInputFromKey(input$addErrorbarLinetype, input$addErrorbarLinetype2) jsonTheme$plotConfigurations$addErrorbar$size <- selectInputFromKey(input$addErrorbarSize, input$addErrorbarSize2) - + #----- Molecule plots by property using expression #--- Points plotNames <- rep(c("plotBoxWhisker", "plotDDIRatio", "plotObsVsPred", "plotPKRatio", "plotTimeProfile", "plotTornado"), each = 3) selectionProperties <- rep(c("Color", "Shape", "Size"), 6) updateConfigurationExpression <- parse(text = paste0( - "jsonTheme$plotConfigurations$", plotNames, "$points$", tolower(selectionProperties), + "jsonTheme$plotConfigurations$", plotNames, "$points$", tolower(selectionProperties), " <- selectInputFromKey(input$", plotNames, "Points", selectionProperties, ", input$", plotNames, "Points", selectionProperties, "2)" )) eval(updateConfigurationExpression) - + #--- Lines plotNames <- rep(c("plotDDIRatio", "plotHistogram", "plotObsVsPred", "plotPKRatio", "plotTimeProfile", "plotTornado"), each = 3) selectionProperties <- rep(c("Color", "Linetype", "Size"), 6) updateConfigurationExpression <- parse(text = paste0( - "jsonTheme$plotConfigurations$", plotNames, "$lines$", tolower(selectionProperties), + "jsonTheme$plotConfigurations$", plotNames, "$lines$", tolower(selectionProperties), " <- selectInputFromKey(input$", plotNames, "Lines", selectionProperties, ", input$", plotNames, "Lines", selectionProperties, "2)" )) eval(updateConfigurationExpression) - + #--- Ribbons plotNames <- rep(c("plotBoxWhisker", "plotHistogram", "plotTimeProfile", "plotTornado"), each = 5) selectionProperties <- rep(c("Fill", "Alpha", "Color", "Linetype", "Size"), 4) updateConfigurationExpression <- parse(text = paste0( - "jsonTheme$plotConfigurations$", plotNames, "$ribbons$", tolower(selectionProperties), + "jsonTheme$plotConfigurations$", plotNames, "$ribbons$", tolower(selectionProperties), " <- selectInputFromKey(input$", plotNames, "Ribbons", selectionProperties, ", input$", plotNames, "Ribbons", selectionProperties, "2)" )) eval(updateConfigurationExpression) - + #--- Errorbars plotNames <- rep(c("plotDDIRatio", "plotObsVsPred", "plotPKRatio", "plotTimeProfile"), each = 3) selectionProperties <- rep(c("Color", "Linetype", "Size"), 4) updateConfigurationExpression <- parse(text = paste0( - "jsonTheme$plotConfigurations$", plotNames, "$errorbars$", tolower(selectionProperties), + "jsonTheme$plotConfigurations$", plotNames, "$errorbars$", tolower(selectionProperties), " <- selectInputFromKey(input$", plotNames, "Errorbars", selectionProperties, ", input$", plotNames, "Errorbars", selectionProperties, "2)" )) eval(updateConfigurationExpression) - + #---------- Use theme for sample plots ----------# # This also set theme as current: after using app, current theme is changed useTheme(jsonTheme) }) - + output$samplePlot <- renderPlot({ - + # Reactive function that update theme object updateTheme() plotConfiguration <- PlotConfiguration$new(title = "title", subtitle = "subtitle", xlabel = "xlabel", ylabel = "ylabel") - + #---------- Define dataMapping from selected sample plot ----------# dataMapping <- switch(input$selectedSamplePlot, - initializePlot = NULL, - addScatter = XYGDataMapping$new(x = "Age", y = "Ratio", color = "Sex", shape = "Country"), - addLine = XYGDataMapping$new(x = "ID", y = "Ratio", color = "Sex", linetype = "Country"), - addRibbon = RangeDataMapping$new(x = "ID", ymin = "Obs", ymax = "Pred", fill = "Sex"), - addErrorbar = RangeDataMapping$new(x = "Age", ymin = "Obs", ymax = "Pred", color = "Sex", linetype = "Country"), - plotBoxWhisker = BoxWhiskerDataMapping$new(x = "AgeBin", y = "Ratio", fill = "Sex"), - plotDDIRatio = DDIRatioDataMapping$new(x = "Obs", y = "Pred", color = "Sex", shape = "Country"), - plotHistogram = HistogramDataMapping$new(x = "Ratio", fill = "Sex"), - plotObsVsPred = ObsVsPredDataMapping$new(x = "Obs", y = "Pred", color = "Sex", shape = "Country"), - plotPKRatio = PKRatioDataMapping$new(x = "Age", y = "Ratio", color = "Sex", shape = "Country"), - plotTimeProfile = TimeProfileDataMapping$new(x = "ID", y = "Ratio", ymin = "ymin", ymax = "ymax", fill = "Sex", color = "Sex", linetype = "Country"), - plotTornado = TornadoDataMapping$new(x = "Ratio", y = "ID") - ) - - + initializePlot = NULL, + addScatter = XYGDataMapping$new(x = "Age", y = "Ratio", color = "Sex", shape = "Country"), + addLine = XYGDataMapping$new(x = "ID", y = "Ratio", color = "Sex", linetype = "Country"), + addRibbon = RangeDataMapping$new(x = "ID", ymin = "Obs", ymax = "Pred", fill = "Sex"), + addErrorbar = RangeDataMapping$new(x = "Age", ymin = "Obs", ymax = "Pred", color = "Sex", linetype = "Country"), + plotBoxWhisker = BoxWhiskerDataMapping$new(x = "AgeBin", y = "Ratio", fill = "Sex"), + plotDDIRatio = DDIRatioDataMapping$new(x = "Obs", y = "Pred", color = "Sex", shape = "Country"), + plotHistogram = HistogramDataMapping$new(x = "Ratio", fill = "Sex"), + plotObsVsPred = ObsVsPredDataMapping$new(x = "Obs", y = "Pred", color = "Sex", shape = "Country"), + plotPKRatio = PKRatioDataMapping$new(x = "Age", y = "Ratio", color = "Sex", shape = "Country"), + plotTimeProfile = TimeProfileDataMapping$new(x = "ID", y = "Ratio", ymin = "ymin", ymax = "ymax", fill = "Sex", color = "Sex", linetype = "Country"), + plotTornado = TornadoDataMapping$new(x = "Ratio", y = "ID") + ) + + #---------- Define plotConfiguration from selected sample plot ----------# plotConfiguration <- switch(input$selectedSamplePlot, - initializePlot = plotConfiguration, - addScatter = plotConfiguration, - addLine = plotConfiguration, - addRibbon = plotConfiguration, - addErrorbar = plotConfiguration, - plotBoxWhisker = BoxWhiskerPlotConfiguration$new(title = "title", subtitle = "subtitle", xlabel = "xlabel", ylabel = "ylabel"), - plotDDIRatio = DDIRatioPlotConfiguration$new(title = "title", subtitle = "subtitle", xlabel = "xlabel", ylabel = "ylabel", xScale = Scaling$log, yScale = Scaling$log), - plotHistogram = HistogramPlotConfiguration$new(title = "title", subtitle = "subtitle", xlabel = "xlabel", ylabel = "ylabel"), - plotObsVsPred = ObsVsPredPlotConfiguration$new(title = "title", subtitle = "subtitle", xlabel = "xlabel", ylabel = "ylabel"), - plotPKRatio = PKRatioPlotConfiguration$new(title = "title", subtitle = "subtitle", xlabel = "xlabel", ylabel = "ylabel", yScale = Scaling$log), - plotTimeProfile = TimeProfilePlotConfiguration$new(title = "title", subtitle = "subtitle", xlabel = "xlabel", ylabel = "ylabel"), - plotTornado = TornadoPlotConfiguration$new(title = "title", subtitle = "subtitle", xlabel = "xlabel", ylabel = "ylabel") - ) - + initializePlot = plotConfiguration, + addScatter = plotConfiguration, + addLine = plotConfiguration, + addRibbon = plotConfiguration, + addErrorbar = plotConfiguration, + plotBoxWhisker = BoxWhiskerPlotConfiguration$new(title = "title", subtitle = "subtitle", xlabel = "xlabel", ylabel = "ylabel"), + plotDDIRatio = DDIRatioPlotConfiguration$new(title = "title", subtitle = "subtitle", xlabel = "xlabel", ylabel = "ylabel", xScale = Scaling$log, yScale = Scaling$log), + plotHistogram = HistogramPlotConfiguration$new(title = "title", subtitle = "subtitle", xlabel = "xlabel", ylabel = "ylabel"), + plotObsVsPred = ObsVsPredPlotConfiguration$new(title = "title", subtitle = "subtitle", xlabel = "xlabel", ylabel = "ylabel"), + plotPKRatio = PKRatioPlotConfiguration$new(title = "title", subtitle = "subtitle", xlabel = "xlabel", ylabel = "ylabel", yScale = Scaling$log), + plotTimeProfile = TimeProfilePlotConfiguration$new(title = "title", subtitle = "subtitle", xlabel = "xlabel", ylabel = "ylabel"), + plotTornado = TornadoPlotConfiguration$new(title = "title", subtitle = "subtitle", xlabel = "xlabel", ylabel = "ylabel") + ) + #---------- Define plot from selected sample plot ----------# samplePlot <- switch(input$selectedSamplePlot, - initializePlot = initializePlot(plotConfiguration), - addScatter = addScatter(data = testData, dataMapping = dataMapping, plotConfiguration = plotConfiguration), - addLine = addLine(data = testData, dataMapping = dataMapping, plotConfiguration = plotConfiguration), - addRibbon = addRibbon(data = testData, dataMapping = dataMapping, plotConfiguration = plotConfiguration), - addErrorbar = addErrorbar(data = testData, dataMapping = dataMapping, plotConfiguration = plotConfiguration), - plotBoxWhisker = plotBoxWhisker(data = testData, dataMapping = dataMapping, plotConfiguration = plotConfiguration), - plotDDIRatio = plotDDIRatio(data = testData, dataMapping = dataMapping, plotConfiguration = plotConfiguration), - plotHistogram = plotHistogram(data = testData, dataMapping = dataMapping, plotConfiguration = plotConfiguration), - plotObsVsPred = plotObsVsPred(data = testData, dataMapping = dataMapping, plotConfiguration = plotConfiguration), - plotPKRatio = plotPKRatio(data = testData, dataMapping = dataMapping, plotConfiguration = plotConfiguration), - plotTimeProfile = plotTimeProfile(data = testData, dataMapping = dataMapping, plotConfiguration = plotConfiguration), - # use only 6 first values for the tornado plot - plotTornado = plotTornado(data = testData[1:6,], dataMapping = dataMapping, plotConfiguration = plotConfiguration) - ) + initializePlot = initializePlot(plotConfiguration), + addScatter = addScatter(data = testData, dataMapping = dataMapping, plotConfiguration = plotConfiguration), + addLine = addLine(data = testData, dataMapping = dataMapping, plotConfiguration = plotConfiguration), + addRibbon = addRibbon(data = testData, dataMapping = dataMapping, plotConfiguration = plotConfiguration), + addErrorbar = addErrorbar(data = testData, dataMapping = dataMapping, plotConfiguration = plotConfiguration), + plotBoxWhisker = plotBoxWhisker(data = testData, dataMapping = dataMapping, plotConfiguration = plotConfiguration), + plotDDIRatio = plotDDIRatio(data = testData, dataMapping = dataMapping, plotConfiguration = plotConfiguration), + plotHistogram = plotHistogram(data = testData, dataMapping = dataMapping, plotConfiguration = plotConfiguration), + plotObsVsPred = plotObsVsPred(data = testData, dataMapping = dataMapping, plotConfiguration = plotConfiguration), + plotPKRatio = plotPKRatio(data = testData, dataMapping = dataMapping, plotConfiguration = plotConfiguration), + plotTimeProfile = plotTimeProfile(data = testData, dataMapping = dataMapping, plotConfiguration = plotConfiguration), + # use only 6 first values for the tornado plot + plotTornado = plotTornado(data = testData[1:6, ], dataMapping = dataMapping, plotConfiguration = plotConfiguration) + ) return(samplePlot) - }) - - + }) + + # Load/save Theme output$downloadJson <- downloadHandler( filename = "my-theme.json", diff --git a/man/getAesStringMapping.Rd b/man/getAesStringMapping.Rd index f1ac053b..f26c2de5 100644 --- a/man/getAesStringMapping.Rd +++ b/man/getAesStringMapping.Rd @@ -15,7 +15,7 @@ A list of mappings that can be used as is by \code{aes_string}. \description{ Get the \code{dataMapping} elements and convert them into character string usable by ggplot mapping function \code{aes_string}. -The conversion fixes any issue of special characters by wrapping the string by \code{``} +The conversion fixes any issue of special characters by wrapping the string by ```` if not already used. \code{dataMapping} unmapped aesthetic elements (e.g. \code{color}) are associated to diff --git a/man/tlfStatFunctions.Rd b/man/tlfStatFunctions.Rd index 4b5e52f6..3ebdd2e9 100644 --- a/man/tlfStatFunctions.Rd +++ b/man/tlfStatFunctions.Rd @@ -11,7 +11,7 @@ An object of class \code{list} of length 31. tlfStatFunctions } \description{ -Bank of predifined functions ready to use by Aggregation methods. Bank defined as Enum. +Bank of predefined functions ready to use by Aggregation methods. Bank defined as Enum. To access the function from its name, use match.fun: e.g. testFun <- match.fun("mean-1.96sd") } \keyword{datasets} diff --git a/tests/dev/aesDefault-necessity.R b/tests/dev/aesDefault-necessity.R index 11c52e8c..fe59a585 100644 --- a/tests/dev/aesDefault-necessity.R +++ b/tests/dev/aesDefault-necessity.R @@ -8,34 +8,40 @@ library(tlf) pkRatioData$aesDefault <- "" -plot1a <- ggplot() + geom_point( - data = pkRatioData, - mapping = aes_string(x = "Age", y = "Ratio"), - show.legend = FALSE -) + labs(title = "1A") +plot1a <- ggplot() + + geom_point( + data = pkRatioData, + mapping = aes_string(x = "Age", y = "Ratio"), + show.legend = FALSE + ) + + labs(title = "1A") # Exemple, change color plot1b <- plot1a + scale_color_manual(values = "red") + labs(title = "1B") -plot2a <- ggplot() + geom_point( - data = pkRatioData, - mapping = aes_string(x = "Age", y = "Ratio"), - color = "red", - show.legend = FALSE -) + labs(title = "2A") +plot2a <- ggplot() + + geom_point( + data = pkRatioData, + mapping = aes_string(x = "Age", y = "Ratio"), + color = "red", + show.legend = FALSE + ) + + labs(title = "2A") # Exemple, change color plot2b <- plot2a + scale_color_manual(values = "blue") + labs(title = "2B") -plot3a <- ggplot() + geom_point( - data = pkRatioData, - mapping = aes_string( - x = "Age", - y = "Ratio", - color = "aesDefault" - ), - show.legend = FALSE -) + labs(title = "3A") +plot3a <- ggplot() + + geom_point( + data = pkRatioData, + mapping = aes_string( + x = "Age", + y = "Ratio", + color = "aesDefault" + ), + show.legend = FALSE + ) + + labs(title = "3A") # Exemple, change color plot3b <- plot3a + scale_color_manual(values = "blue") + labs(title = "3B") diff --git a/tests/dev/test-tornado-plots.R b/tests/dev/test-tornado-plots.R index 7616108c..a52d5059 100644 --- a/tests/dev/test-tornado-plots.R +++ b/tests/dev/test-tornado-plots.R @@ -1,40 +1,58 @@ tornadoPopData <- data.frame( - sensitivity = c(c(1,2,3, -1,-2,-3), c(1,2,3, -1,-2,-3)-0.2), - path = rep(rep(c("liver","kidney"),each=3),2), - quantile = rep(rep(c("5th","50th","95th"),2),2), - population = rep(c("Adults", "Peds"),each=6)) + sensitivity = c(c(1, 2, 3, -1, -2, -3), c(1, 2, 3, -1, -2, -3) - 0.2), + path = rep(rep(c("liver", "kidney"), each = 3), 2), + quantile = rep(rep(c("5th", "50th", "95th"), 2), 2), + population = rep(c("Adults", "Peds"), each = 6) +) -tornadoData <- tornadoPopData[tornadoPopData$population %in% "Adults" & - tornadoPopData$quantile %in% "50th",] +tornadoData <- tornadoPopData[tornadoPopData$population %in% "Adults" & + tornadoPopData$quantile %in% "50th", ] # Direct Tornado Plot -plotTornado(x = tornadoData$sensitivity, - y = tornadoData$path) +plotTornado( + x = tornadoData$sensitivity, + y = tornadoData$path +) # Options/Features -plotTornado(x = tornadoData$sensitivity, - y = tornadoData$path, - colorPalette = "Dark2") +plotTornado( + x = tornadoData$sensitivity, + y = tornadoData$path, + colorPalette = "Dark2" +) -plotTornado(x = tornadoData$sensitivity, - y = tornadoData$path, - bar = FALSE) +plotTornado( + x = tornadoData$sensitivity, + y = tornadoData$path, + bar = FALSE +) # Higher level with dataMapping -plotTornado(data = tornadoPopData[tornadoPopData$population %in% "Adults",], - dataMapping = TornadoDataMapping$new(x = "sensitivity", - y = "path", - color = "quantile")) -plotTornado(data = tornadoPopData, - dataMapping = TornadoDataMapping$new(x = "sensitivity", - y = "path", - color = "quantile"), - bar = FALSE) - -plotTornado(data = tornadoPopData, - dataMapping = TornadoDataMapping$new(x = "sensitivity", - y = "path", - color = "quantile", - shape = "population"), - bar = FALSE) +plotTornado( + data = tornadoPopData[tornadoPopData$population %in% "Adults", ], + dataMapping = TornadoDataMapping$new( + x = "sensitivity", + y = "path", + color = "quantile" + ) +) +plotTornado( + data = tornadoPopData, + dataMapping = TornadoDataMapping$new( + x = "sensitivity", + y = "path", + color = "quantile" + ), + bar = FALSE +) +plotTornado( + data = tornadoPopData, + dataMapping = TornadoDataMapping$new( + x = "sensitivity", + y = "path", + color = "quantile", + shape = "population" + ), + bar = FALSE +) diff --git a/tests/testthat/test-pkratio.R b/tests/testthat/test-pkratio.R index 7ece401c..0f5677b9 100644 --- a/tests/testthat/test-pkratio.R +++ b/tests/testthat/test-pkratio.R @@ -54,7 +54,7 @@ test_that("PK Ratio default settings work", { }) test_that("PK Ratio typical test works", { -# Data mapping: + # Data mapping: # x = Age, y = Ratio, color = Gender, shape = c(Dose, Compound) pkRatioMap <- PKRatioDataMapping$new( x = "Age", diff --git a/tlf.Rproj b/tlf.Rproj index b9255bc9..9a749ba0 100644 --- a/tlf.Rproj +++ b/tlf.Rproj @@ -1,8 +1,8 @@ Version: 1.0 -RestoreWorkspace: Default -SaveWorkspace: Default -AlwaysSaveHistory: Default +RestoreWorkspace: No +SaveWorkspace: No +AlwaysSaveHistory: No EnableCodeIndexing: Yes UseSpacesForTab: Yes @@ -18,3 +18,6 @@ StripTrailingWhitespace: Yes BuildType: Package PackageUseDevtools: Yes PackageInstallArgs: --no-multiarch --with-keep.source + +QuitChildProcessesOnExit: Yes +DisableExecuteRprofile: Yes diff --git a/vignettes/atom-plots.Rmd b/vignettes/atom-plots.Rmd index 2c6e78af..8618f11f 100644 --- a/vignettes/atom-plots.Rmd +++ b/vignettes/atom-plots.Rmd @@ -1,9 +1,11 @@ --- title: "Atom plots" -author: "OSPSuiteR 2019" -output: rmarkdown::html_vignette +author: "OSPSuiteR 2021" +output: + rmarkdown::html_vignette: + toc: true vignette: > - %\VignetteIndexEntry{atom-plots} + %\VignetteIndexEntry{Atom plots} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- @@ -11,7 +13,10 @@ vignette: > ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, - comment = "#>" + comment = "#>", + dpi = 300, + fig.align = "center", + out.width = "100%" ) ``` @@ -19,16 +24,18 @@ knitr::opts_chunk$set( require(tlf) ``` -```{r load theme, echo=FALSE} +```{r load-theme, echo=FALSE} vignetteTheme <- loadThemeFromJson(system.file("extdata", "template-theme.json", package = "tlf")) useTheme(vignetteTheme) ``` -This vignette tackles how to use atom plots to perform simple to more complex plots with the `tlf`-library. + +This vignette tackles how to use atom plots to prepare simple to more complex plots with the `tlf`-library. # Introduction to atom plots -Atom plots correspond to simple plots that can be used independently or in combination to form a final plot, often more complex, that will be referred as molecule plot. -In the sequel, the following atoms are detailed: +An **atom plot** corresponds to a simple plot that can be combined with other atom plots to form a final, often more complex, plot that will be referred to as a **molecule plot**. + +Here we outline the following atom plots: - *initializePlot* - *addScatter* @@ -52,38 +59,54 @@ Below are a few examples of use case of *initializePlot*: emptyPlot <- initializePlot() # Create a PlotConfiguration object with some specifications -myConfiguration <- PlotConfiguration$new(title = "My empty plot", - xlabel = "X", - ylabel = "Y") +myConfiguration <- PlotConfiguration$new( + title = "My empty plot", + xlabel = "X", + ylabel = "Y" +) + # Use the specification to create the plot emptyPlotWithLabels <- initializePlot(myConfiguration) # PlotConfiguration class has a smart mapping feature, # directly deriving labels from data and its metaData and its dataMapping -time <- seq(0,20, 0.1) -myData <- data.frame(x = time, - y = 2*cos(time)) -# If metaData includes dimension and unit, +time <- seq(0, 20, 0.1) +myData <- data.frame( + x = time, + y = 2 * cos(time) +) + +# If metaData includes dimension and unit, # they can be use by the smart configuration to generate labels as "dimension [unit]" -myMetaData <- list(x = list(dimension = "Time", - unit = "min"), - y = list(dimension = "Amplitude", - unit = "cm")) -myMapping <- XYGDataMapping$new(x = "x", - y = "y") +myMetaData <- list( + x = list( + dimension = "Time", + unit = "min" + ), + y = list( + dimension = "Amplitude", + unit = "cm" + ) +) +myMapping <- XYGDataMapping$new( + x = "x", + y = "y" +) # In this example, the configuration will use the x/y mapping from dataMapping # to fetch dimension and unit from metaData -mySmartConfiguration <- PlotConfiguration$new(title = "My smart plot", - data = myData, - metaData = myMetaData, - dataMapping = myMapping) +mySmartConfiguration <- PlotConfiguration$new( + title = "My smart plot", + data = myData, + metaData = myMetaData, + dataMapping = myMapping +) smartEmptyPlot <- initializePlot(mySmartConfiguration) ``` -```{r initializePlot output, echo=FALSE, fig.cap="Left: emptyPlot; Middle: emptyPlotWithLabels; Right: smartEmptyPlot", fig.width=7.5} -gridExtra::grid.arrange(emptyPlot, emptyPlotWithLabels, smartEmptyPlot, ncol=3) +```{r initializePlot-output, echo=FALSE, fig.cap="Left: emptyPlot; Middle: emptyPlotWithLabels; Right: smartEmptyPlot", fig.width=7.5} +gridExtra::grid.arrange(emptyPlot, emptyPlotWithLabels, smartEmptyPlot, ncol = 3) ``` # Add scatter or lines to a plot object: *addScatter*, *addLine* @@ -93,15 +116,19 @@ If a plot object is specified in *plotObject* input, then the layer will be adde In the case the input is `NULL` (default value), the function *initializePlot* is called internally. The following data will be used as an example in the next section: -```{r get ExampleData, echo=FALSE} + +```{r get-ExampleData, echo=FALSE} myTestData <- read.csv(system.file("extdata", "test-data.csv", package = "tlf"), stringsAsFactors = FALSE) -myTestData <- data.frame(x = myTestData$Obs, - y = myTestData$Pred, - type = myTestData$Sex, - country = myTestData$Country) +myTestData <- data.frame( + x = myTestData$Obs, + y = myTestData$Pred, + type = myTestData$Sex, + country = myTestData$Country +) ``` -```{r show ExampleData, results='asis'} -knitr::kable(utils::head(myTestData)) + +```{r show-ExampleData, results='asis'} +knitr::kable(utils::head(myTestData)) ``` ## *addScatter* @@ -109,36 +136,51 @@ knitr::kable(utils::head(myTestData)) The primary input parameter of function *addScatter* is *data* and can be used along with its *metaData* and *dataMapping*. However, it is also possible to directly use the input parameters *x* and *y* instead to plot directly *y* as a function of *x*. -```{r scatter mapping} +```{r scatter-mapping} # Naive mapping on x and y -myMapping <- XYGDataMapping$new(x = "x", - y = "y") +myMapping <- XYGDataMapping$new( + x = "x", + y = "y" +) # Mapping on x and y, while grouping the data by type -myGroupMapping <- XYGDataMapping$new(x = "x", - y = "y", - color = "type") +myGroupMapping <- XYGDataMapping$new( + x = "x", + y = "y", + color = "type" +) + +# Plots + # Using the naive mapping -pNaive <- addScatter(data = myTestData, - metaData = myMetaData, - dataMapping = myMapping) +pNaive <- addScatter( + data = myTestData, + metaData = myMetaData, + dataMapping = myMapping +) # Using tlf smart mapping (same as naive) -pSmart <- addScatter(data = myTestData, - metaData = myMetaData) +pSmart <- addScatter( + data = myTestData, + metaData = myMetaData +) # Using group in mapping -pGroup <- addScatter(data = myTestData, - metaData = myMetaData, - dataMapping = myGroupMapping) +pGroup <- addScatter( + data = myTestData, + metaData = myMetaData, + dataMapping = myGroupMapping +) # Using x and y (same as naive but without metaData, no label) -pXY <- addScatter(x = myTestData$x, - y = myTestData$y) +pXY <- addScatter( + x = myTestData$x, + y = myTestData$y +) ``` -```{r show scatter mapping, echo=FALSE, fig.cap="top left: pNaive; top right: pSmart; bottom left: pGroup; bottom right: pXY", fig.width=7.5} -gridExtra::grid.arrange(pNaive, pSmart, pGroup, pXY, ncol=2) +```{r show-scatter-mapping, fig.height=7, fig.width=7, echo=FALSE, fig.cap="top left: pNaive; top right: pSmart; bottom left: pGroup; bottom right: pXY", fig.width=7.5} +gridExtra::grid.arrange(pNaive, pSmart, pGroup, pXY, ncol = 2) ``` Input parameters of *addScatter* also include *plotConfiguration* and *plotObject* as previously described. @@ -146,35 +188,42 @@ Input parameters *caption*, *color*, *size*, *shape* and *linetype* can overwrit These parameters are optional and will be `NULL` by default, which will lead to use aesthetic from the current theme. In particular, *dataMapping* also allows to create a legend caption, the input parameter *caption* can overwrtie such legend caption. -```{r addScatter options} +```{r addScatter-options} males <- myTestData$type %in% "Male" females <- myTestData$type %in% "Female" + # Using x and y -pScatter1 <- addScatter(x = myTestData$x[males], - y = myTestData$y[males], - color = "blue", - size = 3, - caption = "Male") -pScatter2 <- addScatter(x = myTestData$x[females], - y = myTestData$y[females], - color = "pink", - size = 3, - caption = "Female") -pScatter3 <- addScatter(x = myTestData$x[females], - y = myTestData$y[females], - color = "pink", - size = 3, - caption = "Female", - plotObject = pScatter1) +pScatter1 <- addScatter( + x = myTestData$x[males], + y = myTestData$y[males], + color = "blue", + size = 3, + caption = "Male" +) +pScatter2 <- addScatter( + x = myTestData$x[females], + y = myTestData$y[females], + color = "pink", + size = 3, + caption = "Female" +) +pScatter3 <- addScatter( + x = myTestData$x[females], + y = myTestData$y[females], + color = "pink", + size = 3, + caption = "Female", + plotObject = pScatter1 +) ``` -```{r show addScatter, echo=FALSE, fig.cap="Left: pScatter1; Middle: pScatter2; Right: pScatter3", fig.width=7.5} -gridExtra::grid.arrange(pScatter1, pScatter2, pScatter3, ncol=3) +```{r show-addScatter, echo=FALSE, fig.width=9, fig.cap="Left: pScatter1; Middle: pScatter2; Right: pScatter3"} +gridExtra::grid.arrange(pScatter1, pScatter2, pScatter3, ncol = 3) ``` -Finally, the last input parameters include *caption*, *color*, *size*, *shape* and *linetype*. -These parameters are optional and will use the default of the current theme if they are not defined. -In particular, *dataMapping* also allows to create a legend caption, the input parameter *caption* can overwrtie such legend caption. +Finally, the last input parameters include *caption*, *color*, *size*, *shape*, and *linetype*. +These parameters are optional and will use the default of the current theme if they are not specified. +In particular, *dataMapping* also allows to create a legend caption, the input parameter *caption* can overwrite such legend caption. ## *addLine* @@ -184,9 +233,8 @@ It also differs by the possibility of using *x* or *y* input for x/y-intercepts. # Add ribbon or errorbars to a plot object: *addRibbon*, *addErrorbar* -These 2 atoms work in a similar fashion to *addScatter* and *addLine* but they use a different mapping that require *ymin* and *ymax* insteada of *y*. +These atoms work in a similar fashion to *addScatter* and *addLine* but they use a different mapping that require *ymin* and *ymax* instead of *y*. ## *addRibbon* ## *addErrorbar* - diff --git a/vignettes/box-whisker-vignette.Rmd b/vignettes/box-whisker-vignette.Rmd index 5753201c..4edc04e3 100644 --- a/vignettes/box-whisker-vignette.Rmd +++ b/vignettes/box-whisker-vignette.Rmd @@ -1,9 +1,11 @@ --- title: "Box-whisker plots" -author: "OSPSuiteR 2019" -output: rmarkdown::html_vignette +author: "OSPSuiteR 2021" +output: + rmarkdown::html_vignette: + toc: true vignette: > - %\VignetteIndexEntry{box-whisker-vignette} + %\VignetteIndexEntry{Box-whisker plots} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- @@ -11,58 +13,72 @@ vignette: > ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, - comment = "#>" + comment = "#>", + dpi = 300, + fig.align = "center", + out.width = "100%" ) ``` + ```{r setup} require(tlf) ``` -```{r load theme, echo=FALSE} +```{r load-theme, echo=FALSE} vignetteTheme <- loadThemeFromJson(system.file("extdata", "template-theme.json", package = "tlf")) useTheme(vignetteTheme) ``` # 1. Introduction -## 1.1. Objectives -The following vignette aims at documenting and illustrating workflows for producing PK ratio plots using the `tlf`-Library. -## 1.2. Prerequisite +The following vignette aims at documenting and illustrating workflows for producing box-and-whisker plots using the `tlf`-Library. + This vignette focuses boxplot examples. Detailed documentation on typical `tlf` workflow, use of `AgregationSummary`, `DataMapping`, `PlotConfiguration` and `Theme` can be found in `vignette("tlf-workflow")`. # 2. Definition of the boxplot fonctions and classes + ## 2.1. The `plotBoxWhisker` function + The function for plotting box-whiskers is: `plotBoxWhisker`. Basic documentation of the function can be found using: `?plotBoxWhisker`. The typical usage of this function is: `plotBoxWhisker(data, metaData = NULL, dataMapping = NULL, plotConfiguration = NULL)`. The output of the function is a `ggplot` object. ## 2.2. The `BoxWhiskerDataMapping` class + The `dataMapping` from `plotBoxWhisker` requires a `BoxWhiskerDataMapping` class. This class can simply be initialized by `BoxWhiskerDataMapping$new()`, needing `y` variable name input only. -For boxplots with multiple boxes, `x` variable name or/and `fill` groupMapping can be used. The `x` variable is expected to be factor levels. +For boxplots with multiple boxes, `x` variable name and/or `fill` groupMapping can be used. The `x` variable is expected to be factor levels. Beside these common input, it is possible to overwrite the aggregation functions that plot the edges of the box, the whiskers and the oultying data. -- For the box edges `lower`, `middle` and `upper` use respectively the first quartile, median and third quartile (25th, 50th and 75th percentiles). +- For the box edges `lower`, `middle`, and `upper` correspond to the first quartile, median, and the third quartile (25th, 50th, and 75th percentiles), respectively. - For the whiskers, `ymin` and `ymax` use the 5th and 95th percentiles. -- For outliers, points lower than the 25th percentile - 1.5IQR and points higher than 75th percentiles + 1.5IQR (where IQR is the inter-quartile range) are flagged and plotted. +- For outliers, points lower than the 25th percentile - 1.5 x IQR and points higher than 75th percentile + 1.5 x IQR (where IQR is the inter-quartile range) are flagged and plotted. In order to help with the boxplot aggregation functions, a bank of predefined function names is already available in the tlfStatFunctions (as an enum). Consequently, a tree with the available predefined function names will appear when writing `tlfStatFunctions$`: `r paste0("'", names(tlfStatFunctions), "'", sep = ", ", collapse = "")` # 3. Examples + ## 3.1. Data -To illustrate the workflow leading to performing boxplots. The `pkRatioDataExample.RData` example can be loaded from the `data` folder. -It includes the dataset `pkRatioData` and its metaData `pkRatioMetaData`. -```{r load data, results='asis'} +To illustrate the workflow to produce boxplots, let's use the `pkRatioDataExample.RData` example data from the `extdata` folder. + +It includes the dataset `pkRatioData`: + +```{r load-data, results='asis'} # Load example -pkRatioData <- read.csv(system.file("extdata", "test-data.csv", package = "tlf"), stringsAsFactors = FALSE) +pkRatioData <- read.csv( + system.file("extdata", "test-data.csv", package = "tlf"), + stringsAsFactors = FALSE +) # pkRatioData knitr::kable(utils::head(pkRatioData), digits = 2) ``` -```{r load metadata, echo=FALSE} +We will also need to prepare a corresponding metaData `pkRatioMetaData`: + +```{r load-metadata} # Load example pkRatioMetaData <- list(Age = list(dimension = "Age", unit = "yrs"), @@ -74,13 +90,15 @@ pkRatioMetaData <- list(Age = list(dimension = "Age", unit = "") ) ``` -```{r show metadata, results='asis'} + +```{r show-metadata, results='asis'} knitr::kable(data.frame(Variable = c("Age", "Obs", "Pred", "Ratio"), Dimension = c("Age", "Clearance", "Clearance", "Ratio"), Unit = c("yrs", "dL/h/kg", "dL/h/kg", ""))) ``` ## 3.2. Minimal example + In the minimal example, only the basic `y` variable name is indicated. Here, `"Age"` was chosen for the boxplot. ```{r minimal example, fig.height=5, fig.width=7.5} @@ -93,12 +111,13 @@ minBoxplot ``` ## 3.3. Difference `x` vs `fill` input -As explained in section 2, `x` and/or `fill` can be provided. -If providing only `x`, the plot will use the `x` variable for aggregation and the boxplots will be disposed according to `x`. If providing `fill`, the plot will use the `fill` groupMapping for aggregation and the boxplots will be disposed around the same `x` but comparing the color filling. Consequently, the `fill` variable is useful when performing a double comparison. + +In this plot, `x` and/or `fill` can be provided. +If only `x` is provided, the plot will use the `x` variable for aggregation and the boxplots will be displayed according to `x`. If providing `fill`, the plot will use the `fill` groupMapping for aggregation and the boxplots will be displayed around the same `x` but comparing the color filling. Consequently, the `fill` variable is useful when performing a double comparison. In the example below, `"Country"` and `"Sex"` can both be used for comparison of `"Age"`. -```{r difference x vs fill} +```{r difference-x-vs-fill} xPopMap <- BoxWhiskerDataMapping$new(x = "Country", y = "Age") @@ -119,43 +138,52 @@ xSexFillPopMap <- BoxWhiskerDataMapping$new(x = "Sex", fill = "Country") ``` -```{r boxplot country x, fig.height=5, fig.width=7.5, fig.cap="Boxplot mapping Country as x"} +```{r boxplot-country x, fig.height=5, fig.width=7.5, fig.cap="Boxplot mapping Country as x"} plotBoxWhisker(data = pkRatioData, metaData = pkRatioMetaData, dataMapping = xPopMap) ``` -```{r boxplot sex x, fig.height=5, fig.width=7.5, fig.cap="Boxplot mapping Sex as x"} + +Note that the sample from a given country sometimes did not have any individual from one of the sexes. + +```{r boxplot-sex-x, fig.height=5, fig.width=7.5, fig.cap="Boxplot mapping Sex as x"} plotBoxWhisker(data = pkRatioData, metaData = pkRatioMetaData, dataMapping = xSexMap) ``` -```{r boxplot country fill, fig.height=5, fig.width=7.5, fig.cap="Boxplot mapping Country as fill"} + +```{r boxplot-country-fill, fig.height=5, fig.width=7.5, fig.cap="Boxplot mapping Country as fill"} plotBoxWhisker(data = pkRatioData, metaData = pkRatioMetaData, dataMapping = fillPopMap) ``` -```{r boxplot sex fill, fig.height=5, fig.width=7.5, fig.cap="Boxplot mapping Sex as fill"} + +```{r boxplot-sex-fill, fig.height=5, fig.width=7.5, fig.cap="Boxplot mapping Sex as fill"} plotBoxWhisker(data = pkRatioData, metaData = pkRatioMetaData, dataMapping = fillSexMap) ``` -```{r boxplot country x sex fill, fig.height=5, fig.width=7.5, fig.cap="Boxplot mapping Country as x and Sex as fill"} + +```{r boxplot-country-x-sex-fill, fig.height=5, fig.width=7.5, fig.cap="Boxplot mapping Country as x and Sex as fill"} plotBoxWhisker(data = pkRatioData, metaData = pkRatioMetaData, dataMapping = xPopFillSexMap) ``` -```{r boxplot country fill sex x, fig.height=5, fig.width=7.5, fig.cap="Boxplot mapping Sex as x and Country as fill"} + +```{r boxplot-country-fill-sex-x, fig.height=5, fig.width=7.5, fig.cap="Boxplot mapping Sex as x and Country as fill"} plotBoxWhisker(data = pkRatioData, metaData = pkRatioMetaData, dataMapping = xSexFillPopMap) ``` ## 3.4. Boxplot functions -In some cases, 5th and 95th percentiles are not wanted for whiskers for instance when a normal distribution is assumed and mean +/- 1.96 standard deviation would be preferred. -In these cases, it is easy to overwrite the default functions by specifying either using an home made function or directly using predifined functions as suggested in section 2.2. -In the 2 following examples, the boxplot will use the mean for the middle line and mean +/- 1.96 standard deviation for the whiskers: -```{r aggregation functions 1, fig.height=5, fig.width=7.5, fig.cap="Boxplot mapping Country as x, Sex as fill and assuming normal distribution"} +In some cases, displaying 5th and 95th percentiles is not necessary. For instance, when a normal distribution is assumed, mean +/- 1.96 standard deviation would be preferred. +In these cases, it is easy to overwrite the default functions by specifying either using a home made function or directly using predefined functions as suggested in section 2.2. + +In the following examples, the boxplot will use the mean for the middle line and mean +/- 1.96 standard deviation for the whiskers: + +```{r aggregation-functions-1, fig.height=5, fig.width=7.5, fig.cap="Boxplot mapping Country as x, Sex as fill and assuming normal distribution"} normMap <- BoxWhiskerDataMapping$new(x = "Country", y = "Age", @@ -171,7 +199,8 @@ normBoxplot ``` In this example, the boxplot use also mean +/- standard deviation for the box edges -```{r aggregation functions 2, fig.height=5, fig.width=7.5, fig.cap="Boxplot mapping Country as x, Sex as fill and assuming normal distribution"} + +```{r aggregation-functions-2, fig.height=5, fig.width=7.5, fig.cap="Boxplot mapping Country as x, Sex as fill and assuming normal distribution"} normMap2 <- BoxWhiskerDataMapping$new(x = "Country", y = "Age", @@ -188,13 +217,17 @@ normBoxplot2 <- plotBoxWhisker(data = pkRatioData, normBoxplot2 ``` -## 3.5. Outlyier functions -Default outliers are flagged when oustide the range from 25th percentiles - 1.5IQR to 75th percentiles + 1.5IQR as suggested by McGill and implemented by the current boxplot functions from ggplot (`geom_boxplot`). -However, these default can also be overwritten. +**Important**: If you override the defaults this way, please make sure to specify this in the plot annotations as you are basically redefining a boxplot and the reader might not be aware of this and will misinterpret the plot. + +## 3.5. Outlier functions + +Default outliers are flagged when outside the range from 25th percentiles - 1.5 x IQR to 75th percentiles + 1.5 x IQR, as suggested by McGill and implemented by the current boxplot functions from ggplot (`geom_boxplot`). +However, these default can also be overridden. In the following example, outliers will be flagged when values are out of the 10th-90th percentiles, while whiskers will go until these same percentiles: -```{r outlier function, fig.height=5, fig.width=7.5, fig.cap="Boxplot mapping Country as x, Sex as fill and assuming normal distribution"} + +```{r outlier-function, fig.height=5, fig.width=7.5, fig.cap="Boxplot mapping Country as x, Sex as fill and assuming normal distribution"} outlierMap <- BoxWhiskerDataMapping$new(x = "Country", y = "Age", @@ -215,8 +248,9 @@ outlierBoxplot To define the properties of the boxes and points of the box whisker plots, a *BoxWhiskerPlotConfiguration* object can be defined to overwrite the default properties. The *ribbons* and *points* fields will define how the boxes and outliers will be handled. -Using the previous example where country was defined in X and gender as a color. -```{r boxplot update configuration, fig.height=5, fig.width=7.5, fig.cap="Boxplot with updated plot configuration"} +Using the previous example where country was defined in `x` and gender as `color`. + +```{r boxplot-update-configuration, fig.height=5, fig.width=7.5, fig.cap="Boxplot with updated plot configuration"} # Define a PlotConfiguration object using smart mapping boxplotConfiguration <- BoxWhiskerPlotConfiguration$new(data = pkRatioData, metaData = pkRatioMetaData, @@ -224,7 +258,7 @@ boxplotConfiguration <- BoxWhiskerPlotConfiguration$new(data = pkRatioData, # Change the properties of the box colors boxplotConfiguration$ribbons$fill <- c("pink", "dodgerblue") -boxplotConfiguration$ribbons$color <- "black" +boxplotConfiguration$ribbons$color <- "orange" # Change the properties of the points (outliers) boxplotConfiguration$points$size <- 2 @@ -236,20 +270,20 @@ plotBoxWhisker(data = pkRatioData, plotConfiguration = boxplotConfiguration) ``` -# 4. Derive use of `BoxWhiskerDataMapping` +# 4. Further utility of `BoxWhiskerDataMapping` -Since the boxplot datamapping performs an aggregation of the data, it possible to get directly the resulting aggregated statistic as a table using `getBoxWhiskerLimits()` +Since the boxplot data mapping performs an aggregation of the data, it possible to get directly the resulting aggregated statistic as a table using `getBoxWhiskerLimits()`. Similarly, it can be used to flag any values out of a certain range using `getOutliers()`. -For instance, using the example from section 3.5., one can get the following results +For instance, using the example from section 3.5, one can get the following results -```{r box plot measure, results='as.is'} +```{r box-plot-measure, results='asis'} boxplotSummary <- outlierMap$getBoxWhiskerLimits(pkRatioData) knitr::kable(boxplotSummary, digits = 2) ``` -```{r get outliers, results='as.is'} +```{r get-outliers, results='asis'} outliers <- outlierMap$getOutliers(pkRatioData) outliers <- outliers[, c("Age", "minOutlierLimit", "maxOutlierLimit", "minOutliers", "maxOutliers")] diff --git a/vignettes/pk-ratio-vignette.Rmd b/vignettes/pk-ratio-vignette.Rmd index db159f53..64df9e09 100644 --- a/vignettes/pk-ratio-vignette.Rmd +++ b/vignettes/pk-ratio-vignette.Rmd @@ -1,9 +1,11 @@ --- title: "PK Ratio plots" -author: "OSPSuiteR 2019" -output: rmarkdown::html_vignette +author: "OSPSuiteR 2021" +output: + rmarkdown::html_vignette: + toc: true vignette: > - %\VignetteIndexEntry{pk-ratio-vignette} + %\VignetteIndexEntry{PK Ratio plots} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} --- @@ -11,41 +13,51 @@ vignette: > ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, - comment = "#>" + comment = "#>", + dpi = 300, + fig.align = "center", + out.width = "100%" ) ``` + ```{r setup} require(tlf) ``` -```{r load theme, echo=FALSE} +```{r load-theme, echo=FALSE} vignetteTheme <- loadThemeFromJson(system.file("extdata", "template-theme.json", package = "tlf")) useTheme(vignetteTheme) ``` # 1. Introduction -## 1.1. Objectives + The following vignette aims at documenting and illustrating workflows for producing PK ratio plots using the `tlf`-Library. -## 1.2. Prerequisite -This vignette focuses PK ratio plots examples. Detailed documentation on typical `tlf` workflow, use of `AgregationSummary`, `DataMapping`, `PlotConfiguration` and `Theme` can be found in `vignette("tlf-workflow")`. +This vignette focuses PK ratio plots examples. Detailed documentation on typical `tlf` workflow, use of `AgregationSummary`, `DataMapping`, `PlotConfiguration`, and `Theme` can be found in `vignette("tlf-workflow")`. # 2. Illustration of basic PK ratio plots + ## 2.1. Data + The data showed in the sequel is available at the following path: `system.file("extdata", "test-data.csv", package = "tlf")`. -In the code below, the data is loaded and will be named `pkRatioData`. +In the code below, the data is loaded and assigned to `pkRatioData`. -```{r load data, results='asis'} +```{r load-data, results='asis'} # Load example -pkRatioData <- read.csv(system.file("extdata", "test-data.csv", package = "tlf"), stringsAsFactors = FALSE) +pkRatioData <- read.csv( + system.file("extdata", "test-data.csv", package = "tlf"), + stringsAsFactors = FALSE +) # pkRatioData knitr::kable(utils::head(pkRatioData), digits = 2) ``` + + A list of information about `pkRatioData` can be provided through `metaData`. -```{r load metadata, echo=FALSE} +```{r load-metadata, echo=FALSE} # Load example pkRatioMetaData <- list(Age = list(dimension = "Age", unit = "yrs"), @@ -57,19 +69,23 @@ pkRatioMetaData <- list(Age = list(dimension = "Age", unit = "") ) ``` -```{r show metadata, results='asis'} + +```{r show-metadata, results='asis'} knitr::kable(data.frame(Variable = c("Age", "Obs", "Pred", "Ratio"), Dimension = c("Age", "Clearance", "Clearance", "Ratio"), Unit = c("yrs", "dL/h/kg", "dL/h/kg", ""))) ``` -## User interface: *runPKRatioPlot()* + -A user interface is available using the function `runPKRatioPlot()` and provides an easy way to understand and tune the feature of PK Ratio plots. -```{r embedded app, echo=FALSE} -#runPKRatioPlot() -# or knitr::include_app() -``` + + + + + + + + ## 2.2. `plotPKRatio` @@ -79,14 +95,15 @@ The typical usage of this function is: `plotPKRatio(data, metaData = NULL, dataM The output of the function is a `ggplot` object. It can be seen from this usage that only `data` is a necessary input. Default set ups are used for `metaData`, `dataMapping` and `plotConfiguration` within the call of `plotPKRatio`. -For instance, if `dataMapping` is not provided, a smart mapping will be tested checking if data contains a `"x"` and a `"y"` named column. +For instance, if `dataMapping` is not provided, smart mapping will check if data contains `"x"` and `"y"` columns. If the `data` has only two columns not named `"x"` and `"y"`, it will assume the first one should be plot in x-axis and the second in y-axis. -Then, `PKRatioPlotConfiguration` is initialized if not provided, defining a standard configuration with `PK Ratio Plot` as title, the current date as subtitle and using predifned fonts as defined by the current theme. +Then, `PKRatioPlotConfiguration` is initialized if not provided, defining a standard configuration with `PK Ratio Plot` as title, the current date as subtitle and using predefined fonts as defined by the current theme. ## 2.3. Minimal example The minimal example can work using directly the function `plotPKRatio(data = pkRatioData[, c("Age", "Ratio")])`. -```{r minimal example, fig.height=5, fig.width=7.5} + +```{r minimal-example, fig.height=5, fig.width=7.5} plotPKRatio(data = pkRatioData[,c("Age", "Ratio")]) ``` @@ -101,7 +118,8 @@ Some variables can be used to cluster the data. To this end, *PKRatioDataMapping* objects include *GroupMapping* objects that can define how to cluster based on a variable or a data.frame. As illustrated below, most of the time, the direct input of `color` and `shape` is faster to define such objects. Consequently, the following examples are identical: -```{r group mapping} + +```{r group-mapping} # Two-step process colorMapping <- GroupMapping$new(color = "Sex") dataMappingA <- PKRatioDataMapping$new(x = "Age", @@ -120,6 +138,7 @@ print(dataMappingB$groupMapping$color$label) ``` Then, in this example, `plotPKRatio` can use the groupMapping to split the data by "Gender" and associate different colors to each "Gender": + ```{r dataMappingB, fig.height=5, fig.width=7.5} plotPKRatio(data = pkRatioData, dataMapping = dataMappingB) @@ -128,6 +147,7 @@ plotPKRatio(data = pkRatioData, Multiple groupMappings can be performed for PK ratio: data can be regrouped by `color`, `shape` and/or `size`. The next example uses 2 groups in the groupMapping: One group splits "Gender" by `color`, the other splits `shape` by "Amount" and "Compound". + ```{r dataMapping2groups, fig.height=5, fig.width=7.5} dataMapping2groups <- PKRatioDataMapping$new(x = "Age", y = "Ratio", @@ -151,6 +171,7 @@ knitr::kable(groupDataFrame) ``` The `dataMapping` introduced below will split the `color` and `shape` using the data frame. + ```{r dataMappingDF, fig.height=5, fig.width=7.5} dataMappingDF <- PKRatioDataMapping$new(x = "Age", y = "Ratio", @@ -162,9 +183,11 @@ plotPKRatio(data = pkRatioData, ### 2.4.2 PK values defined in `lines` + In PK ratio examples, usually horizontal lines are added allowing to flag values in and out of the [0.67-1.5] as well as [0.5-2.0] ranges. -The value mapping these horizontal lines was predifined as a list: "pkRatioLine1" is 1, "pkRatioLine2" is c(0.67, 1.5) and "pkRatioLine3" is c(0.5, 2). +The value mapping these horizontal lines was predefined as a list: "pkRatioLine1" is 1, "pkRatioLine2" is c(0.67, 1.5) and "pkRatioLine3" is c(0.5, 2). Consequently, for any default `PKRatioDataMapping`, you have: + ```{r linesMapping} linesMapping <- PKRatioDataMapping$new() linesMapping$lines @@ -172,7 +195,8 @@ linesMapping$lines Overwriting these value is possible by updating the value either when initializing the mapping or afterwards. For instance: -```{r linesMapping plot, fig.height=5, fig.width=7.5} + +```{r linesMapping-plot, fig.height=5, fig.width=7.5} linesMapping <- PKRatioDataMapping$new(lines = list(pkRatio1 = 1, pkRatio2 = c(0.2, 5)), x = "Age", y = "Ratio", @@ -201,7 +225,7 @@ knitr::kable(x = PKRatioMeasure, To configure the plot properties, `PKRatioPlotConfiguration` objects can be used. They combine multiple features that set the plot properties. -PK ratio plos consists in *lines* and *points*. -As illustrated in the vignette related to *PlotConfiguration* objects and *Theme*, you can tune the aesthetic maps and their selections. +PK ratio plot consists in *lines* and *points*. +As illustrated in the vignette related to *PlotConfiguration* objects and *Theme*, you can tune the aesthetic maps and their selections (see `vignette("plot-configuration")` and `vignette("theme-maker")`). Colors, shapes and size of the PK ratio scatter points can be tuned in the plotConfiguration *points* field. Likewise, colors, linetype and size of the PK ratio lines can be tuned in the plotConfiguration *lines* field. diff --git a/vignettes/plot-configuration.Rmd b/vignettes/plot-configuration.Rmd index 58405b82..abce56e7 100644 --- a/vignettes/plot-configuration.Rmd +++ b/vignettes/plot-configuration.Rmd @@ -1,9 +1,11 @@ --- title: "Introduction to PlotConfiguration objects" -author: "OSPSuiteR 2019" -output: rmarkdown::html_vignette +author: "OSPSuiteR 2021" +output: + rmarkdown::html_vignette: + toc: true vignette: > - %\VignetteIndexEntry{plot-configuration} + %\VignetteIndexEntry{Introduction to PlotConfiguration objects} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- @@ -11,19 +13,22 @@ vignette: > ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, - comment = "#>" + comment = "#>", + dpi = 300, + fig.align = "center", + out.width = "100%" ) ``` + ```{r setup} require(tlf) ``` -```{r load theme, echo=FALSE} +```{r load-theme, echo=FALSE} vignetteTheme <- loadThemeFromJson(system.file("extdata", "template-theme.json", package = "tlf")) useTheme(vignetteTheme) ``` - This vignette tackles about *PlotConfiguration* objects and their implementation within the `tlf`-library. # 1. Introduction @@ -43,7 +48,7 @@ Each of these properties is managed by a different R6 class object detailed in t - *legend* - *save* -```{r empty configuration plots} +```{r empty-configuration-plots} myConfiguration <- PlotConfiguration$new() # myConfiguration$print() @@ -52,17 +57,19 @@ myConfiguration <- PlotConfiguration$new(title = "my title", # myConfiguration$print() ``` -When a `ggplot` object is initialized using the `tlf` method *initializePlot*, a *plotConfiguration* field of is implanted to the plot object. -The *plotConfiguration* field is class or subclass of *PlotConfiguration* that aims at simplifying and clarifying the plot properties mentioned above. +When a `ggplot` object is initialized using the `tlf` method *initializePlot*, a *plotConfiguration* field is implanted to the plot object. -*PlotConfiguration* objects can also be pass on the method *initializePlot* as shown below: +The ***p**lotConfiguration* field is class or subclass of ***P**lotConfiguration* that aims at simplifying and clarifying the plot properties mentioned above. -```{r empty plots} +*PlotConfiguration* objects can also be directly passed to the method *initializePlot* as shown below: + +```{r empty-plots} emptyPlot <- initializePlot() myEmptyPlot <- initializePlot(myConfiguration) ``` -```{r show empty plots, echo=FALSE, fig.cap="left: emptyPlot; right: myEmptyPlot", fig.width=7.5} + +```{r show-empty-plots, echo=FALSE, fig.cap="left: emptyPlot; right: myEmptyPlot", fig.width=7.5} gridExtra::grid.arrange(emptyPlot, myEmptyPlot, ncol=2) ``` @@ -79,12 +86,14 @@ It defines the label properties of the following plot captions: - ylabel Each field is a *Label* object that associate a text with font properties: -```{r label example} + +```{r label-example} title <- Label$new(text = "This is a title text", font = Font$new(color = "red", size = 12)) ``` -```{r show label example, results='asis', echo=FALSE} + +```{r show-label-example, results='asis', echo=FALSE} knitr::kable(data.frame("text" = title$text, "color" = title$font$color, "size" = title$font$size, @@ -94,13 +103,16 @@ knitr::kable(data.frame("text" = title$text, )) ``` -When initializating a *LabelConfiguration* or *PlotConfiguration* object, *Label* or/and *character* objects can be passed on. +When initializing a *LabelConfiguration* or *PlotConfiguration* object, *Label* and/or *character* objects can be passed on. + *Character* objects will be converted into *Label* objects internally using the current theme. -```{r label configuration} + +```{r label-configuration} myRedPlotLabel <- LabelConfiguration$new(title = Label$new(text = "my title", color = "red")) ``` -```{r show label configuration, results='asis', echo=FALSE} + +```{r show-label-configuration, results='asis', echo=FALSE} knitr::kable( data.frame( Property = c("text", "color", "size", "angle", "fontFace", "fontFamily"), @@ -119,7 +131,8 @@ knitr::kable( ## 2.2. Label configuration in plots The effect of label configuration in plots is straightforward: -```{r label in plot configuration} + +```{r label-in-plot-configuration} plotConfigurationLabel1 <- PlotConfiguration$new(title = "Title", subtitle = "Subtitle", xlabel = "x label", @@ -134,22 +147,25 @@ plotConfigurationLabel2 <- PlotConfiguration$new(title = Label$new(text = "Title pLab2 <- initializePlot(plotConfigurationLabel2) ``` -```{r show label in plot configuration, echo=FALSE, fig.cap="left: pLab1; right: pLab2", fig.width=7.5} + +```{r show-label-in-plot-configuration, echo=FALSE, fig.cap="left: pLab1; right: pLab2", fig.width=7.5} gridExtra::grid.arrange(pLab1, pLab2, ncol=2) ``` ## 2.3. Changing plot labels After creating a plot, it is possible to change its label configuration using the `tlf` method *setPlotLabels*. -The metod requires the plot object and which label property to update. -Similar to the construction of the Label configuration, *Label* or/and *character* objects can be passed on. +The method requires the plot object and which label property to update. + +Similar to the construction of the Label configuration, *Label* and/or *character* objects can be passed on. Using the previous example, *pLab2*, -```{r set new title, fig.width=7.5} + +```{r set-new-title, fig.width=7.5} setPlotLabels(pLab2, title = "new title") ``` -```{r set new redtitle, fig.width=7.5} +```{r set-new-redtitle, fig.width=7.5} setPlotLabels(pLab2, title = Label$new(text = "new title", color = "red")) ``` @@ -158,11 +174,14 @@ setPlotLabels(pLab2, title = Label$new(text = "new title", color = "red")) Smart plot labels are available for initializing *PlotConfiguration* objects. The principle is to provide in advance the *data* that will be used within the plot. As a consequence, three optional arguments can be passed on *PlotConfiguration* initialization: *data*, *metaData* and *dataMapping*. -If no label is specifically defined, the smart configuration will fetch x and y labels within *data* and *metaData* names based on the *dataMapping*. -*dataMapping* uses also smart functions that will check the input data.frame if not specifically initialized and will use variables named "x" and "y" as *x* and *y*. -The 4 examples below illustrates the smart configurations. *pSmart1* and *pSmart2* will turn out the same, while *pSmart3* will use the information from *metaData* to write the x and y labels. *pSmart4* will overwrite the y label and title based on the input. -```{r smart example} +If no label is specifically defined, the smart configuration will fetch `x` and `y` labels within *data* and *metaData* names based on the *dataMapping*. *dataMapping* also uses smart functions that will check the input data frame - if not specifically initialized - and will use variables named "x" and "y" as `x` and `y`. + +The four examples below illustrate the smart configurations: + +*pSmart1* and *pSmart2* will turn out the same, while *pSmart3* will use the information from *metaData* to write the x and y labels. *pSmart4* will overwrite the y label and title based on the input. + +```{r smart-example} time <- seq(0,20, 0.1) myData <- data.frame(x = time, y = 2*cos(time)) @@ -189,17 +208,19 @@ pSmart3 <- initializePlot(smartConfig3) pSmart4 <- initializePlot(smartConfig4) ``` -```{r show smart example 1, echo=FALSE, fig.cap="left: pSmart1; right: pSmart2", fig.width=7.5} +```{r show-smart-example-1, echo=FALSE, fig.cap="left: pSmart1; right: pSmart2", fig.width=7.5} gridExtra::grid.arrange(pSmart1, pSmart2, ncol=2) ``` -```{r show smart example 2, echo=FALSE, fig.cap="left: pSmart3; right: pSmart4", fig.width=7.5} +```{r show-smart-example-2, echo=FALSE, fig.cap="left: pSmart3; right: pSmart4", fig.width=7.5} gridExtra::grid.arrange(pSmart3, pSmart4, ncol=2) ``` -Since all of the `tlf` plots are using internally *initializePlot* if a previous plot is not provided, the smart configurations can directly be used through the plot functions. Consequently, if *scatter1* will provide simple x and y labels, *scatter2* will name these labels after the metaData properties. +Since all of the `tlf` plots are internally using *initializePlot*, if a previous plot is not provided, the smart configurations can directly be used through the plot functions. Consequently, if *scatter1* will provide simple x and y labels, *scatter2* will name these labels after the metaData properties. + As for *scatter3* and *scatter4*, they will use the plotConfiguration defined by *smartConfig4* and lead to the exact same plot. -```{r smart sccatter} + +```{r smart-scatter} scatter1 <- addScatter(data = myData) scatter2 <- addScatter(data = myData, metaData = myMetaData) @@ -211,11 +232,11 @@ scatter4 <- addScatter(data = myData, plotObject = scatter4) ``` -```{r show smart scatter 1, echo=FALSE, fig.cap="left: scatter1; right: scatter2", fig.width=7.5} +```{r show-smart-scatter 1, echo=FALSE, fig.cap="left: scatter1; right: scatter2", fig.width=7.5} gridExtra::grid.arrange(scatter1, scatter2, ncol=2) ``` -```{r show smart scatter 2, echo=FALSE, fig.cap="left: scatter3; right: scatter4", fig.width=7.5} +```{r show-smart-scatter 2, echo=FALSE, fig.cap="left: scatter3; right: scatter4", fig.width=7.5} gridExtra::grid.arrange(scatter3, scatter4, ncol=2) ``` @@ -223,15 +244,27 @@ gridExtra::grid.arrange(scatter3, scatter4, ncol=2) ## 3.1. Background configuration properties -Background configuration defines the configuration of the following Background elements: `plot`, `panel`, `xGrid`, `yGrid`, `xAxis`, `yAxis`, `legendPosition` and `watermark`. -Except for `watermark` and `legendPosition` which are the text of the watermark and the position of the legend defined as an element of `LegendPositions` enum; -background fields are `LineElement` and `BackgroundElement` objects which defines the properties of the background element. +Background configuration defines the configuration of the following Background elements: +- `plot` +- `panel` +- `xGrid` +- `yGrid` +- `xAxis` +- `yAxis` +- `legendPosition` +- `watermark` + +Except for `watermark` and `legendPosition`, which are the text of the watermark and the position of the legend defined as an element of `LegendPositions` enum, background fields are `LineElement` and `BackgroundElement` objects, which define the properties of the background element. + As for all the `PlotConfiguration` inputs, their default values are defined from the current `Theme`, however this default can be overwritten. For instance: -```{r background object, result='as.is'} + +```{r background-object, results='asis'} background <- BackgroundConfiguration$new() +``` +```{r show-background-object, results='asis', echo=FALSE} knitr::kable( data.frame(Property = c("color", "size", "linetype", "fill"), plot = c(background$plot$color, background$plot$size, background$plot$linetype, background$plot$fill), @@ -248,7 +281,8 @@ knitr::kable( ## 3.2. Background configuration in plots The effect of background configuration in plots is also quite straightforward: -```{r background in plot configuration} + +```{r background-in-plot-configuration} plotConfigurationBackground1 <- PlotConfiguration$new(watermark = "My Watermark") pBack1 <- initializePlot(plotConfigurationBackground1) @@ -259,7 +293,7 @@ plotConfigurationBackground1$background$panel <- BackgroundElement$new(fill = "g pBack2 <- initializePlot(plotConfigurationBackground1) ``` -```{r show background in plot configuration, echo=FALSE, fig.cap="left: pBack1; right: pBack2", fig.width=7.5} +```{r show-background-in-plot-configuration, echo=FALSE, fig.cap="left: pBack1; right: pBack2", fig.width=7.5} gridExtra::grid.arrange(pBack1, pBack2, ncol=2) ``` @@ -267,49 +301,58 @@ gridExtra::grid.arrange(pBack1, pBack2, ncol=2) After creating a plot, it is possible to change its background configuration using the following `tlf` methods: -- *setBackground*, *setBackgroundPanelArea* and *setBackgroundPlotArea* +- *setBackground*, *setBackgroundPanelArea*, and *setBackgroundPlotArea* - *setGrid*, *setXGrid* and *setYGrid* - *setWatermark* ### 3.3.1. Set Background -The methods *setBackground*, *setBackgroundPanelArea* and *setBackgroundPlotArea* require the plot object and which properties to update. +The methods *setBackground*, *setBackgroundPanelArea*, and *setBackgroundPlotArea* require the plot object and which properties to update. Using the previous example, *scatter1*, -```{r set plot background 1, fig.width=7.5} + +```{r set-plot-background-1, fig.width=7.5} setBackground(scatter1, fill = "lemonchiffon", color = "darkgreen", linetype = "solid") ``` -```{r set panel background 1, fig.width=7.5} +```{r set-panel-background-1, fig.width=7.5} setBackgroundPanelArea(scatter1, fill = "lemonchiffon", color = "darkgreen", linetype = "solid") ``` ### 3.3.2. Set Grid -The methods *setGrid*, *setXGrid* and *setYGrid* are very similar and requires the plot object and which grid properties to update. +The methods *setGrid*, *setXGrid*, and *setYGrid* are very similar and require the plot object and the grid properties to be updated. Using the previous example *scatter1*: -```{r set plot grid 1, fig.width=7.5} + +```{r set-plot-grid, fig.width=7.5} setGrid(scatter1, linetype = "blank") ``` -```{r set plot y grid, fig.width=7.5} +```{r set-plot-y-grid, fig.width=7.5} setXGrid(scatter1, linetype = "blank") ``` +```{r set-plot-x-grid, fig.width=7.5} +setYGrid(scatter1, linetype = "blank") +``` + ### 3.3.3. Set Watermark -The metod *setWatermark* requires the plot object, the watermark and its properties to update. -Included in the properties, *alpha* is a value between 0 and 1 managing transparency of the watermark. -The closer to 0, the more transparent the watermark will be. The closer to 1, the more opaque the watermark will be. -The property *angle*, is the angle of the watermark in degrees. +The *setWatermark* method requires the plot object, the watermark, and its properties to update. + +Among its properties, the following are the few important ones: + +- The property *alpha* is a value between 0 and 1 managing transparency of the watermark. The closer to 0, the more transparent the watermark will be. The closer to 1, the more opaque the watermark will be. +- The property *angle*, is the angle of the watermark in degrees. Using the previous example *scatter1*: -```{r set watermark 1, fig.width=7.5} + +```{r set-watermark-1, fig.width=7.5} setWatermark(scatter1, watermark = "Hello watermark !!") ``` -```{r set watermark 2, fig.width=7.5} +```{r set-watermark-2, fig.width=7.5} setWatermark(scatter1, watermark = "Confidential", angle = 45, size = 6, color = "firebrick") ``` @@ -329,14 +372,14 @@ The property *scale* is a character string corresponding the axis scale. Available scales are *`r paste0(c('"', paste0(Scaling, collapse = '", "'), '"'), collapse="")`* and can be accessed using the enum *Scaling*. The property *limits* is a vector defining the range of the axis. -Regarding ticks and ticklabels their values are directly be passed on and managed by `ggplot2`. +Regarding ticks and ticklabels, their values are directly be passed on and managed by `ggplot2`. The value *"default"* will leave the management of the limits to R. The properties *ticks* and *ticklabels* are vectors defining the plot ticks and their labels. These vectors are required to have the same length. The value *"default"* will leave the management of the limits to R. -When initializating a *XAxisConfiguration*, *YAxisConfiguration* or *PlotConfiguration* objects, the axis properties can be passed on. +When initializing a *XAxisConfiguration*, *YAxisConfiguration*, or *PlotConfiguration* objects, the axis properties can be passed on. -```{r define axis} +```{r define-axis} myAxisConfiguration <- XAxisConfiguration$new() myAxisConfiguration$scale @@ -349,11 +392,12 @@ myAxisConfiguration$ticklabels The methods *setXAxis* and *setYAxis* require the plot object, and the axis properties to update. Using the previous example, *scatter1*: -```{r set x axis, fig.width=7.5} + +```{r set-x-axis, fig.width=7.5} setXAxis(scatter1, limits = c(0.5, 20), scale = Scaling$sqrt) ``` -```{r set x axis ticks, fig.width=7.5} +```{r set-x-axis-ticks, fig.width=7.5} setXAxis(scatter1, limits = c(0, 6*pi), ticks = seq(0, 6*pi, pi), @@ -375,7 +419,7 @@ The property *position* is a character string corresponding the legend position. Available legend positions are *`r paste0(c('"', paste0(LegendPositions, collapse = '", "'), '"'), collapse="")`* and can be accessed using the enum *LegendPositions*. The property *caption* is a data.frame defining the caption properties of the legend. -```{r legend configuration} +```{r legend-configuration} myLegend <- LegendConfiguration$new(position = LegendPositions$insideTopRight) ``` @@ -384,7 +428,8 @@ myLegend <- LegendConfiguration$new(position = LegendPositions$insideTopRight) Legend position can be modified using the function `setLegendPosition` The methods *setLegendPosition* requires the plot object, and the position as defined by the elements of the enum *LegendPositions* Using the previous example, *scatter1*: -```{r legend position, fig.width=7.5} + +```{r legend-position, fig.width=7.5} setLegendPosition(scatter1, LegendPositions$insideTopLeft) ``` @@ -403,7 +448,7 @@ To call for the shiny app, users only needed to run the function `runThemeMaker( The function `exportPlotConfigurationCode(plotConfiguration)` creates character strings corresponding to commented R code that allows you to re-create a PlotConfiguration object. -```{r export configuration} +```{r export-configuration} # Create and export a plot confiugration plotConfigurationToExport1 <- PlotConfiguration$new() exportPlotConfigurationCode(plotConfigurationToExport1) diff --git a/vignettes/plot-maker.Rmd b/vignettes/plot-maker.Rmd index 24a3b57e..9b28d14b 100644 --- a/vignettes/plot-maker.Rmd +++ b/vignettes/plot-maker.Rmd @@ -1,7 +1,11 @@ --- title: "plot-maker" -author: "OSPSuiteR 2019" -output: rmarkdown::html_vignette +author: "OSPSuiteR 2021" +output: + rmarkdown::html_vignette: + fig.align: 'center' + dpi: 300 + toc: true vignette: > %\VignetteIndexEntry{plot-maker} %\VignetteEngine{knitr::rmarkdown} diff --git a/vignettes/theme-maker.Rmd b/vignettes/theme-maker.Rmd index 7065f763..ed71af32 100644 --- a/vignettes/theme-maker.Rmd +++ b/vignettes/theme-maker.Rmd @@ -1,7 +1,9 @@ --- title: "theme-maker" -author: "OSPSuiteR 2019" -output: rmarkdown::html_vignette +author: "OSPSuiteR 2021" +output: + rmarkdown::html_vignette: + toc: true vignette: > %\VignetteIndexEntry{theme-maker} %\VignetteEngine{knitr::rmarkdown} @@ -11,7 +13,11 @@ vignette: > ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, - comment = "#>" + comment = "#>", + dpi = 300, + fig.align = "center", + out.width = "100%", + echo = FALSE ) ``` @@ -21,15 +27,15 @@ require(tlf) # 1. Introduction -The aim of this vignette is to document how to create, update and save `Theme` objects using the `tlf` user interface (uI) called by **`runThemeMaker()`**. +The aim of this vignette is to document how to create, update, and save `Theme` objects using the `tlf` user interface (UI) called by **`runThemeMaker()`**. -`Theme` objects define the default values and methods of `PlotConfiguration` objects which describe the properties of a plot (such as colors, fonts...). +`Theme` objects define the default values and methods of `PlotConfiguration` objects, which themselves describe the properties of a plot (such as colors, fonts, etc.). # 2. How to start Use the function `runThemeMaker()` to start the theme-maker User Interface. The function will load `shiny` required for the UI and set the current theme defined by the UI. -```{r start-theme-maker, out.width="100%", include=TRUE, fig.align="center", echo=FALSE} +```{r start-theme-maker} knitr::include_graphics("theme-maker/start-theme-maker.png") ``` @@ -37,70 +43,70 @@ knitr::include_graphics("theme-maker/start-theme-maker.png") On the upper left side of the UI, a navigation bar indicates the main properties that can be updated in the theme: **Labels**, **Background**, **Axes**, **Legend**, **Aesthetic Maps** and **Plot Configurations**. -In the **Labels** navigation bar (already available when starting the UI), font properties of the most common labels are available. For font properties of ticks and legend are available in the properties **Axes** anbd **Legend**. +In the **Labels** navigation bar (already available when starting the UI), font properties of the most common labels are available. The font properties of ticks and legend are available in the properties **Axes** and **Legend**. Note that *Color* properties use a predefined list of available colors as illustrated in the figure below, however, users can type and add their own colors (e.g. hex colors). -```{r theme-labels, out.width="100%", include=TRUE, fig.align="center", echo=FALSE} +```{r theme-labels} knitr::include_graphics("theme-maker/labels.png") ``` Properties of the watermark are available in the **Labels** navigation bar, and include the field *Content* which allows to define the content of the watermark (in this example the content is *template*). -The **Background** navigation bar includes the properties of the colors, sizes and linetypes for each background elements (illustrated below). +The **Background** navigation bar includes the properties of the colors, sizes, and linetypes for each background elements (illustrated below). -```{r theme-background, out.width="100%", include=TRUE, fig.align="center", echo=FALSE} +```{r theme-background} knitr::include_graphics("theme-maker/background.png") ``` The **Axes** navigation bar includes the properties of the axes lines (colors, sizes and linetypes) as well as the font properties of their ticks (illustrated below). -```{r theme-axes, out.width="100%", include=TRUE, fig.align="center", echo=FALSE} +```{r theme-axes} knitr::include_graphics("theme-maker/axes.png") ``` -The **Legend** navigation bar includes the properties of the position, fonts and background of the legend (illustrated below). +The **Legend** navigation bar includes the properties of the position, fonts, and background of the legend (illustrated below). -```{r theme-legend, out.width="100%", include=TRUE, fig.align="center", echo=FALSE} +```{r theme-legend} knitr::include_graphics("theme-maker/legend.png") ``` The **Aesthetic Maps** navigation bar defines the maps of aesthetic properties (color, fill, linetype, shape, size and alpha). -Such maps can be used by `PlotConfiguration` objects to define how they will plot **points**, **lines**, **ribbons** and **errorbars**. +Such maps can be used by `PlotConfiguration` objects to define how they will plot **points**, **lines**, **ribbons**, and **errorbars**. Consequently, these properties are paired with the **Plot Configurations** navigation bar. -The **Plot Configurations** navigation bar defines the default aesthetic selection properties for each type of `PlotConfiguration` objects: it defines how to plot **points**, **lines**, **ribbons** and **errorbars** for each type of atom or molecule plot available in the `tlf` package. +The **Plot Configurations** navigation bar defines the default aesthetic selection properties for each type of `PlotConfiguration` objects: it defines how to plot **points**, **lines**, **ribbons**, and **errorbars** for each type of atom or molecule plot available in the `tlf` package. -To illustrate these propperties, the example below will update these properties for a PK ratio plots +To illustrate these properties, the example below will update these properties for a PK ratio plots First, select *plotPKRatio* in the list of sample plots to check the current features of the theme. The list of sample plots available in the UI corresponds to all the atom and molecule plot functions defined in the `tlf` package. -```{r sample-plots, out.width="100%", include=TRUE, fig.align="center", echo=FALSE} +```{r sample-plots} knitr::include_graphics("theme-maker/sample-plots.png") ``` Then, the **Aesthetic Maps** indicates for each aesthetic property pairs of rank-value for the aesthetic map. The current color map defines *30078D7* (blue color). -```{r aes-map, out.width="100%", include=TRUE, fig.align="center", echo=FALSE} +```{r aes-map} knitr::include_graphics("theme-maker/aes-map.png") ``` The values can be changed as illustrated below where color ranked 1 was set as *salmon* and color ranked 2 was set as *dodgerblue*. -```{r aes-map-set, out.width="100%", include=TRUE, fig.align="center", echo=FALSE} +```{r aes-map-set} knitr::include_graphics("theme-maker/aes-map-set.png") ``` -On the **Plot Configurations** navigation bar, select the *plotPKRatio* (figure below). Three selection keys are available for this plot as it includes points, lines and optionally errorbars. +On the **Plot Configurations** navigation bar, select the *plotPKRatio* (figure below). Three selection keys are available for this plot as it includes points, lines and optionally error bars. The current selection key is **reset** which resets and uses in sequence the values of the color map. -```{r pk-ratio-color, out.width="100%", include=TRUE, fig.align="center", echo=FALSE} +```{r pk-ratio-color} knitr::include_graphics("theme-maker/pk-ratio-color.png") ``` -The example below updates how the lines are drawn in the PK ratio plots. Currently, the selection key is defined as **Other** and the corresponding value has *longdash* which is translated as the PK ratio lines are all plotted as long dashes +The example below updates how the lines are drawn in the PK ratio plots. Currently, the selection key is defined as **Other** and the corresponding value has *longdash* which is translated as the PK ratio lines are all plotted as long dashes: -```{r pk-ratio-linetype, out.width="100%", include=TRUE, fig.align="center", echo=FALSE} +```{r pk-ratio-linetype} knitr::include_graphics("theme-maker/pk-ratio-linetype.png") ``` @@ -112,30 +118,30 @@ To update how lines are drawn in PK ratio plots, you can use a default linetype - **reset** will select the next values of the map every time a line is added but resetting the count before the call of the plot function - **other** allows you to specify a user defined lineytpe(s) not related to the map -```{r pk-ratio-selection-key, out.width="100%", include=TRUE, fig.align="center", echo=FALSE} +```{r pk-ratio-selection-key} knitr::include_graphics("theme-maker/pk-ratio-selection-key.png") ``` By selecting *next*, the PK ratio plot uses the next value in the linetype map every time a line is added. In this example, this leads to draw the ratio of 1 as a solid line, the ratio of 1.5 as a longdash line and the ratio of 2 as a dotted line. -```{r pk-ratio-linetype-next, out.width="100%", include=TRUE, fig.align="center", echo=FALSE} +```{r pk-ratio-linetype-next} knitr::include_graphics("theme-maker/pk-ratio-linetype-next.png") ``` # 4. How to export and re-use a theme -The theme-maker UI allows an easy way to save your theme properties as a json file, which can be reloaded whenever suited using the function `loadThemeFromJson(jsonFile)` and used as the current theme with the function `useTheme(theme)`. +The theme-maker UI allows an easy way to save your theme properties as a json file. This file can be reloaded when needed using the function `loadThemeFromJson(jsonFile)` and can be used as the current theme with the function `useTheme(theme)`. -To save your current theme using the UI, click on **Download theme .json** as illustrated on the figure below and indicate the location/name of the file in which the theme will be saved. -Please be cautious to include the extension **.json** at the end of the filename. +To save your current theme using the UI, click on **Download theme .json** as illustrated in the figure below and indicate the location/name for saving the theme file. +Please remember to specify the **.json** file extension while saving the theme to a file. -```{r save-theme, out.width="100%", include=TRUE, fig.align="center", echo=FALSE} +```{r save-theme} knitr::include_graphics("theme-maker/save-theme.png") ``` -The UI also allows you to load a previously saved theme from its json file using the button **Load a Theme from Json** as illustrated in the figure below. +The UI also allows you to load a previously saved theme in `.json` file using the button **Load a Theme from Json** as illustrated in the figure below. -```{r use-saved-theme, out.width="100%", include=TRUE, fig.align="center", echo=FALSE} +```{r use-saved-theme} knitr::include_graphics("theme-maker/use-saved-theme.png") -``` \ No newline at end of file +``` diff --git a/vignettes/tlf-workflow.Rmd b/vignettes/tlf-workflow.Rmd index eaae7fe5..c2c31077 100644 --- a/vignettes/tlf-workflow.Rmd +++ b/vignettes/tlf-workflow.Rmd @@ -1,9 +1,11 @@ --- -title: "Introduction to tlf workflows" -author: "OSPSuiteR 2019" -output: rmarkdown::html_vignette +title: "Introduction to tlf-based workflow" +author: "OSPSuiteR 2021" +output: + rmarkdown::html_vignette: + toc: true vignette: > - %\VignetteIndexEntry{tlf-workflow} + %\VignetteIndexEntry{Introduction to tlf-based workflow} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- @@ -11,31 +13,38 @@ vignette: > ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, - comment = "#>" + comment = "#>", + dpi = 300, + fig.align = "center", + out.width = "100%" ) ``` + ```{r setup} require(tlf) ``` -```{r load theme, echo=FALSE} +```{r load-theme, echo=FALSE} vignetteTheme <- loadThemeFromJson(system.file("extdata", "template-theme.json", package = "tlf")) useTheme(vignetteTheme) ``` # 1. Introduction + ## 1.1. Objectives + The aim of this vignette is to document and illustrate the typical workflow needed for the production of plots using the `tlf`-library. ## 1.2. Libraries -The main purpose of the `tlf`-library is to standardized the production of `ggplot` objects from data output by the `OSPSuiteR`. + +The main purpose of the `tlf`-library is to standardize the production of `ggplot` objects from data produced by the `OSPSuiteR` package. As such, `tlf`-library requires that the `ggplot2` package be installed. ## 1.3. `tlf` typical workflow -The suggested workflow for performing any kind of plot with the `tlf`-library is illustrated in the figure below. -```{r workflow illustration, out.width="100%", include=TRUE, fig.align="center", echo=FALSE} -# echo=FALSE prints only code chunk output +The suggested workflow for producing any kind of plot with the `tlf`-library is illustrated in the figure below. + +```{r workflow-illustration, out.width="100%", fig.align="center", echo=FALSE} knitr::include_graphics("workflow.png") ``` @@ -49,19 +58,20 @@ The standard workflow then proceeds as follows: **Step 3 - Data mapping.** Use the `DataMapping` class to select the independent and dependent variables of the processed data as well as the aesthetics that will be used to differentiate between the groupings of the data that were specified in step 2. -**Step 4 - Plot configuration** Set the `PlotConfiguration` object which will define settings of the plot such as axis labeling, font sizes and watermarks. +**Step 4 - Plot configuration** Set the `PlotConfiguration` object which will define settings of the plot such as axis labeling, font sizes, and watermarks. **Step 5 - Plot generation** Create a `ggplot` object from the above classes using the dedicated plotting function. -Steps 1, 2, 3 and 4 are not mandatory. If not implemented, `tlf`-libray uses default settings in lieu of the objects that are otherwise created in these optional steps. In addition, the `PlotConfiguration` object and the `DataMapping` object can be created independently. -Sections 2 to 4 will focus on `AggregationSummary`, `DataMapping` and `PlotConfiguration`. +Steps 1, 2, 3, and 4 are not mandatory. If they are skipped, `tlf`-library uses default settings in lieu of the objects created otherwise. Additionally, the `PlotConfiguration` object and the `DataMapping` object can be created independently. +Sections 2 to 4 will focus on `AggregationSummary`, `DataMapping`, and `PlotConfiguration`. ## 1.4. Naming Conventions + In this package, it was chosen to use specific names for functions and classes referring to specific plots. The naming convention for classes is `` and for function ``. Below presents the table of specific classes and functions that are created using this convention: -```{r naming convention, echo = FALSE, results='asis'} +```{r naming-convention, echo = FALSE, results='asis'} # This small script gives a fast way to introduce the nomenclature of the classes and functions plotNames <- c("PKRatio", "DDIRatio", "IndividualIdProfile", "ObsVsPred", "Histogram", "BoxWhisker") classesNames <- c("DataMapping", "PlotConfiguration") @@ -80,26 +90,37 @@ knitr::kable(conventionTable) ## 2.1. Data format The workflow assumes that the data to be plotted has been gathered in the form of a [*tidy*](https://cran.r-project.org/web/packages/tidyr/vignettes/tidy-data.html) dataframe. -In a tidy format dataframe, each *measurement*, such as a simulation result or experimental observation, is described entirely in one row. -The columns of the data.frame are limited to no more than the *independent variable* columns of the measurement (for example, *time* and *IndividualId*) and the *dependent variable* columns (in this case *Organism|VenousBlood|Volume*), which hold the value of the measurement. +In a tidy format dataframe, each *measurement*, such as a simulation result or an experimental observation, is described entirely in one row. +The columns of the data.frame are limited to no more than the *independent variable* columns of the measurement (for example, *time* and *IndividualId*) and the *dependent variable* columns (in this case *Organism|VenousBlood|Volume*), which hold the value of the measurement. Since no additional columns are allowed, two dependent variables that have differing sets of independent variables should each have their own tidy dataframes. -In the sequel, we will use a dataset derived from the `OSPSuiteR` package: `testData`. +In the sequel, we will use a dataset derived from the `OSPSuiteR` package: `testData`. Let's look at a few rows to get a sense of the data: + +```{r get-test-data, echo=FALSE, results='asis'} +testData <- read.csv( + system.file("extdata", "ospsuite-data.csv", package = "tlf"), + check.names = FALSE, + stringsAsFactors = FALSE + ) -```{r get test data, echo=FALSE, results='asis'} -testData <- read.csv(system.file("extdata", "ospsuite-data.csv", package = "tlf"), check.names = FALSE, stringsAsFactors = FALSE) knitr::kable(head(testData[,1:6])) #For aesthetics of the table align='c', digits =2) ``` ## 2.2. MetaData -A `metaData` variable associated with the data can be used to define additional information such as the `dimension` and `unit` of each column in the `data.frame`. The lower limit of quantitiation of a IndividualId profile can also be stored in the `metaData`. The format of metaData is currently expected to be a list on each variable of lists showing unit and dimension. +A `metaData` variable associated with the data can be used to define additional information such as the `dimension` and `unit` of each column in the `data.frame`. The lower limit of quantification of a IndividualId profile can also be stored in the `metaData`. The format of metaData is currently expected to be a list on each variable of lists showing unit and dimension. + +```{r get-test-metadata, results='asis', echo=FALSE} +metaDataTable <- read.csv( + system.file("extdata", "ospsuite-metadata.csv", package = "tlf"), + check.names = FALSE, + stringsAsFactors = FALSE + ) -```{r get test metadata, results='asis', echo=FALSE} -metaDataTable <- read.csv(system.file("extdata", "ospsuite-metadata.csv", package = "tlf"), check.names = FALSE, stringsAsFactors = FALSE) knitr::kable(metaDataTable) ``` -```{r get test metadata as list, include=FALSE} + +```{r get-test-metadata-as-list, include=FALSE} testMetaData <- list() for(variableIndex in 1:nrow(metaDataTable)){ testMetaData[[metaDataTable$Variable[variableIndex]]] <- list(dimension = metaDataTable$Dimension[variableIndex], @@ -109,11 +130,11 @@ for(variableIndex in 1:nrow(metaDataTable)){ ## 2.3. Aggregation -A common processing of the data is its aggregation. The aggregation consists in splitting the data into subsets, then computes summary statistics for each, and returns the result in a convenient form. +A common processing of the data is its aggregation. The aggregation consists in splitting the data into subsets, then computing summary statistics for each, and returning the result in a convenient form. Visual predictive checks are typical plots where such method is useful. The `AggregationSummary` class is a helper class that simplifies the use of aggregation methods on the data. -The `R6` class `AggregationSummary` automates the computation of multiple summary statistics of the raw data that is output by **Step 0**. The output of this optional data pre-processing step is a dataframe with a column for each summary statistic. This dataframe can be input into the subsequent steps of the workflow. The user also has the option of generating `metaData` for each of the summary statistics evaluated. +The `R6` class `AggregationSummary` automates the computation of multiple summary statistics of the raw data produced at **Step 0**. The output of this optional data pre-processing step is a dataframe with a column for each summary statistic. This dataframe can be input into the subsequent steps of the workflow. The user also has the option of generating `metaData` for each of the summary statistics evaluated. To illustrate the functions of this class for the example of the dataframe `testData`, let's suppose that for each individual in the *IndividualId* column, the *minimum* and the *mean* value of the simulated *Organism|VenousBlood|Volume* column is to be computed for each gender in the *Gender* column. The `AggregationSummary` class works in 3 steps: @@ -121,11 +142,11 @@ To illustrate the functions of this class for the example of the dataframe `test 2. For each value of the independent variable `xColumnNames`, the rows of the dataframe are aggregated into groups defined by unique combinations of the elements in the grouping variable columns `groupingColumnNames`. -3. Summary statistics (in this case, the `minimum` and the `mean`) for the `yColumnNames` variables in each group are evaluated. The functions for computing the the summary statistics are specified when initializing an `AggregationSummary`, via `aggregationFunctionsVector`. User-specified descriptive names of these functions are supplied via the vector of strings named `aggregationFunctionNames`. The units and dimensions of the outputs of these functions are supplied via the vectors of strings named `aggregationUnitsVector` and `aggregationDimensionsVector`, respectively. +3. Summary statistics (in this case, the `minimum` and the `mean`) for the `yColumnNames` variables in each group are evaluated. The functions for computing the the summary statistics are specified when initializing an `AggregationSummary`, via `aggregationFunctionsVector`. User-specified descriptive names of these functions are supplied via the vector of strings named `aggregationFunctionNames`. The units and dimensions of the outputs of these functions are supplied via the vectors of strings named `aggregationUnitsVector` and `aggregationDimensionsVector`, respectively. -For this example, the `AggregationSummary` object `aggSummary` is instatiated as follows: +For this example, the `AggregationSummary` object `aggSummary` is instantiated as follows: -```{r aggregate example, results='asis'} +```{r aggregate-example, results='asis'} aggSummary <- AggregationSummary$new(data = testData , metaData = testMetaData, xColumnNames = "IndividualId", @@ -139,15 +160,19 @@ aggSummary <- AggregationSummary$new(data = testData , "Volume")) ``` -The dataframe that holds the summary statistics of the aggregated rows is stored in the `dfHelper` property of the resulting `aggSummary` object. Since two functions (`min` and `mean`) were specified in `aggregationFunctionsVector`, the dataframe `aggSummary$dfHelper` has, in addition to the `xColumnNames`and `groupingColumnNames` columns, two additional columns named `Simulated Min` and `Simulated Mean`, which were the names specified in `aggregationFunctionNames`. +The dataframe that holds the summary statistics of the aggregated rows is stored in the `dfHelper` property of the resulting `aggSummary` object. Since two functions (`min` and `mean`) were specified in `aggregationFunctionsVector`, the dataframe `aggSummary$dfHelper` has, in addition to the `xColumnNames`and `groupingColumnNames` columns, two additional columns named `Simulated Min` and `Simulated Mean`, which were the names specified in `aggregationFunctionNames`. -```{r show aggregation summary, echo=FALSE, results='asis'} +```{r eval=FALSE} +head(aggSummary$dfHelper) +``` + +```{r show-aggregation-summary, echo=FALSE, results='asis'} knitr::kable(head(aggSummary$dfHelper, digits=2)) ``` The `metaData` corresponding to the columns of the resulting dataframes are lists that are stored together in a list with the `metaData` of the `xColumnNames`and `groupingColumnNames` columns. The `metaData` for the new `aggSummary$dfHelper` dataframe is stored as the `metaDataHelper` property of the `aggSummary` object. For this example, the two `metaData` lists corresponding to the `Simulated Min` and `Simulated Mean` columns are also are labeled `Simulated Min` and `Simulated Mean`. The contents of the list `aggSummary$metaDataHelper` are: -```{r show meta data of aggregation, results='asis'} +```{r show-meta-data-of-aggregation, results='asis'} # Currently issue with metaData of Gender aggSummary$metaDataHelper[[2]] <- NULL aggMetaData <- data.frame("unit" = sapply(aggSummary$metaDataHelper, function(x){x$unit}), @@ -156,31 +181,36 @@ aggMetaData <- data.frame("unit" = sapply(aggSummary$metaDataHelper, function(x) knitr::kable(aggMetaData) ``` -# 3. Mapping and grouping of data: `DataMapping` class. +# 3. Mapping and grouping of data: `DataMapping` class -The role of the `DataMapping` class is to provide a user-friendly interface to indicate what data should plotted. -In most cases, this class needs to be initiliazed to map what variable is `x`, `y` and someIndividualIds what variable(s) will group the data. -Thus, the most common input are `x` and `y`, however, for more advanced plots input such as `groupMapping` may be used often. +The role of the `DataMapping` class is to provide a user-friendly interface to indicate what data should be plotted. +In most cases, this class needs to be initialized to map what variables are `x` and `y`, and which IndividualIds variable(s) will group the data. +Thus, the most common input are `x` and `y`; however, for more advanced plots, input such as `groupMapping` may be used often. For advanced plots, subclasses are derived from `DataMapping`, they use unique input and default related to the advanced plot to make it easier to use them. ## 3.1. GroupMapping + ### 3.1.1. Grouping class -An `R6` class called `Grouping` can be used to group the data into subsets that, in the final plots, are to be distinguished both aesthetically and in legend captions. In addition, these subsets can be listed under descriptive legend titles. +An `R6` class called `Grouping` can be used to group the data into subsets that, in the final plots, are to be distinguished both aesthetically and in legend captions. In addition, these subsets can be listed under descriptive legend titles. As an example, a `Grouping` object called `grouping1` can be used to specify that the data in a *tidy* data.frame should be grouped by both "Compound" and "Dose": -```{r grouping 2 variables, results='asis'} + +```{r grouping-2-variables, results='asis'} # Grouping by variable names: grouping1 <- Grouping$new(c("Compound","Dose")) ``` -With this minimal input, a legend associated with this grouping will have the default title "Compound-Dose". On the other hand, a custom title for this grouping and its legend can be supplied by the user with the optional `label` input: -```{r grouping 2 variable with label, results='asis'} + +With this minimal input, a legend associated with this grouping will have the default title "Compound-Dose". On the other hand, a custom title for this grouping and its legend can be supplied by the user with the optional `label` input: + +```{r grouping-2-variable-with-label, results='asis'} # Grouping by variable names and overwriting the default label: grouping2 <- Grouping$new(group = c("Compound","Dose"), label = "Compound & Dose") ``` -In the above two examples, default captions are constructed by hyphenating the compound type and the dose amount for each row. Alternatively, the captions can be customized by the user by supplying a dataframe with the custom captions to the `group` input of the `Grouping` object constructor. The format of this dataframe is such that the rightmost column contains the desired captions, the name of this rightmost column is the default legend title for this grouping, and the remaining columns define the combinations of row entries that are to receive each caption in the rightmost column. To illustrate this method, the following dataframe `mappingDataFrame` is used to assign captions based on entries in the "Dose" and "Compound" columns. For example the caption "6mg of Aspirin" is assigned to any row in which the "Dose" entry is 6 and the "Compound" entry is "Aspirin". -```{r grouping using data.frame, results='asis'} +In the above two examples, default captions are constructed by hyphenating the compound type and the dose amount for each row. Alternatively, the captions can be customized by the user by supplying a dataframe with the custom captions to the `group` input of the `Grouping` object constructor. The format of this dataframe is such that the rightmost column contains the desired captions, the name of this rightmost column is the default legend title for this grouping, and the remaining columns define the combinations of row entries that are to receive each caption in the rightmost column. To illustrate this method, the following dataframe `mappingDataFrame` is used to assign captions based on entries in the "Dose" and "Compound" columns. For example, the caption "6mg of Aspirin" is assigned to any row in which the "Dose" entry is 6 and the "Compound" entry is "Aspirin". + +```{r grouping-using-dataframe, results='asis'} # Grouping using a data.frame: mappingDataFrame <- data.frame(Compound = c("Aspirin","Aspirin","Sugar","Sugar"), Dose = c(6,3,6,3), @@ -193,10 +223,11 @@ knitr::kable(mappingDataFrame) grouping3 <- Grouping$new(group = mappingDataFrame) ``` -The default title of the legend that results from this grouping is the name of the rightmost column, which is "Compound & Dose". Note that the `check.names` option should be set to `FALSE` when creating the dataframe `mappingDataFrame` since the legend title contains spaces in this instance. This legend title can be overridden to be another string by using the `label` input of the object constructor, as in the case of `grouping2` above. +The default title of the legend that results from this grouping is the name of the rightmost column, which is "Compound & Dose". Note that the `check.names` option should be set to `FALSE` when creating the dataframe `mappingDataFrame`, since the legend title contains spaces in this instance. This legend title can be overridden to be another string by using the `label` input of the object constructor, as in the case of `grouping2` above. + +The three `Grouping` objects, `grouping1`, `grouping2`, and `grouping3` respectively yield the last three columns of the following dataframe: -The three `Grouping` objects, `grouping1`, `grouping2` and `grouping3` respectively yield the last three columns of the following dataframe: -```{r grouping show captions, results='asis'} +```{r grouping-show-captions, results='asis'} # Apply the mapping to get the grouping captions: groupingsDataFrame <- data.frame(testData$IndividualId, testData$Dose, @@ -213,21 +244,24 @@ knitr::kable(groupingsDataFrame) ``` A dataframe can also be used to create a `Grouping` object that subsets the data based on whether a numeric grouping variable satisfies an specific inequality. For example, individuals in `testData` can be grouped according to whether or not their age exceeds 6 years by first defining the following dataframe: -```{r binning age, results='asis'} + +```{r binning-age, results='asis'} # Grouping using a data.frame: binningDataFrame <- data.frame(Age = I( list(c(0,6),c(7,100)) ), "Age Range" = c("Age 6 or lower", "Above age 6"), check.names = FALSE) ``` + Then creating a new grouping: -```{r grouping with age bins, results='asis'} + +```{r grouping-with-age-bins, results='asis'} grouping4 <- Grouping$new(group = binningDataFrame) ``` This new `Grouping` object `grouping4` yields the following captions -```{r show grouping with age bins, results='asis'} +```{r show-grouping-with-age-bins, results='asis'} # Apply the mapping to get the grouping captions: testData$Age <- testData$`Organism|Age` binnedGroupingsDataFrame <- data.frame(testData$IndividualId, @@ -244,18 +278,20 @@ knitr::kable(binnedGroupingsDataFrame) An additional `R6` class called `GroupMapping` maps `Grouping` objects to aesthetic parameters such as `color` or `linetype`. To distinguish between "Compound" and "Dose" groups by color and to use the captions and legend title specified in `grouping2`, the following groupings object `groups1` is constructed: -```{r group mapping class, results='asis'} +```{r group-mapping-class, results='asis'} # Map groups to aesthtic properties groups1 <- GroupMapping$new(color = grouping2 ) ``` A `GroupMapping` object `groups2` can also be constructed more quickly by directly associating an aesthetic, such as `color`, to a vector of dataframe column names: + ```{r, results='asis'} # Map groups to aesthtic properties groups2 <- GroupMapping$new(color = c("Compound", "Dose")) ``` or to a `Grouping` object directly: + ```{r, results='asis'} # Map groups to aesthetic properties groups3 <- GroupMapping$new(color = Grouping$new(group = c("Compound", "Dose"), @@ -264,18 +300,20 @@ groups3 <- GroupMapping$new(color = Grouping$new(group = c("Compound", "Dose"), ## 3.2. DataMapping -The `R6` class `XYGDataMapping` extracts the maps the x, y and groups of data according to the aesthetics specified in an input `GroupMapping` object. This mapping is carried out by an internal function of this class named `checkMapData` which check if the variables indicated the `GroupMapping` are included in the data. Then, this method returns a simplified data.frame with the variables defined by the dataMapping. +The `R6` class `XYGDataMapping` extracts the maps the x, y, and grouping variables of data according to the aesthetics specified in an input `GroupMapping` object. This mapping is carried out by an internal function of this class named `checkMapData` which checks if the variables indicated the `GroupMapping` are included in the data. This method then returns a simplified dataframe with the variables defined by the dataMapping. When no `GroupMapping` object is supplied upon construction of a `XYGDataMapping` object, the function `checkMapData` returns a dataframe with `x` and `y`. A dummy variable named `aesDefault` is added to the data.frame, its sole purpose is to allow modifications of aesthetic properties after the creation of the ggplot object (not possible otherwise). -```{r data mapping, results='asis'} + +```{r data-mapping, results='asis'} tpMapping <- XYGDataMapping$new(x="IndividualId", y="Organism|VenousBlood|Volume") knitr::kable(tpMapping$checkMapData(data = testData, metaData = IndividualIdProfileMetaData)) ``` When a `GroupMapping` object is supplied upon construction of the `XYGDataMapping` object, each `x`,`y` pair is associated with a group that can be used to distinguish the pair aesthetically in the final plot: -```{r data mapping groups 1, results='asis'} + +```{r data-mapping-groups-1, results='asis'} # Re-use the variable groups previously defined tpMapping <- XYGDataMapping$new(x="IndividualId", y="Organism|VenousBlood|Volume", groupMapping = groups1)