The main purpose of the ospsuite.plots library is to
provide standardized plots typically used in the context of PBPK
modeling. The library supports plot generation for the packages
OSPSuiteR and OSPSuite.ReportingEngine.
The library is based on ggplot2 functionality and also
utilizes the ggh4x package.
ospsuite.plots provides default settings for the layout,
including theme, geometric aesthetics, colors, and shapes for distinct
scales.
Examples within this vignette are plotted using the following test data:
testData <- exampleDataCovariates |>
dplyr::filter(SetID == "DataSet1") |>
dplyr::select(c("ID", "Age", "Obs", "Pred", "Sex"))
knitr::kable(head(testData), digits = 3)| ID | Age | Obs | Pred | Sex |
|---|---|---|---|---|
| 1 | 48 | 4.00 | 2.90 | Male |
| 2 | 36 | 4.40 | 5.75 | Male |
| 3 | 52 | 2.80 | 2.70 | Male |
| 4 | 47 | 3.75 | 3.05 | Male |
| 5 | 0 | 1.95 | 5.25 | Male |
| 6 | 48 | 2.45 | 5.30 | Male |
ospsuite.plots function# ospsuite.plots function
ospsuite.plots::plotHistogram(data = testData, mapping = aes(x = Age)) + labs(tag = "A")
# Customized plot
ggplot(data = testData, mapping = aes(x = Obs, y = Pred, color = Sex, shape = Sex)) +
geom_point() +
theme(legend.position = "top") +
labs(tag = "B")To set the default layout, we use the same logic as in
ggplot2::theme_set(). The previous settings are returned
invisibly, so you can easily save them and restore them later.
setDefaults() sets the theme, discrete color palette,
and various options. All objects can also be set separately as described
below. Shape ordering for OSP-aware geoms is controlled per plot via
scale_shape_osp() or
scale_shape_osp_manual().
# Set default layout and save previous layout in variable oldDefaults
oldDefaults <- ospsuite.plots::setDefaults(defaultOptions = list(), colorMapList = NULL)
# ospsuite.plots function
ospsuite.plots::plotHistogram(data = testData, mapping = aes(x = Age)) + labs(tag = "A")
# Customized plot
ggplot(data = testData, mapping = aes(x = Obs, y = Pred, color = Sex, fill = Sex, shape = Sex)) +
geom_point() +
theme(legend.position = "top") +
labs(tag = "B")# Reset to previously saved layout options
ospsuite.plots::resetDefaults(oldDefaults = oldDefaults)
# ospsuite.plots function
ospsuite.plots::plotHistogram(data = testData, mapping = aes(x = Age)) + labs(tag = "A")
# Customized plot
ggplot(data = testData, mapping = aes(x = Obs, y = Pred, color = Sex, shape = Sex)) +
geom_point() +
theme(legend.position = "top") +
labs(tag = "B")Functions to set the ospsuite.plots default theme only
are setDefaultTheme() and resetDefaultTheme().
These functions are called by setDefaults() and
resetDefaults().
Functions to set the ospsuite.plots default color only
are setDefaultColorMapDistinct() and
resetDefaultColorMapDistinct(). These functions are called
by setDefaults() and resetDefaults().
Colors are set to discrete and ordinal scales for fill
and colour.
The package provides some color palettes in the object
colorMaps (see ?colorMaps).
The example below shows plots with:
colorMaps[["grays"]]scale_fill_grey()ggsci::pal_lancet()(9)ggsci::scale_color_lancet()# Set ospsuite.plots Default Color
oldColors <- ospsuite.plots::setDefaultColorMapDistinct()
ggplot() +
geom_tile(aes(x = rep(seq(1, 3), 2), y = rep(seq(1, 2), each = 3), fill = as.factor(seq(1, 6)))) +
labs(title = "Default settings for up to 6 different colors", tag = "A") +
theme(legend.position = "none", axis.title = element_blank())ggplot() +
geom_tile(aes(x = c(rep(seq(1, 7), 7), 1, 2), y = c(rep(seq(1, 7), each = 7), 8, 8), fill = as.factor(seq(1, 51)))) +
labs(title = "Default settings for more than 6 different colors") +
theme(legend.position = "none", axis.title = element_blank())# Customize colors: set to gray colors
ospsuite.plots::setDefaultColorMapDistinct(colorMaps[["grays"]])
ggplot() +
geom_tile(aes(x = rep(seq(1, 3), 3), y = rep(seq(1, 3), each = 3), fill = as.factor(seq(1, 9)))) +
theme(legend.position = "none", axis.title = element_blank()) +
labs(title = "colorMaps gray", tag = "C")ggplot() +
geom_tile(aes(x = rep(seq(1, 3), 3), y = rep(seq(1, 3), each = 3), fill = as.factor(seq(1, 9)))) +
theme(legend.position = "none", axis.title = element_blank()) +
scale_fill_grey() +
labs(title = "scale_fill_grey", tag = "D")# Set to color palettes inspired by plots in Lancet journals
ospsuite.plots::setDefaultColorMapDistinct(ggsci::pal_lancet()(9))
ggplot() +
geom_tile(aes(x = rep(seq(1, 3), 3), y = rep(seq(1, 3), each = 3), fill = as.factor(seq(1, 9)))) +
theme(legend.position = "none", axis.title = element_blank()) +
labs(title = "ggsci::pal_lancet", tag = "E")# Set to color palettes inspired by plots in Lancet journals
ospsuite.plots::setDefaultColorMapDistinct(ggsci::pal_lancet()(9))
ggplot() +
geom_tile(aes(x = rep(seq(1, 3), 3), y = rep(seq(1, 3), each = 3), fill = as.factor(seq(1, 9)))) +
theme(legend.position = "none", axis.title = element_blank()) +
ggsci::scale_color_lancet() +
labs(title = "ggsci::scale_color_lancet", tag = "F")All point layers produced by ospsuite.plots use
geom_point_osp(), which draws from the OSP shape palette
defined in ospShapeNames. When you build your own plots and
want them to combine consistently with ospsuite.plots
outputs, prefer geom_point_osp() over the raw
ggplot2::geom_point().
Shape ordering is controlled per plot, not via a global option:
geom_point_osp() paired with
scale_shape_osp() assigns shapes automatically from
ospShapeNames.scale_shape_osp_manual(values = c(level1 = "circle", level2 = "diamond", ...))
sets an explicit mapping.scale_shape_osp_identity() is the right choice when the
data already contains shape names.Raw ggplot2::geom_point() keeps using ggplot2’s native
pch shapes and is unaffected.
getDefaultOptions() returns a list of options used in
this package. These options are set by the function
setDefaults() via the variable
defaultOptions.
The names of all options defined by this package start with the
package name ospsuite.plots as a prefix and a suffix. The
suffixes are listed in the enumeration OptionKeys. There
are two helper functions (setOspsuite.plots.option and
getOspsuite.plots.option) to set and get these options.
All plots in this packages are created with the function
ggplotWithWatermark() instead of ggplot().
This function creates a ggplot with a customized print
function which adds a watermark.
The watermark is enabled by default — plots produced
without any configuration will already carry the watermark. Setting the
option to NULL is treated the same as using the default, so
the watermark will still appear.
No opt-in is required; you only need to interact with these options
if you want to customize or remove the watermark. To override this
default in your .Rprofile (e.g., to disable watermarks
globally):
You can edit your .Rprofile with
usethis::edit_r_profile().
Attention! If you combine plots e.g. with
cowplot:plot_grid the default print function without
watermark is called. In this case you have to add the watermark with the
function addWatermark(plotObject) before the print.
The watermark can be customized by these options:
watermarkEnabled, default = TRUE)watermarkLabel, default
= “preliminary analysis”)watermarkFormat, default
=
list(x = 0.5, y = 0.5, color = "lightgrey", angle = 30, fontsize = 12, alpha = 0.7))# Change format and label of watermark
setOspsuite.plots.option(optionKey = OptionKeys$watermarkFormat, value = list(x = 0.2, y = 0.6, color = "red", angle = 90, fontsize = 24, alpha = 0.2))
setOspsuite.plots.option(optionKey = OptionKeys$watermarkLabel, value = "NEW")
# Initialize plot
ggplotWithWatermark() + labs(title = "Changed Watermark", tag = "A")# Disable watermark
setOspsuite.plots.option(optionKey = OptionKeys$watermarkEnabled, value = FALSE)
# Initialize plot
ggplotWithWatermark() + labs(title = "No Watermark", tag = "B")# Reset to default
setOspsuite.plots.option(optionKey = OptionKeys$watermarkFormat, value = NULL)
setOspsuite.plots.option(optionKey = OptionKeys$watermarkLabel, value = NULL)
setOspsuite.plots.option(optionKey = OptionKeys$watermarkEnabled, value = TRUE)
# Initialize plot
ggplotWithWatermark() + labs(title = "Default Watermark", tag = "C")All plot functions have input variables geom*Attributes
which are passed as variables to the corresponding ggplot layer. The
defaults of the input variables can be set by options.
| functions | Line | Ribbon | Point | Errorbar | LLOQ | Hist | Boxplot | ComparisonLine | GuestLine |
|---|---|---|---|---|---|---|---|---|---|
| plotTimeProfile() | geomLineAttributes | geomRibbonAttributes | geomPointAttributes | geomErrorbarAttributes | geomLLOQAttributes | ||||
| plotResVsCov() | geomPointAttributes | geomErrorbarAttributes | geomLLOQAttributes | geomComparisonLineAttributes | geomGuestLineAttributes | ||||
| plotRatioVsCov() | geomPointAttributes | geomErrorbarAttributes | geomLLOQAttributes | geomComparisonLineAttributes | geomGuestLineAttributes | ||||
| plotPredVsObs() | geomPointAttributes | geomErrorbarAttributes | geomLLOQAttributes | geomComparisonLineAttributes | geomGuestLineAttributes | ||||
| plotHistogram() | geomHistAttributes | ||||||||
| plotBoxWhisker() | geomBoxplotAttributes, geomPointAttributes |
With default options:
LineAttributes = list()Ribbon = list(color = NA)PointAttributes = list()ErrorbarAttributes = list(width = 0)LLOQAttributes = list()ComparisonLineAttributes = list(linetype = "dashed")GuestLineAttributes = list(linetype = "dashed")BoxplotAttributes = list(position = position_dodge(width = 1), color = "black")HistAttributes = list(bins = 10, position = ggplot2::position_nudge())Options to set the face alpha of ribbons, filled points and options to set the filled points for values below and above LLOQ.
There are two percentile-related options controlling default behavior:
percentiles: A numeric vector of five quantiles
defining the lower whisker, lower box, median, upper box, and upper
whisker used by plotBoxWhisker() (default =
c(0.05, 0.25, 0.5, 0.75, 0.95)).defaultPercentiles: A numeric vector of three quantiles
used as the default for plotRangeDistribution() (default =
c(0.05, 0.5, 0.95)).# Get current box-whisker percentiles (5 values)
getOspsuite.plots.option(optionKey = OptionKeys$percentiles)
# Change box-whisker percentiles globally
setOspsuite.plots.option(optionKey = OptionKeys$percentiles, value = c(0.1, 0.25, 0.5, 0.75, 0.9))
# Get current range-plot percentiles (3 values)
getOspsuite.plots.option(optionKey = OptionKeys$defaultPercentiles)
# Change range-plot default percentiles globally
setOspsuite.plots.option(optionKey = OptionKeys$defaultPercentiles, value = c(0.1, 0.5, 0.9))There are options to define the export format using the function
exportPlot (see details below):
exportWidth: Width of the exported fileexportUnits: Units for width and heightexportDevice: Device for plot exportexportDpi: Plot resolutionThe latter options are used directly as input for
ggplot2::ggsave, so check the help for available
values.
All plot functions listed below call internally the function
initializePlot(). This function constructs labels from the
metadata and adds a watermark layer. It can also be used to create a
customized ggplot.
plotTimeProfile()plotBoxWhisker()plotHistogram()plotPredVsObs()plotResVsCov()plotRatioVsCov()plotQQ()This package provides some additional aesthetics.
For more details, see the examples within the vignettes for the respective functions.
groupby: Shortcut to use different aesthetics to group.
All functions where this aesthetic is used have also a variable
groupAesthetics. The mapping groupby is copied
to all aesthetics listed within this variable and to the aesthetic
group.lloq: Mapped to a column with values indicating the
lower limit of quantification, adds horizontal (or vertical) lines to
the plot. All observed values below the “lloq” are plotted with a
lighter alpha. As values are compared row by row, it is possible to have
more than one LLOQ.error: Mapped to a column with additive error (e.g.,
standard deviation); error bars are plotted. This is a shortcut to map
ymin and ymax directly
(ymin = y - error and ymax = y + error).
Additionally, if yScale is set, ymin values
below 0 are set to y.error_relative: Mapped to a column with relative error
(e.g., geometric standard deviation); error bars are plotted. This is a
shortcut to map ymin and ymax directly
(ymin = y / error_relative and
ymax = y * error_relative).y2axis: Creates a plot with 2 y axes. It is used to map
to a column with a logical value. Values where this column has a TRUE
entry will be displayed with a secondary axis.mdv: Mapped to a logical column. Rows where this column
has entries set to TRUE are not plotted (MDV = missing data value, taken
from NONMEM notation).observed / predicted: For the function
plotPredVsObs(), observed is mapped to
x and predicted is mapped to
y.Residuals and ratios must be pre-calculated before passing them to
the plotting functions. If you are using the {ospsuite}
package, use ospsuite::addResidualColumn() to add a
residual column to your data.
See
vignette("Goodness of Fit", package = "ospsuite.plots") for
examples.
| functions | groupby |
lloq |
error |
error_relative |
y2axis |
mdv |
observed / predicted |
|---|---|---|---|---|---|---|---|
| plotTimeProfile() | X | X | X | X | X | X | |
| plotHistogram() | X | X | |||||
| plotPredVsObs() | X | X | X | X | X | X | |
| plotResVsCov() | X | X | X | X | |||
| plotRatioVsCov() | X | X | X | X | |||
| plotQQ() | X | X | |||||
| plotBoxWhisker() | X |
This section demonstrates how to use the exportPlot
function to save ggplot objects to files, adjusting the
width and height of the exported plots as necessary. This function is
part of the ospsuite.plots package and simplifies the
process of exporting plots for various purposes, such as publication or
presentation.
To export a plot, you need a ggplot object. Here’s a basic example:
Create a simple ggplot object:
Exporting the Plot: Using the exportPlot function, you
can easily save this plot to a file:
Replace “path/to/save” with the actual directory path where you want to save the plot, and adjust the width and height parameters as needed.
The exportPlot function can automatically adjust the
plot dimensions based on its content, such as the presence of a legend
or the aspect ratio.
Assuming plotObject is your ggplot object:
In this case, you don’t need to specify the width and height
explicitly; the function calculates them for you. The default width
value saved in the ospsuite.plots option
exportWidth is used. If an aspect ratio is defined in the
theme of the plot, height will be adjusted accordingly; otherwise, the
function exports square figures.
shapes <- data.frame(
shapeNames = ospShapeNames,
x = rep(1:6, length.out = length(ospShapeNames)),
y = rep(1:4, each = 6, length.out = length(ospShapeNames))
)
ggplot(shapes, aes(x, y, shape = shapeNames)) +
geom_point_osp(size = 5, color = "blue", fill = "red") +
scale_shape_osp_identity() +
geom_text(aes(label = shapeNames), nudge_y = -0.3, size = 3) +
theme_void()OSP shapes are available in all ospsuite.plots functions
via the default shape scale set by setDefaults(). You can
also apply them directly with scale_shape_osp().
oldDefaults <- ospsuite.plots::setDefaults()
dt <- data.frame(x = c(1, 2, 1, 2), y = c(1, 1, 2, 2), species = c("dog", "cat", "mouse", "rat"))
plotObject <- plotYVsX(data = dt, mapping = aes(x = x, y = y, groupby = species), xScale = "linear", xScaleArgs = list(limits = c(0.5, 2.5)), yScale = "linear", yScaleArgs = list(limits = c(0.5, 2.5)))
plot(plotObject)```