{"repo_name": "tinyplot", "file_name": "/tinyplot/R/hooks.R", "inference_info": {"prefix_code": "# Copied from https://raw.githubusercontent.com/r-lib/evaluate/refs/heads/main/R/hooks.R\n# license: MIT + file LICENSE\n\n\n\n#' Set and remove hooks\n#'\n#' This interface wraps the base [setHook()] function to provide a return\n#' value that makes it easy to undo.\n#'\n#' @param hooks a named list of hooks - each hook can either be a function or\n#' a list of functions.\n#' @param action `\"replace\"`, `\"append\"` or `\"prepend\"`\n#' @keywords internal\nset_hooks <- function(hooks, action = \"append\") {\n old <- list()\n for (hook_name in names(hooks)) {\n old[[hook_name]] <- getHook(hook_name)\n setHook(hook_name, hooks[[hook_name]], action = action)\n }\n invisible(old)\n}\n\n#' @rdname set_hooks\n#' @keywords internal\nremove_hooks <- ", "suffix_code": "\n", "middle_code": "function(hooks) {\n for (hook_name in names(hooks)) {\n hook <- getHook(hook_name)\n if (length(hook) > 0) {\n for (fun in unlist(hooks[hook_name])) {\n hook[sapply(hook, identical, fun)] <- NULL\n }\n }\n setHook(hook_name, hook, \"replace\")\n }\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/tinyplot/R/tpar.R", "#' @title Set or query graphical parameters\n#'\n#' @description Extends \\code{\\link[graphics]{par}}, serving as a (near) drop-in\n#' replacement for setting or querying graphical parameters. The key\n#' differences is that, beyond supporting the standard group of R graphical\n#' parameters in \\code{\\link[graphics]{par}}, `tpar` also supports additional\n#' graphical parameters that are provided by `tinyplot`. Similar to\n#' \\code{\\link[graphics]{par}}, parameters are set by passing appropriate\n#' `key = value` argument pairs, and multiple parameters can be set or queried\n#' at the same time.\n#'\n#' @param ... arguments of the form `key = value`. This includes all of the\n#' parameters typically supported by \\code{\\link[graphics]{par}}, as well as\n#' the `tinyplot`-specific ones described in the 'Graphical Parameters'\n#' section below.\n#' @param hook Logical. If `TRUE`, base graphical parameters persist across \n#' plots via a hook applied before each new plot (see `?setHook`).\n#'\n#' @md\n#' @details The `tinyplot`-specific parameters are saved in an internal\n#' environment called `.tpar` for performance and safety reasons. However,\n#' they can also be set at package load time via \\code{\\link[base]{options}},\n#' which may prove convenient for users that want to enable different default\n#' behaviour at startup (e.g., through an `.Rprofile` file). These options all\n#' take a `tinyplot_*` prefix, e.g.\n#' `options(tinyplot_grid = TRUE, tinyplot_facet.bg = \"grey90\")`.\n#'\n#' For their part, any \"base\" graphical parameters are caught dynamically and\n#' passed on to \\code{\\link[graphics]{par}} as appropriate. Technically, only\n#' parameters that satisfy `par(..., no.readonly = TRUE)` are evaluated.\n#'\n#' However, note the important distinction: `tpar` only evaluates parameters\n#' from \\code{\\link[graphics]{par}} if they are passed _explicitly_ by the\n#' user. This means that `tpar` should not be used to capture the (invisible)\n#' state of a user's entire set of graphics parameters, i.e. `tpar()` !=\n#' `par()`. If you want to capture the _all_ existing graphics settings, then\n#' you should rather use `par()` instead.\n#'\n#' @returns When parameters are set, their previous values are returned in an\n#' invisible named list. Such a list can be passed as an argument to `tpar` to\n#' restore the parameter values.\n#'\n#' When just one parameter is queried, the value of that parameter is returned\n#' as (atomic) vector. When two or more parameters are queried, their values\n#' are returned in a list, with the list names giving the parameters.\n#'\n#' Note the inconsistency: setting one parameter returns a list, but querying\n#' one parameter returns a vector.\n#'\n#' @section Additional Graphical Parameters:\n#'\n#' * `adj.xlab`: Numeric value between 0 and 1 controlling the alignment of the x-axis label.\n#' * `adj.ylab`: Numeric value between 0 and 1 controlling the alignment of the y-axis label.\n#' * `cairo`: Logical indicating whether \\code{\\link[grDevices]{cairo_pdf}} should be used when writing plots to PDF. If `FALSE`, then \\code{\\link[grDevices]{pdf}} will be used instead, with implications for embedding (non-standard) fonts. Only used if `tinyplot(..., file = \".pdf\")` is called. Defaults to the value of `capabilities(\"cairo\")`.\n#' * `dynmar`: Logical indicating whether `tinyplot` should attempt dynamic adjustment of margins to reduce whitespace and/or account for spacing of text elements (e.g., long horizontal y-axis labels). Note that this parameter is tightly coupled to internal `tinythemes()` logic and should _not_ be adjusted manually unless you really know what you are doing or don't mind risking unintended consequences to your plot.\n#' * `facet.bg`: Character or integer specifying the facet background colour. If an integer, will correspond to the user's default colour palette (see `palette`). Passed to `rect`. Defaults to `NULL` (none).\n#' * `facet.border`: Character or integer specifying the facet border colour. If an integer, will correspond to the user's default colour palette (see `palette`). Passed to `rect`. Defaults to `NA` (none).\n#' * `facet.cex`: Expansion factor for facet titles. Defaults to `1`.\n#' * `facet.col`: Character or integer specifying the facet text colour. If an integer, will correspond to the user's default global colour palette (see `palette`). Defaults to `NULL`, which is equivalent to \"black\".\n#' * `facet.font`: An integer corresponding to the desired font face for facet titles. For most font families and graphics devices, one of four possible values: `1` (regular), `2` (bold), `3` (italic), or `4` (bold italic). Defaults to `NULL`, which is equivalent to `1` (i.e., regular).\n#' * `file.height`: Numeric specifying the height (in inches) of any plot that is written to disk using the `tinyplot(..., file = X)` argument. Defaults to `7`.\n#' * `file.res`: Numeric specifying the resolution (in dots per square inch) of any plot that is written to disk in bitmap format (i.e., PNG or JPEG) using the `tinyplot(..., file = X)` argument. Defaults to `300`.\n#' * `file.width`: Numeric specifying the width (in inches) of any plot that is written to disk using the `tinyplot(..., file = X)` argument. Defaults to `7`.\n#' * `fmar`: A numeric vector of form `c(b,l,t,r)` for controlling the (base) margin padding, in terms of lines, between the individual facets in a faceted plot. Defaults to `c(1,1,1,1)`. If more than three facets are detected, the `fmar` parameter is scaled by 0.75 to reduce excess whitespace. For 2x2 plots, the padding better matches the `cex` expansion logic of base graphics.\n#' * `grid.col`: Character or (integer) numeric that specifies the color of the panel grid lines. Defaults to `\"lightgray\"`.\n#' * `grid.lty`: Character or (integer) numeric that specifies the line type of the panel grid lines. Defaults to `\"dotted\"`.\n#' * `grid.lwd`: Non-negative numeric giving the line width of the panel grid lines. Defaults to `1`.\n#' * `grid`: Logical indicating whether a background panel grid should be added to plots automatically. Defaults to `NULL`, which is equivalent to `FALSE`.\n#' * `lmar`: A numeric vector of form `c(inner, outer)` that gives the margin padding, in terms of lines, around the automatic `tinyplot` legend. Defaults to `c(1.0, 0.1)`. The inner margin is the gap between the legend and the plot region, and the outer margin is the gap between the legend and the edge of the graphics device.\n#' * `palette.qualitative`: Palette for qualitative colors. See the `palette` argument in `?tinyplot`.\n#' * `palette.sequential`: Palette for sequential colors. See the `palette` argument in `?tinyplot`.\n#' * `ribbon.alpha`: Numeric factor in the range `[0,1]` for modifying the opacity alpha of \"ribbon\" and \"area\" type plots. Default value is `0.2`.\n#'\n#' @importFrom graphics par\n#' @importFrom utils modifyList\n#' \n#' @seealso [`graphics::par`] which `tpar` builds on top of. [`get_saved_par`]\n#' is a convenience function for retrieving graphical parameters at different\n#' stages of a `tinyplot` call (and used for internal accounting purposes).\n#' [`tinytheme`] allows users to easily set a group of graphics parameters\n#' in a single function call, according to a variety of predefined themes.\n#' \n#' @examples\n#' # Return a list of existing base and tinyplot graphic params\n#' tpar(\"las\", \"pch\", \"facet.bg\", \"facet.cex\", \"grid\")\n#'\n#' # Simple facet plot with these default values\n#' tinyplot(mpg ~ wt, data = mtcars, facet = ~am)\n#'\n#' # Set params to something new. Similar to graphics::par(), note that we save\n#' # the existing values at the same time by assigning to an object.\n#' op = tpar(\n#' las = 1,\n#' pch = 2,\n#' facet.bg = \"grey90\",\n#' facet.cex = 2,\n#' grid = TRUE\n#' )\n#'\n#' # Re-plot with these new params\n#' tinyplot(mpg ~ wt, data = mtcars, facet = ~am)\n#'\n#' # Reset back to original values\n#' tpar(op)\n#'\n#' # Important: tpar() only evalutes parameters that have been passed explicitly\n#' # by the user. So it it should not be used to query and set (restore)\n#' # parameters that weren't explicitly requested, i.e. tpar() != par().\n#'\n#' # Note: The tinyplot-specific parameters can also be be set via `options`\n#' # with a `tinyplot_*` prefix, which can be convenient for enabling\n#' # different default behaviour at startup time (e.g., via an .Rprofile\n#' # file). Example:\n#' # options(tinyplot_grid = TRUE, tinyplot_facet.bg = \"grey90\")\n#'\n#' @export\ntpar = function(..., hook = FALSE) {\n\n opts = list(...)\n if (length(opts) == 1 && is.null(names(opts))) {\n if (inherits(opts[[1]], \"list\") && !is.null(names(opts[[1]]))) {\n opts = opts[[1]]\n }\n }\n\n ###### Assign parameters\n\n # assign tinyplot-specific arguments with known names to .tpar\n assign_tpar(opts)\n\n # return informative error messages if the input is invalid\n assert_tpar(.tpar)\n\n # if tpar(...) includes arguments that are not known to be tinyplot-specific,\n # we set a hook to set them using par() when the graphic device is started\n nam = names(opts)\n if (!is.null(nam)) {\n base_par = setdiff(nam, known_tpar)\n base_par = opts[base_par]\n if (length(base_par) > 0) {\n if (isTRUE(hook)) {\n # append new hook to existing ones\n new_hooks = list(\"before.plot.new\" = function() par(base_par))\n set_hooks(new_hooks, action = \"append\")\n # save new hook to tinyplot environment for later removal\n old_hooks = get_environment_variable(\".tpar_hooks\")\n set_environment_variable(\".tpar_hooks\", c(old_hooks, new_hooks))\n } else {\n par_names = names(par(no.readonly = TRUE))\n base_par = base_par[names(base_par) %in% par_names]\n base_par_old = par(base_par)\n par(base_par)\n }\n }\n }\n\n\n ###### Retrieve parameters\n\n # User didn't assign any new values, but may have requested explicit (print\n # of) some existing value(s)\n tpar_old = as.list(.tpar)\n if (is.null(nam)) {\n known_par = names(par(no.readonly = TRUE))\n if (!is.null(nam)) {\n used_par = intersect(nam, known_par)\n } else {\n used_par = intersect(opts, known_par)\n }\n if (length(used_par)) {\n if (!is.null(nam)) used_par = opts[used_par]\n used_par_old = par(used_par)\n tpar_old = modifyList(as.list(.tpar), used_par_old, keep.null = TRUE)\n }\n if (!is.null(opts) && length(opts) != 0) {\n # specific values requested\n opts = Filter(is.character, opts)\n ret = (`names<-`(lapply(opts, function(x) .tpar[[x]]), opts))\n if (length(used_par)) {\n ret_par = par(used_par)\n ret = modifyList(ret, ret_par, keep.null = TRUE)\n }\n if (length(ret) == 1) ret = ret[[1]]\n return(ret)\n } else {\n # no specific request; return all existing values invisibly\n return(invisible(tpar_old))\n }\n # assign new values, but still return old values for saving existing settings\n # a la `oldpar = par(param = new_value)`\n } else {\n `names<-`(lapply(nam, function(x) .tpar[[x]]), nam)\n if (length(base_par) > 0 && isFALSE(hook)) tpar_old = modifyList(tpar_old, base_par_old, keep.null = TRUE)\n return(invisible(tpar_old))\n }\n}\n\n\n# Two levels of priority: .tpar[[\"name\"]] -> par(\"name\")\nget_tpar = function(opts, default = NULL) {\n # parameter priority\n # .tpar[[\"name\"]] -> par(\"name\")\n for (o in opts) {\n tp = .tpar[[o]]\n if (!is.null(tp)) {\n return(tp)\n } else {\n p = suppressWarnings(par(o))\n if (!is.null(p)) {\n return(p)\n }\n }\n\n }\n return(default)\n}\n\n\nknown_tpar = c(\n \"adj.main\",\n \"adj.sub\",\n \"adj.xlab\",\n \"adj.ylab\",\n \"cex.xlab\",\n \"cex.ylab\",\n \"col.xaxs\",\n \"col.yaxs\",\n \"cairo\",\n \"dynmar\",\n \"facet.bg\",\n \"facet.border\",\n \"facet.cex\",\n \"facet.col\",\n \"facet.font\",\n \"file.height\",\n \"file.res\",\n \"file.width\",\n \"fmar\",\n \"grid\",\n \"grid.bg\",\n \"grid.col\",\n \"grid.lty\",\n \"grid.lwd\",\n \"lmar\",\n \"lty.xaxs\",\n \"lty.yaxs\",\n \"lwd.xaxs\",\n \"lwd.yaxs\",\n \"lwd.axis\",\n \"pch\",\n \"palette.qualitative\",\n \"palette.sequential\",\n \"ribbon.alpha\",\n \"side.sub\",\n \"tinytheme\",\n \"xaxt\",\n \"yaxt\"\n)\n\n\nassign_tpar = function(opts) {\n for (n in intersect(names(opts), known_tpar)) {\n .tpar[[n]] = opts[[n]]\n }\n}\n\n\nassert_tpar = function(.tpar) {\n assert_numeric(.tpar[[\"adj.main\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"adj.main\")\n assert_numeric(.tpar[[\"adj.sub\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"adj.sub\")\n assert_numeric(.tpar[[\"adj.xlab\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"adj.xlab\")\n assert_numeric(.tpar[[\"adj.ylab\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"adj.ylab\")\n assert_flag(.tpar[[\"cairo\"]], name = \"cairo\")\n assert_flag(.tpar[[\"dynmar\"]], null.ok = FALSE, name = \"dynmar\")\n assert_numeric(.tpar[[\"lmar\"]], len = 2, null.ok = TRUE, name = \"lmar\")\n assert_numeric(.tpar[[\"ribbon.alpha\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"ribbon.alpha\")\n assert_numeric(.tpar[[\"grid.lwd\"]], len = 1, lower = 0, null.ok = TRUE, name = \"grid.lwd\")\n assert_flag(.tpar[[\"grid\"]], null.ok = TRUE, name = \"grid\")\n assert_numeric(.tpar[[\"file.res\"]], len = 1, lower = 0, null.ok = TRUE, name = \"file.res\")\n assert_numeric(.tpar[[\"file.height\"]], len = 1, lower = 0, null.ok = TRUE, name = \"file.height\")\n assert_numeric(.tpar[[\"file.width\"]], len = 1, lower = 0, null.ok = TRUE, name = \"file.width\")\n assert_numeric(.tpar[[\"facet.font\"]], len = 1, null.ok = TRUE, name = \"facet.font\")\n assert_numeric(.tpar[[\"facet.cex\"]], len = 1, null.ok = TRUE, name = \"facet.cex\")\n assert_numeric(.tpar[[\"side.sub\"]], len = 1, null.ok = TRUE, name = \"side.sub\")\n assert_string(.tpar[[\"grid.bg\"]], null.ok = TRUE, name = \"grid.bg\")\n assert_numeric(.tpar[[\"fmar\"]], len = 4, null.ok = TRUE, name = \"fmar\")\n\n facet.col = .tpar[[\"facet.col\"]]\n if (!is.null(facet.col)) {\n if (!is.null(facet.col) && !is.numeric(facet.col) && !is.character(facet.col)) {\n stop(\"facet.col needs to be NULL, or a numeric or character\", call. = FALSE)\n }\n assert_true(length(facet.col) == 1, name = \"length(facet.col)==1\")\n }\n\n facet.bg = .tpar$facet.bg\n if (!is.null(facet.bg)) {\n if (!is.numeric(facet.bg) && !is.character(facet.bg)) {\n stop(\"facet.bg needs to be NULL, or a numeric or character\", call. = FALSE)\n }\n assert_true(length(facet.bg) == 1, name = \"length(facet.bg)==1\")\n }\n\n facet.border = .tpar$facet.border\n if (!is.null(facet.border)) {\n if (!is.numeric(facet.border) && !is.character(facet.border) && !is.na(facet.border)) {\n stop(\"facet.border needs to be NULL, or a numeric, character, or NA\", call. = FALSE)\n }\n assert_true(length(facet.border) == 1, name = \"length(facet.border)==1\")\n }\n}\n\n\ninit_tpar = function(rm_hook = FALSE) {\n rm(list = names(.tpar), envir = .tpar)\n\n if (isTRUE(rm_hook)) {\n old_hooks = get_environment_variable(\".tpar_hooks\")\n if (length(old_hooks) > 0) {\n remove_hooks(old_hooks)\n set_environment_variable(\".tpar_hooks\", NULL)\n }\n }\n\n .tpar$cairo = if (is.null(getOption(\"tinyplot_cairo\"))) capabilities(\"cairo\") else as.logical(getOption(\"tinyplot_cairo\"))\n \n \n .tpar$dynmar = if (is.null(getOption(\"tinyplot_dynmar\"))) FALSE else as.logical(getOption(\"tinyplot_dynmar\"))\n \n # Figure output options if written to file\n .tpar$file.width = if (is.null(getOption(\"tinyplot_file.width\"))) 7 else as.numeric(getOption(\"tinyplot_file.width\"))\n .tpar$file.height = if (is.null(getOption(\"tinyplot_file.height\"))) 7 else as.numeric(getOption(\"tinyplot_file.height\"))\n .tpar$file.res = if (is.null(getOption(\"tinyplot_file.res\"))) 300 else as.numeric(getOption(\"tinyplot_file.res\"))\n\n # Facet margin, i.e. gap between the individual facet windows\n .tpar$fmar = if (is.null(getOption(\"tinyplot_fmar\"))) c(1, 1, 1, 1) else as.numeric(getOption(\"tinyplot_fmar\"))\n\n # Other facet options\n .tpar$facet.cex = if (is.null(getOption(\"tinyplot_facet.cex\"))) 1 else as.numeric(getOption(\"tinyplot_facet.cex\"))\n .tpar$facet.font = if (is.null(getOption(\"tinyplot_facet.font\"))) NULL else as.numeric(getOption(\"tinyplot_facet.font\"))\n .tpar$facet.col = if (is.null(getOption(\"tinyplot_facet.col\"))) NULL else getOption(\"tinyplot_facet.col\")\n .tpar$facet.bg = if (is.null(getOption(\"tinyplot_facet.bg\"))) NULL else getOption(\"tinyplot_facet.bg\")\n .tpar$facet.border = if (is.null(getOption(\"tinyplot_facet.border\"))) NA else getOption(\"tinyplot_facet.border\")\n\n # Plot grid\n .tpar$grid = if (is.null(getOption(\"tinyplot_grid\"))) FALSE else as.logical(getOption(\"tinyplot_grid\"))\n .tpar$grid.col = if (is.null(getOption(\"tinyplot_grid.col\"))) \"lightgray\" else getOption(\"tinyplot_grid.col\")\n .tpar$grid.lty = if (is.null(getOption(\"tinyplot_grid.lty\"))) \"dotted\" else getOption(\"tinyplot_grid.lty\")\n .tpar$grid.lwd = if (is.null(getOption(\"tinyplot_grid.lwd\"))) 1 else as.numeric(getOption(\"tinyplot_grid.lwd\"))\n\n # Legend margin, i.e. gap between the legend and the plot elements\n .tpar$lmar = if (is.null(getOption(\"tinyplot_lmar\"))) c(1.0, 0.1) else as.numeric(getOption(\"tinyplot_lmar\"))\n\n # Alpha fill (transparency) default for ribbon and area plots\n .tpar$ribbon.alpha = if (is.null(getOption(\"tinyplot_ribbon.alpha\"))) 0.2 else as.numeric(getOption(\"tinyplot_ribbon.alpha\"))\n}\n"], ["/tinyplot/R/draw_legend.R", "#' @title Calculate placement of legend and draw it\n#' \n#' @description Function used to calculate the placement of (including\n#' outside the plotting area) and drawing of legend.\n#' \n#' @md\n#' @param legend Legend placement keyword or list, passed down from [tinyplot].\n#' @param legend_args Additional legend arguments to be passed to\n#' \\code{\\link[graphics]{legend}}.\n#' @param by_dep The (deparsed) \"by\" grouping variable name.\n#' @param lgnd_labs The labels passed to `legend(legend = ...)`.\n#' @param type Plotting type(s), passed down from [tinyplot].\n#' @param pch Plotting character(s), passed down from [tinyplot].\n#' @param lty Plotting linetype(s), passed down from [tinyplot].\n#' @param lwd Plotting line width(s), passed down from [tinyplot].\n#' @param col Plotting colour(s), passed down from [tinyplot].\n#' @param bg Plotting character background fill colour(s), passed down from [tinyplot].\n#' @param cex Plotting character expansion(s), passed down from [tinyplot].\n#' @param gradient Logical indicating whether a continuous gradient swatch\n#' should be used to represent the colors.\n#' @param lmar Legend margins (in lines). Should be a numeric vector of the form\n#' `c(inner, outer)`, where the first number represents the \"inner\" margin\n#' between the legend and the plot, and the second number represents the\n#' \"outer\" margin between the legend and edge of the graphics device. If no\n#' explicit value is provided by the user, then reverts back to `tpar(\"lmar\")`\n#' for which the default values are `c(1.0, 0.1)`.\n#' @param has_sub Logical. Does the plot have a sub-caption. Only used if\n#' keyword position is \"bottom!\", in which case we need to bump the legend\n#' margin a bit further.\n#' @param new_plot Logical. Should we be calling plot.new internally?\n#' @param draw Logical. If `FALSE`, no legend is drawn but the sizes are\n#' returned. Note that a new (blank) plot frame will still need to be started\n#' in order to perform the calculations. \n#' \n#' @returns No return value, called for side effect of producing a(n empty) plot\n#' with a legend in the margin.\n#' \n#' @importFrom graphics grconvertX grconvertY rasterImage strwidth\n#' @importFrom grDevices as.raster recordGraphics\n#' @importFrom utils modifyList\n#' \n#' @examples\n#' oldmar = par(\"mar\")\n#' \n#' draw_legend(\n#' legend = \"right!\", ## default (other options incl, \"left(!)\", \"\"bottom(!)\", etc.)\n#' legend_args = list(title = \"Key\", bty = \"o\"),\n#' lgnd_labs = c(\"foo\", \"bar\"),\n#' type = \"p\",\n#' pch = 21:22,\n#' col = 1:2\n#' )\n#' \n#' # The legend is placed in the outer margin...\n#' box(\"figure\", col = \"cyan\", lty = 4)\n#' # ... and the plot is proportionally adjusted against the edge of this\n#' # margin.\n#' box(\"plot\")\n#' # You can add regular plot objects per normal now\n#' plot.window(xlim = c(1,10), ylim = c(1,10))\n#' points(1:10)\n#' points(10:1, pch = 22, col = \"red\")\n#' axis(1); axis(2)\n#' # etc.\n#' \n#' # Important: A side effect of draw_legend is that the inner margins have been\n#' # adjusted. (Here: The right margin, since we called \"right!\" above.)\n#' par(\"mar\")\n#' \n#' # To reset you should call `dev.off()` or just reset manually.\n#' par(mar = oldmar)\n#' \n#' # Note that the inner and outer margin of the legend itself can be set via\n#' # the `lmar` argument. (This can also be set globally via\n#' # `tpar(lmar = c(inner, outer))`.)\n#' draw_legend(\n#' legend_args = list(title = \"Key\", bty = \"o\"),\n#' lgnd_labs = c(\"foo\", \"bar\"),\n#' type = \"p\",\n#' pch = 21:22,\n#' col = 1:2,\n#' lmar = c(0, 0.1) ## set inner margin to zero\n#' )\n#' box(\"figure\", col = \"cyan\", lty = 4)\n#' \n#' par(mar = oldmar)\n#' \n#' # Continuous (gradient) legends are also supported\n#' draw_legend(\n#' legend = \"right!\",\n#' legend_args = list(title = \"Key\"),\n#' lgnd_labs = LETTERS[1:5],\n#' col = hcl.colors(5),\n#' gradient = TRUE ## enable gradient legend\n#' )\n#' \n#' par(mar = oldmar)\n#' \n#' @export\ndraw_legend = function(\n legend = NULL,\n legend_args = NULL,\n by_dep = NULL,\n lgnd_labs = NULL,\n type = NULL,\n pch = NULL,\n lty = NULL,\n lwd = NULL,\n col = NULL,\n bg = NULL,\n cex = NULL,\n gradient = FALSE,\n lmar = NULL,\n has_sub = FALSE,\n new_plot = TRUE,\n draw = TRUE\n) {\n \n if (is.null(lmar)) {\n lmar = tpar(\"lmar\")\n } else {\n if (!is.numeric(lmar) || length(lmar)!=2) stop (\"lmar must be a numeric of length 2.\")\n }\n \n assert_logical(gradient)\n assert_logical(has_sub)\n assert_logical(new_plot)\n assert_logical(draw)\n \n #\n ## legend args ----\n \n if (is.null(legend_args[[\"x\"]])) {\n if (is.null(legend)) {\n legend_args[[\"x\"]] = \"right!\"\n } else if (is.character(legend)) {\n legend_args = utils::modifyList(legend_args, list(x = legend))\n } else if (class(legend) %in% c(\"call\", \"name\")) {\n largs = as.list(legend)\n if (is.null(largs[[\"x\"]])) {\n lnms = names(largs)\n # check second position b/c first will be a symbol \n if (is.null(lnms)) {\n largs = stats::setNames(largs, c(\"\", \"x\"))\n } else if (length(largs)>=2 && lnms[2] == \"\") {\n lnms[2] = \"x\"\n largs = stats::setNames(largs, lnms)\n } else {\n largs[[\"x\"]] = \"right!\"\n }\n }\n # Finally, combine with any pre-existing legend args (e.g., title from the by label)\n legend_args = utils::modifyList(legend_args, largs, keep.null = TRUE)\n }\n }\n \n ## Use `!exists` rather than `is.null` for title in case user specified no title\n if (!exists(\"title\", where = legend_args)) legend_args[[\"title\"]] = by_dep\n \n legend_args[[\"pch\"]] = legend_args[[\"pch\"]] %||% pch\n legend_args[[\"lty\"]] = legend_args[[\"lty\"]] %||% lty\n legend_args[[\"col\"]] = legend_args[[\"col\"]] %||% col\n legend_args[[\"bty\"]] = legend_args[[\"bty\"]] %||% \"n\"\n legend_args[[\"horiz\"]] = legend_args[[\"horiz\"]] %||% FALSE\n legend_args[[\"xpd\"]] = legend_args[[\"xpd\"]] %||% NA\n \n if (!isTRUE(type %in% c(\"p\", \"ribbon\", \"polygon\", \"polypath\"))) {\n legend_args[[\"lwd\"]] = legend_args[[\"lwd\"]] %||% lwd\n }\n \n if (isTRUE(type %in% c(\"p\", \"pointrange\", \"errorbar\")) && (length(col) == 1 || length(cex) == 1)) {\n legend_args[[\"pt.cex\"]] = legend_args[[\"pt.cex\"]] %||% cex\n }\n \n # turn off inner line for \"barplot\" type\n if (identical(type, \"barplot\")) {\n legend_args[[\"lty\"]] = 0\n }\n \n if (isTRUE(type %in% c(\"rect\", \"ribbon\", \"polygon\", \"polypath\", \"boxplot\", \"hist\", \"histogram\", \"spineplot\", \"ridge\", \"barplot\", \"violin\")) || gradient) {\n legend_args[[\"pch\"]] = 22\n legend_args[[\"pt.cex\"]] = legend_args[[\"pt.cex\"]] %||% 3.5\n legend_args[[\"y.intersp\"]] = legend_args[[\"y.intersp\"]] %||% 1.25\n legend_args[[\"seg.len\"]] = legend_args[[\"seg.len\"]] %||% 1.25\n }\n \n if (isTRUE(type %in% c(\"ribbon\", \"hist\", \"histogram\", \"spineplot\"))) {\n legend_args[[\"pt.lwd\"]] = legend_args[[\"pt.lwd\"]] %||% 0\n }\n \n if (identical(type, \"p\")) {\n legend_args[[\"pt.lwd\"]] = legend_args[[\"pt.lwd\"]] %||% lwd\n }\n \n if (identical(type, \"n\") && isFALSE(gradient)) {\n legend_args[[\"pch\"]] = legend_args[[\"pch\"]] %||% par(\"pch\")\n }\n \n if (identical(type, \"spineplot\")) {\n legend_args[[\"pt.bg\"]] = legend_args[[\"pt.bg\"]] %||% legend_args[[\"col\"]]\n }\n \n if (identical(type, \"ridge\") && isFALSE(gradient)) {\n legend_args[[\"pt.bg\"]] = legend_args[[\"pt.bg\"]] %||% sapply(legend_args[[\"col\"]], function(ccol) seq_palette(ccol, n = 2)[2])\n }\n \n legend_args[[\"pt.bg\"]] = legend_args[[\"pt.bg\"]] %||% bg\n \n legend_args[[\"legend\"]] = legend_args[[\"legend\"]] %||% lgnd_labs\n if (length(lgnd_labs) != length(eval(legend_args[[\"legend\"]]))) {\n warning(\n \"\\nUser-supplied legend labels do not match the number of groups.\\n\",\n \"Defaulting to automatic labels determined by the group splits in `by`,\\n\"\n )\n legend_args[[\"legend\"]] = lgnd_labs\n }\n \n if (isTRUE(gradient)) {\n legend_args[[\"ncol\"]] = NULL\n }\n \n #\n ## legend placement ----\n \n # Note: \"side\" = left/right ; \"end\" = top/bottom\n outer_side = outer_end = outer_right = outer_bottom = FALSE ## placeholders\n \n ooma = par(\"oma\")\n omar = par(\"mar\")\n topmar_epsilon = 0.1\n \n # Catch to avoid recursive offsets, e.g. repeated tinyplot calls with\n # \"bottom!\" legend position.\n \n ## restore inner margin defaults\n ## (in case the plot region/margins were affected by the preceding tinyplot call)\n dynmar = isTRUE(.tpar[[\"dynmar\"]])\n if (any(ooma != 0) && !dynmar) {\n if ( ooma[1] != 0 & omar[1] == par(\"mgp\")[1] + 1*par(\"cex.lab\") ) omar[1] = 5.1\n if ( ooma[2] != 0 & omar[2] == par(\"mgp\")[1] + 1*par(\"cex.lab\") ) omar[2] = 4.1\n if ( ooma[3] == topmar_epsilon & omar[3] != 4.1 ) omar[3] = 4.1\n if ( ooma[4] != 0 & omar[4] == 0 ) omar[4] = 2.1\n par(mar = omar)\n }\n ## restore outer margin defaults\n par(omd = c(0,1,0,1))\n ooma = par(\"oma\")\n \n ## Legend to outer side (either right or left) of plot\n if (grepl(\"right!$|left!$\", legend_args[[\"x\"]])) {\n \n outer_side = TRUE\n outer_right = grepl(\"right!$\", legend_args[[\"x\"]])\n \n # extra bump for spineplot if outer_right legend (to accommodate secondary y-axis)\n if (identical(type, \"spineplot\")) lmar[1] = lmar[1] + 1.1\n \n ## Switch position anchor (we'll adjust relative to the _opposite_ side below)\n if (outer_right) legend_args[[\"x\"]] = gsub(\"right!$\", \"left\", legend_args[[\"x\"]])\n if (!outer_right) legend_args[[\"x\"]] = gsub(\"left!$\", \"right\", legend_args[[\"x\"]])\n \n ## We have to set the inner margins of the plot before the (fake) legend is\n ## drawn, otherwise the inset calculation---which is based in the legend\n ## width---will be off the first time.\n if (outer_right) {\n omar[4] = 0\n } else {\n # For outer left we have to account for the y-axis label too, which\n # requires additional space\n omar[2] = par(\"mgp\")[1] + 1*par(\"cex.lab\")\n }\n par(mar = omar)\n \n if (new_plot && draw) {\n plot.new()\n # For themed + dynamic plots, we need to make sure the adjusted plot\n # margins for the legend are reinstated (after being overwritten by\n # the before.plot.new hook.\n if (dynmar) {\n omar = par(\"mar\")\n if (outer_right) {\n omar[4] = 0\n } else {\n omar[2] = par(\"mgp\")[1] + 1*par(\"cex.lab\")\n }\n par(mar = omar)\n }\n }\n \n legend_args[[\"horiz\"]] = FALSE\n \n ## Legend at the outer top or bottom of plot\n } else if (grepl(\"bottom!$|top!$\", legend_args[[\"x\"]])) {\n\n outer_end = TRUE\n outer_bottom = grepl(\"bottom!$\", legend_args[[\"x\"]])\n\n ## Switch position anchor (we'll adjust relative to the _opposite_ side below)\n if (outer_bottom) legend_args[[\"x\"]] = gsub(\"bottom!$\", \"top\", legend_args[[\"x\"]])\n if (!outer_bottom) legend_args[[\"x\"]] = gsub(\"top!$\", \"bottom\", legend_args[[\"x\"]])\n\n ## We have to set the inner margins of the plot before the (fake) legend is\n ## drawn, otherwise the inset calculation---which is based in the legend\n ## width---will be off the first time.\n if (outer_bottom) {\n omar[1] = par(\"mgp\")[1] + 1*par(\"cex.lab\")\n if (has_sub && (is.null(.tpar[[\"side.sub\"]]) || .tpar[[\"side.sub\"]]==1)) omar[1] = omar[1] + 1*par(\"cex.sub\")\n } else {\n ## For \"top!\", the logic is slightly different: We don't expand the outer\n ## margin b/c we need the legend to come underneath the main title. So\n ## we rather expand the existing inner margin.\n ooma[3] = ooma[3] + topmar_epsilon\n par(oma = ooma)\n }\n par(mar = omar)\n\n if (new_plot && draw) {\n plot.new()\n # For themed + dynamic plots, we need to make sure the adjusted plot\n # margins for the legend are reinstated (after being overwritten by\n # the before.plot.new hook.\n if (dynmar) {\n omar = par(\"mar\")\n if (outer_bottom) {\n # omar[1] = par(\"mgp\")[1] + 1*par(\"cex.lab\")\n omar[1] = theme_clean$mgp[1] + 1*par(\"cex.lab\") ## bit of a hack\n if (has_sub && (is.null(.tpar[[\"side.sub\"]]) || .tpar[[\"side.sub\"]]==1)) omar[1] = omar[1] + 1*par(\"cex.sub\")\n } else {\n ooma[3] = ooma[3] + topmar_epsilon\n par(oma = ooma)\n }\n par(mar = omar)\n }\n }\n\n # enforce horizontal legend if user hasn't specified ncol arg\n # (exception: gradient legends at bottom/top are always horizontal)\n if (is.null(legend_args[[\"ncol\"]]) || gradient) legend_args[[\"horiz\"]] = TRUE\n\n } else {\n \n legend_args[[\"inset\"]] = 0\n if (new_plot && draw) plot.new()\n \n }\n \n # Additional tweaks for horiz and/or multi-column legends\n if (isTRUE(legend_args[[\"horiz\"]]) || !is.null(legend_args[[\"ncol\"]])) {\n # tighter horizontal labelling\n # See: https://github.com/grantmcdermott/tinyplot/issues/434\n if (!gradient) {\n legend_args[[\"text.width\"]] = NA\n # Add a space to all labs except the outer most right ones\n nlabs = length(legend_args[[\"legend\"]])\n nidx = nlabs\n if (!is.null(legend_args[[\"ncol\"]])) nidx = tail(1:nlabs, (nlabs %/% legend_args[[\"ncol\"]]))\n legend_args[[\"legend\"]][-nidx] = paste(legend_args[[\"legend\"]][-nidx], \" \")\n }\n # catch for horizontal ribbon legend spacing\n if (type==\"ribbon\") {\n if (legend_args[[\"pt.lwd\"]] == 1) {\n legend_args[[\"x.intersp\"]] = 1\n } else {\n legend_args[[\"x.intersp\"]] = 0.5\n }\n } else if (gradient) {\n legend_args[[\"x.intersp\"]] = 0.5\n }\n }\n \n #\n ## draw the legend ----\n \n # Legend drawing is handled by the internal `tinylegend()` function, which:\n # 1. calculates appropriate insets for \"outer\" legend placement\n # 2. can draw gradient legends (via `gradient_legend()` below)\n #\n # Note: We wrap everything in `recordGraphics()` to preserve legend spacing\n # if the plot is resized (also necessary for Positron graphics logic regardless)\n recordGraphics(\n tinylegend(\n legend_args = legend_args,\n ooma = ooma,\n omar = omar,\n lmar = lmar,\n topmar_epsilon = topmar_epsilon,\n outer_side = outer_side,\n outer_right = outer_right,\n outer_end = outer_end,\n outer_bottom = outer_bottom,\n gradient = gradient,\n draw = draw\n ),\n list = list(\n legend_args = legend_args,\n ooma = ooma,\n omar = omar,\n lmar = lmar,\n topmar_epsilon = topmar_epsilon,\n outer_side = outer_side,\n outer_right = outer_right,\n outer_end = outer_end,\n outer_bottom = outer_bottom,\n gradient = gradient,\n draw = draw\n ),\n env = getNamespace(\"tinyplot\")\n )\n \n}\n\n\n# tinylegend ----\n\n## Internal workhorse function that draws the legend, given a set of legend\n## arguments and other graphical parameters. It does this in three steps:\n## 1) draw a fake legend, 2) calculate the associated inset and adjust the plot\n## margins accordingly, 3) draw the real legend\n\ntinylegend = function(\n legend_args,\n ooma, omar, lmar, topmar_epsilon,\n outer_side, outer_right, outer_end, outer_bottom,\n gradient,\n draw\n) {\n \n #\n ## Step 1: \"draw\" fake legend\n \n fklgnd.args = modifyList(\n legend_args,\n list(plot = FALSE),\n keep.null = TRUE\n )\n \n if (gradient) {\n lgnd_labs_tmp = na.omit(fklgnd.args[[\"legend\"]])\n if (length(lgnd_labs_tmp) < 5L) {\n nmore = 5L - length(lgnd_labs_tmp)\n lgnd_labs_tmp = c(lgnd_labs_tmp, rep(\"\", nmore))\n }\n fklgnd.args = modifyList(\n fklgnd.args,\n list(legend = lgnd_labs_tmp),\n keep.null = TRUE\n )\n if (outer_end) fklgnd.args = modifyList(fklgnd.args, list(title = NULL), keep.null = TRUE)\n }\n \n if (draw) {\n fklgnd = do.call(\"legend\", fklgnd.args)\n } else {\n plot.new()\n fklgnd = do.call(\"legend\", fklgnd.args)\n return(fklgnd)\n }\n \n #\n ## Step 2: Calculate legend inset (for outer placement in plot region)\n \n # calculate outer margin width in lines\n soma = 0\n if (outer_side) {\n soma = grconvertX(fklgnd$rect$w, to=\"lines\") - grconvertX(0, to=\"lines\")\n } else if (outer_end) {\n soma = grconvertY(fklgnd$rect$h, to=\"lines\") - grconvertY(0, to=\"lines\")\n }\n # Add legend margins to the outer margin\n soma = soma + sum(lmar)\n \n ## differing outer margin adjustments depending on side\n if (outer_side) {\n if (outer_right) {\n ooma[4] = soma\n } else {\n ooma[2] = soma\n }\n } else if (outer_end) {\n if (outer_bottom) {\n ooma[1] = soma\n } else {\n omar[3] = omar[3] + soma - topmar_epsilon\n par(mar = omar)\n }\n }\n par(oma = ooma)\n \n # determine legend inset\n inset = 0\n if (outer_side) {\n inset = grconvertX(lmar[1], from=\"lines\", to=\"npc\") - grconvertX(0, from = \"lines\", to = \"npc\")\n # extra space needed for \"left!\" b/c of lhs inner margin\n if (!outer_right) {\n inset_bump = grconvertX(par(\"mar\")[2], from = \"lines\", to = \"npc\") - grconvertX(0, from = \"lines\", to = \"npc\")\n inset = inset + inset_bump\n }\n inset = c(1+inset, 0)\n } else if (outer_end) {\n inset = grconvertY(lmar[1], from=\"lines\", to=\"npc\") - grconvertY(0, from=\"lines\", to=\"npc\")\n if (outer_bottom) {\n # extra space needed for \"bottom!\" b/c of lhs inner margin\n inset_bump = grconvertY(par(\"mar\")[1], from=\"lines\", to=\"npc\") - grconvertY(0, from=\"lines\", to=\"npc\")\n inset = inset + inset_bump\n } else {\n epsilon_bump = grconvertY(topmar_epsilon, from=\"lines\", to=\"npc\") - grconvertY(0, from=\"lines\", to=\"npc\")\n inset = inset + epsilon_bump\n }\n inset = c(0, 1+inset)\n }\n \n # GM: The legend inset spacing only works _exactly_ if we refresh the plot\n # area. I'm not sure why (and it works properly if we use the same\n # parameters manually while debugging), but this hack seems to work.\n ## v0.3.0 update: Using (temporary) hook instead of direct par(new = TRUE)\n ## assignment to play nice with tinytheme logic.\n oldhook = getHook(\"before.plot.new\")\n setHook(\"before.plot.new\", function() par(new = TRUE), action = \"append\")\n setHook(\"before.plot.new\", function() par(mar = omar), action = \"append\")\n plot.new()\n setHook(\"before.plot.new\", oldhook, action = \"replace\")\n \n # Finally, set the inset as part of the legend args.\n legend_args[[\"inset\"]] = inset\n \n #\n ## Step 3: Draw the legend\n\n if (gradient) {\n if (!more_than_n_unique(legend_args[[\"col\"]], 1)) {\n if (!is.null(legend_args[[\"pt.bg\"]]) && length(legend_args[[\"pt.bg\"]])==100) {\n legend_args[[\"col\"]] = legend_args[[\"pt.bg\"]]\n }\n }\n gradient_legend(\n legend_args = legend_args,\n fklgnd = fklgnd,\n lmar = lmar,\n outer_side = outer_side,\n outer_end = outer_end,\n outer_right = outer_right,\n outer_bottom = outer_bottom\n )\n } else {\n do.call(\"legend\", legend_args)\n }\n \n}\n\n\n# gradient legend ----\n\n# For gradient (i.e., continuous color) legends, we'll role our own bespoke\n# legend function based on grDevices::as.raster\n\ngradient_legend = function(legend_args, fklgnd, lmar, outer_side, outer_end, outer_right, outer_bottom) {\n pal = legend_args[[\"col\"]]\n lgnd_labs = legend_args[[\"legend\"]]\n if (!is.null(legend_args[[\"horiz\"]])) horiz = legend_args[[\"horiz\"]] else horiz = FALSE\n if (isTRUE(horiz)) {\n rasterlgd = as.raster(matrix(pal, nrow = 1))\n } else {\n rasterlgd = as.raster(matrix(rev(pal), ncol = 1))\n }\n \n corners = par(\"usr\")\n rasterbox = rep(NA_real_, 4)\n \n inner = !any(c(outer_side, outer_end))\n inner_right = inner_bottom = FALSE\n if (inner) {\n if (!is.null(legend_args[[\"x\"]]) && grepl(\"left$|right$\", legend_args[[\"x\"]])) {\n inner_right = grepl(\"right$\", legend_args[[\"x\"]])\n }\n if (!is.null(legend_args[[\"x\"]]) && grepl(\"^bottoml|^top\", legend_args[[\"x\"]])) {\n inner_bottom = grepl(\"^bottom\", legend_args[[\"x\"]])\n }\n }\n \n if (inner) {\n \n fklgnd$rect$h = fklgnd$rect$h - (grconvertY(1.5 + 0.4, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\"))\n \n rasterbox[1] = fklgnd$rect$left\n if (isFALSE(inner_right)) rasterbox[1] = rasterbox[1] + (grconvertX(0.2, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\"))\n rasterbox[2] = fklgnd$rect$top - fklgnd$rect$h - (grconvertY(1.5 + 0.2, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\"))\n rasterbox[3] = rasterbox[1] + (grconvertX(1.25, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\"))\n rasterbox[4] = rasterbox[2] + fklgnd$rect$h\n \n } else if (outer_side) {\n \n rb1_adj = grconvertX(lmar[1] + 0.2, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\")\n rb3_adj = grconvertX(1.25, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\")\n rb2_adj = (corners[4] - corners[3] - (grconvertY(5+1 + 2.5, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\"))) / 2\n # override if top or bottom\n if (!is.null(legend_args[[\"x\"]])) {\n if (grepl(\"^bottom\", legend_args[[\"x\"]])) {\n rb2_adj = corners[3]\n }\n if (grepl(\"^top\", legend_args[[\"x\"]])) {\n rb2_adj = corners[4] - (grconvertY(5+1 + 2.5, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\"))\n }\n }\n rb4_adj = grconvertY(5+1, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n \n if (outer_right) {\n rasterbox[1] = corners[2] + rb1_adj\n rasterbox[2] = rb2_adj \n rasterbox[3] = rasterbox[1] + rb3_adj\n rasterbox[4] = rasterbox[2] + rb4_adj\n } else {\n rb1_adj = rb1_adj + grconvertX(par(\"mar\")[2] + 1, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\")\n rasterbox[1] = corners[1] - rb1_adj\n rasterbox[2] = rb2_adj \n rasterbox[3] = rasterbox[1] - rb3_adj\n rasterbox[4] = rasterbox[2] + rb4_adj\n }\n \n } else if (outer_end) {\n \n rb1_adj = (corners[2] - corners[1] - (grconvertX(5+1, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\"))) / 2\n rb3_adj = grconvertX(5+1, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\")\n rb2_adj = grconvertY(lmar[1], from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n rb4_adj = grconvertY(1.25, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n \n if (outer_bottom) {\n rb2_adj = rb2_adj + grconvertY(par(\"mar\")[2], from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n rasterbox[1] = rb1_adj\n rasterbox[2] = corners[3] - rb2_adj \n rasterbox[3] = rasterbox[1] + rb3_adj\n rasterbox[4] = rasterbox[2] - rb4_adj\n } else {\n rb2_adj = rb2_adj + grconvertY(1.25 + 1, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n rasterbox[1] = rb1_adj\n rasterbox[2] = corners[4] + rb2_adj \n rasterbox[3] = rasterbox[1] + rb3_adj\n rasterbox[4] = rasterbox[2] - rb4_adj\n }\n \n }\n \n #\n ## Draw the gradient swatch\n \n rasterImage(\n rasterlgd,\n rasterbox[1], #x1\n rasterbox[2], #y1\n rasterbox[3], #x2\n rasterbox[4], #y2\n xpd = NA\n ) \n \n #\n ## Add the labels, tick marks, and title \n \n if (isFALSE(horiz)) {\n labs_idx = !is.na(lgnd_labs)\n lgnd_labs[labs_idx] = paste0(\" \", format(lgnd_labs[labs_idx]))\n lbl_x_anchor = rasterbox[3]\n ttl_x_anchor = rasterbox[1]\n lbl_adj = c(0, 0.5)\n tck_adj = c(1, 0.5)\n ttl_adj = c(0, 0)\n if (!inner && !outer_right) {\n lbl_x_anchor = rasterbox[1]\n ttl_x_anchor = ttl_x_anchor + max(strwidth(lgnd_labs[labs_idx]))\n ttl_adj = c(1, 0)\n }\n text(\n x = lbl_x_anchor,\n y = seq(rasterbox[2], rasterbox[4], length.out = length(lgnd_labs)),\n labels = lgnd_labs,\n xpd = NA, \n adj = lbl_adj\n )\n # legend tick marks\n lgnd_ticks = lgnd_labs\n lgnd_ticks[labs_idx] = \"- -\"\n text(\n x = lbl_x_anchor,\n y = seq(rasterbox[2], rasterbox[4], length.out = length(lgnd_labs)),\n labels = lgnd_ticks, col = \"white\",\n xpd = NA, adj = tck_adj\n )\n # legend title\n text(\n x = ttl_x_anchor,\n y = rasterbox[4] + grconvertY(1, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\"),\n labels = legend_args[[\"title\"]],\n xpd = NA, adj = ttl_adj\n )\n } else {\n lbl_y_anchor = rasterbox[4]\n ttl_y_anchor = rasterbox[4]\n lbl_adj = c(0.5, 1.25)\n tck_adj = c(0, 0.5)\n ttl_adj = c(1, -0.5)\n # legend labs\n text(\n x = seq(rasterbox[1], rasterbox[3], length.out = length(lgnd_labs)),\n y = lbl_y_anchor,\n labels = lgnd_labs,\n xpd = NA, adj = lbl_adj\n )\n # legend tick marks\n lgnd_ticks = lgnd_labs\n lgnd_ticks[!is.na(lgnd_ticks)] = \"- -\"\n text(\n x = seq(rasterbox[1], rasterbox[3], length.out = length(lgnd_labs)),\n y = lbl_y_anchor,\n labels = lgnd_ticks, col = \"white\",\n xpd = NA, adj = tck_adj, srt = 90\n )\n # legend title\n text(\n x = rasterbox[1],\n y = ttl_y_anchor,\n labels = paste0(legend_args[[\"title\"]], \" \"),\n xpd = NA, adj = ttl_adj\n )\n }\n}\n\n\n"], ["/tinyplot/R/tinyplot.R", "#' @title Lightweight extension of the base R plotting function\n#'\n#' @description\n#' Enhances the base \\code{\\link[graphics]{plot}} function. Supported features\n#' include automatic legends and facets for grouped data, additional plot types,\n#' theme customization, and so on. Users can call either `tinyplot()`, or its\n#' shorthand alias `plt()`.\n#'\n#' @md\n#' @param x,y the x and y arguments provide the x and y coordinates for the\n#' plot. Any reasonable way of defining the coordinates is acceptable; most\n#' likely the names of existing vectors or columns of data frames. See the\n#' 'Examples' section below, or the function\n#' \\code{\\link[grDevices]{xy.coords}} for details. If supplied separately, `x`\n#' and `y` must be of the same length.\n#' @param xmin,xmax,ymin,ymax minimum and maximum coordinates of relevant area\n#' or interval plot types. Only used when the `type` argument is one of\n#' `\"rect\"` or `\"segments\"` (where all four min-max coordinates are required),\n#' or `\"pointrange\"`, `\"errorbar\"`, or `\"ribbon\"` (where only `ymin` and\n#' `ymax` required alongside `x`). In the formula method the arguments\n#' can be specified as `ymin = var` if `var` is a variable in `data`.\n#' @param by grouping variable(s). The default behaviour is for groups to be\n#' represented in the form of distinct colours, which will also trigger an\n#' automatic legend. (See `legend` below for customization options.) However,\n#' groups can also be presented through other plot parameters (e.g., `pch` or\n#' `lty`) by passing an appropriate \"by\" keyword; see Examples. Note that\n#' continuous (i.e., gradient) colour legends are also supported if the user\n#' passes a numeric or integer to `by`. To group by multiple variables, wrap\n#' them with \\code{\\link[base]{interaction}}.\n#' @param facet the faceting variable(s) that you want arrange separate plot\n#' windows by. Can be specified in various ways:\n#' - In \"atomic\" form, e.g. `facet = fvar`. To facet by multiple variables in\n#' atomic form, simply interact them, e.g.\n#' `interaction(fvar1, fvar2)` or `factor(fvar1):factor(fvar2)`.\n#' - As a one-sided formula, e.g. `facet = ~fvar`. Multiple variables can be\n#' specified in the formula RHS, e.g. `~fvar1 + fvar2` or `~fvar1:fvar2`. Note\n#' that these multi-variable cases are _all_ treated equivalently and\n#' converted to `interaction(fvar1, fvar2, ...)` internally. (No distinction\n#' is made between different types of binary operators, for example, and so\n#' `f1+f2` is treated the same as `f1:f2`, is treated the same as `f1*f2`,\n#' etc.)\n#' - As a two-side formula, e.g. `facet = fvar1 ~ fvar2`. In this case, the\n#' facet windows are arranged in a fixed grid layout, with the formula LHS\n#' defining the facet rows and the RHS defining the facet columns. At present\n#' only single variables on each side of the formula are well supported. (We\n#' don't recommend trying to use multiple variables on either the LHS or RHS\n#' of the two-sided formula case.)\n#' - As a special `\"by\"` convenience keyword, in which case facets will match\n#' the grouping variable(s) passed to `by` above.\n#' @param facet.args an optional list of arguments for controlling faceting\n#' behaviour. (Ignored if `facet` is NULL.) Supported arguments are as\n#' follows:\n#' - `nrow`, `ncol` for overriding the default \"square\" facet window\n#' arrangement. Only one of these should be specified, but `nrow` will take\n#' precedence if both are specified together. Ignored if a two-sided formula\n#' is passed to the main `facet` argument, since the layout is arranged in a\n#' fixed grid.\n#' - `free` a logical value indicating whether the axis limits (scales) for\n#' each individual facet should adjust independently to match the range of\n#' the data within that facet. Default is `FALSE`. Separate free scaling of\n#' the x- or y-axis (i.e., whilst holding the other axis fixed) is not\n#' currently supported.\n#' - `fmar` a vector of form `c(b,l,t,r)` for controlling the base margin\n#' between facets in terms of lines. Defaults to the value of `tpar(\"fmar\")`,\n#' which should be `c(1,1,1,1)`, i.e. a single line of padding around each\n#' individual facet, assuming it hasn't been overridden by the user as part\n#' their global \\code{\\link[tinyplot]{tpar}} settings. Note some automatic\n#' adjustments are made for certain layouts, and depending on whether the plot\n#' is framed or not, to reduce excess whitespace. See\n#' \\code{\\link[tinyplot]{tpar}} for more details.\n#' - `cex`, `font`, `col`, `bg`, `border` for adjusting the facet title text\n#' and background. Default values for these arguments are inherited from\n#' \\code{\\link[tinyplot]{tpar}} (where they take a \"facet.\" prefix, e.g.\n#' `tpar(\"facet.cex\")`). The latter function can also be used to set these\n#' features globally for all `tinyplot` plots.\n#' @param formula a \\code{\\link[stats]{formula}} that optionally includes\n#' grouping variable(s) after a vertical bar, e.g. `y ~ x | z`. One-sided\n#' formulae are also permitted, e.g. `~ y | z`. Only a single `y` and `x`\n#' variable (if any) must be specified but multiple grouping variables\n#' can be included in different ways, e.g. `y ~ x | z1:z2` or\n#' `y ~ x | z1 + z2`. (These two representations are treated as equivalent;\n#' both are parsed as `interaction(z1, z2)` internally.) If arithmetic\n#' operators are used for transforming variables, they should be wrapped in\n#' `I()`, e.g., `I(y1/y2) ~ x`. Note that the `formula` and `x` arguments\n#' should not be specified in the same call.\n#' @param data a data.frame (or list) from which the variables in formula\n#' should be taken. A matrix is converted to a data frame.\n#' @param type character string or call to a `type_*()` function giving the\n#' type of plot desired.\n#' - NULL (default): Choose a sensible type for the type of `x` and `y` inputs\n#' (i.e., usually `\"p\"`).\n#' - 1-character values supported by \\code{\\link[graphics]{plot}}:\n#' - `\"p\"` Points\n#' - `\"l\"` Lines\n#' - `\"b\"` Both points and lines\n#' - `\"c\"` Empty points joined by lines\n#' - `\"o\"` Overplotted points and lines\n#' - `\"s\"` Stair steps\n#' - `\"S\"` Stair steps\n#' - `\"h\"` Histogram-like vertical lines\n#' - `\"n\"` Empty plot over the extent of the data\n#' - `tinyplot`-specific types. These fall into several categories:\n#' - Shapes:\n#' - `\"area\"` / [`type_area()`]: Plots the area under the curve from `y` = 0 to `y` = f(`x`).\n#' - `\"errorbar\"` / [`type_errorbar()`]: Adds error bars to points; requires `ymin` and `ymax`.\n#' - `\"pointrange\"` / [`type_pointrange()`]: Combines points with error bars.\n#' - `\"polygon\"` / [`type_polygon()`]: Draws polygons.\n#' - `\"polypath\"` / [`type_polypath()`]: Draws a path whose vertices are given in `x` and `y`.\n#' - `\"rect\"` / [`type_rect()`]: Draws rectangles; requires `xmin`, `xmax`, `ymin`, and `ymax`.\n#' - `\"ribbon\"` / [`type_ribbon()`]: Creates a filled area between `ymin` and `ymax`.\n#' - `\"segments\"` / [`type_segments()`]: Draws line segments between pairs of points.\n#' - `\"text\"` / [`type_text()`]: Add text annotations.\n#' - Visualizations:\n#' - `\"barplot\"` / [`type_barplot()`]: Creates a bar plot.\n#' - `\"boxplot\"` / [`type_boxplot()`]: Creates a box-and-whisker plot.\n#' - `\"density\"` / [`type_density()`]: Plots the density estimate of a variable.\n#' - `\"histogram\"` / [`type_histogram()`]: Creates a histogram of a single variable.\n#' - `\"jitter\"` / [`type_jitter()`]: Jittered points.\n#' - `\"qq\"` / [`type_qq()`]: Creates a quantile-quantile plot.\n#' - `\"ridge\"` / [`type_ridge()`]: Creates a ridgeline (aka joy) plot.\n#' - `\"rug\"` / [`type_rug()`]: Adds a rug to an existing plot.\n#' - `\"spineplot\"` / [`type_spineplot()`]: Creates a spineplot or spinogram.\n#' - `\"violin\"` / [`type_violin()`]: Creates a violin plot.\n#' - Models:\n#' - `\"loess\"` / [`type_loess()`]: Local regression curve.\n#' - `\"lm\"` / [`type_lm()`]: Linear regression line.\n#' - `\"glm\"` / [`type_glm()`]: Generalized linear model fit.\n#' - `\"spline\"` / [`type_spline()`]: Cubic (or Hermite) spline interpolation.\n#' - Functions:\n#' - [`type_abline()`]: line(s) with intercept and slope.\n#' - [`type_hline()`]: horizontal line(s).\n#' - [`type_vline()`]: vertical line(s).\n#' - [`type_function()`]: arbitrary function.\n#' - [`type_summary()`]: summarize `y` by unique values of `x`.\n#' @param legend one of the following options:\n#' - NULL (default), in which case the legend will be determined by the\n#' grouping variable. If there is no group variable (i.e., `by` is NULL) then\n#' no legend is drawn. If a grouping variable is detected, then an automatic\n#' legend is drawn to the _outer_ right of the plotting area. Note that the\n#' legend title and categories will automatically be inferred from the `by`\n#' argument and underlying data.\n#' - A convenience string indicating the legend position. The string should\n#' correspond to one of the position keywords supported by the base `legend`\n#' function, e.g. \"right\", \"topleft\", \"bottom\", etc. In addition, `tinyplot`\n#' supports adding a trailing exclamation point to these keywords, e.g.\n#' \"right!\", \"topleft!\", or \"bottom!\". This will place the legend _outside_\n#' the plotting area and adjust the margins of the plot accordingly. Finally,\n#' users can also turn off any legend printing by specifying \"none\".\n#' - Logical value, where TRUE corresponds to the default case above (same\n#' effect as specifying NULL) and FALSE turns the legend off (same effect as\n#' specifying \"none\").\n#' - A list or, equivalently, a dedicated `legend()` function with supported\n#' legend arguments, e.g. \"bty\", \"horiz\", and so forth.\n#' @param main a main title for the plot, see also `title`.\n#' @param sub a subtitle for the plot.\n#' @param xlab a label for the x axis, defaults to a description of x.\n#' @param ylab a label for the y axis, defaults to a description of y.\n#' @param ann a logical value indicating whether the default annotation (title\n#' and x and y axis labels) should appear on the plot.\n#' @param xlim the x limits (x1, x2) of the plot. Note that x1 > x2 is allowed\n#' and leads to a ‘reversed axis’. The default value, NULL, indicates that\n#' the range of the `finite` values to be plotted should be used.\n#' @param ylim the y limits of the plot.\n#' @param axes logical or character. Should axes be drawn (`TRUE` or `FALSE`)?\n#' Or alternatively what type of axes should be drawn: `\"standard\"` (with\n#' axis, ticks, and labels; equivalent to `TRUE`), `\"none\"` (no axes;\n#' equivalent to `FALSE`), `\"ticks\"` (only ticks and labels without axis line),\n#' `\"labels\"` (only labels without ticks and axis line), `\"axis\"` (only axis\n#' line and labels but no ticks). To control this separately for the two\n#' axes, use the character specifications for `xaxt` and/or `yaxt`.\n#' @param xaxt,yaxt character specifying the type of x-axis and y-axis,\n#' respectively. See `axes` for the possible values.\n#' @param xaxs,yaxs character specifying the style of the interval calculation\n#' used for the x-axis and y-axis, respectively. See\n#' \\code{\\link[graphics]{par}} for the possible values.\n#' @param xaxb,yaxb numeric vector (or character vector, if appropriate) giving\n#' the break points at which the axis tick-marks are to be drawn. Break points\n#' outside the range of the data will be ignored if the associated axis\n#' variable is categorical, or an explicit `x/ylim` range is given.\n#' @param xaxl,yaxl a function or a character keyword specifying the format of\n#' the x- or y-axis tick labels. Note that this is a post-processing step that\n#' affects the _appearance_ of the tick labels only; use in conjunction with\n#' `x/yaxb` if you would like to adjust the position of the tick marks too. In\n#' addition to user-supplied formatting functions (e.g., [`format`],\n#' [`toupper`], [`abs`], or other custom function), several convenience\n#' keywords (or their symbol equivalents) are available for common formatting\n#' transformations: `\"percent\"` (`\"%\"`), `\"comma\"` (`\",\"`), `\"log\"` (`\"l\"`),\n#' `\"dollar\"` (`\"$\"`), `\"euro\"` (`\"€\"`), or `\"sterling\"` (`\"£\"`). See the\n#' [`tinylabel`] documentation for examples.\n#' @param log a character string which contains `\"x\"` if the x axis is to be\n#' logarithmic, `\"y\"` if the y axis is to be logarithmic and `\"xy\"` or `\"yx\"`\n#' if both axes are to be logarithmic.\n#' @param flip logical. Should the plot orientation be flipped, so that the\n#' y-axis is on the horizontal plane and the x-axis is on the vertical plane?\n#' Default is FALSE.\n#' @param frame.plot a logical indicating whether a box should be drawn around\n#' the plot. Can also use `frame` as an acceptable argument alias.\n#' The default is to draw a frame if both axis types (set via `axes`, `xaxt`,\n#' or `yaxt`) include axis lines.\n#' @param grid argument for plotting a background panel grid, one of either:\n#' - a logical (i.e., `TRUE` to draw the grid), or\n#' - a panel grid plotting function like `grid()`.\n#' Note that this argument replaces the `panel.first` and `panel.last`\n#' arguments from base `plot()` and tries to make the process more seamless\n#' with better default behaviour. The default behaviour is determined by (and\n#' can be set globally through) the value of `tpar(\"grid\")`.\n#' @param palette one of the following options:\n#' - NULL (default), in which case the palette will be chosen according to\n#' the class and cardinality of the \"by\" grouping variable. For non-ordered\n#' factors or strings with a reasonable number of groups, this will inherit\n#' directly from the user's default \\code{\\link[grDevices]{palette}} (e.g.,\n#' \"R4\"). In other cases, including ordered factors and high cardinality, the\n#' \"Viridis\" palette will be used instead. Note that a slightly restricted\n#' version of the \"Viridis\" palette---where extreme color values have been\n#' trimmed to improve visual perception---will be used for ordered factors\n#' and continuous variables. In the latter case of a continuous grouping\n#' variable, we also generate a gradient legend swatch.\n#' - A convenience string corresponding to one of the many palettes listed by\n#' either `palette.pals()` or `hcl.pals()`. Note that the string can be\n#' case-insensitive (e.g., \"Okabe-Ito\" and \"okabe-ito\" are both valid).\n#' - A palette-generating function. This can be \"bare\" (e.g.,\n#' `palette.colors`) or \"closed\" with a set of named arguments (e.g.,\n#' `palette.colors(palette = \"Okabe-Ito\", alpha = 0.5)`). Note that any\n#' unnamed arguments will be ignored and the key `n` argument, denoting the\n#' number of colours, will automatically be spliced in as the number of\n#' groups.\n#' - A vector or list of colours, e.g. `c(\"darkorange\", \"purple\", \"cyan4\")`.\n#' If too few colours are provided for a discrete (qualitative) set of\n#' groups, then the colours will be recycled with a warning. For continuous\n#' (sequential) groups, a gradient palette will be interpolated. \n#' @param col plotting color. Character, integer, or vector of length equal to\n#' the number of categories in the `by` variable. See `col`. Note that the\n#' default behaviour in `tinyplot` is to vary group colors along any variables\n#' declared in the `by` argument. Thus, specifying colors manually should not\n#' be necessary unless users wish to override the automatic colors produced by\n#' this grouping process. Typically, this would only be done if grouping\n#' features are deferred to some other graphical parameter (i.e., passing the\n#' \"by\" keyword to one of `pch`, `lty`, `lwd`, or `bg`; see below.)\n#' @param pch plotting \"character\", i.e., symbol to use. Character, integer, or\n#' vector of length equal to the number of categories in the `by` variable.\n#' See `pch`. In addition, users can supply a special `pch = \"by\"` convenience\n#' argument, in which case the characters will automatically loop over the\n#' number groups. This automatic looping will begin at the global character\n#' value (i.e., `par(\"pch\")`) and recycle as necessary.\n#' @param lty line type. Character, integer, or vector of length equal to the\n#' number of categories in the `by` variable. See `lty`. In addition, users\n#' can supply a special `lty = \"by\"` convenience argument, in which case the\n#' line type will automatically loop over the number groups. This automatic\n#' looping will begin at the global line type value (i.e., `par(\"lty\")`) and\n#' recycle as necessary.\n#' @param lwd line width. Numeric scalar or vector of length equal to the\n#' number of categories in the `by` variable. See `lwd`. In addition, users\n#' can supply a special `lwd = \"by\"` convenience argument, in which case the\n#' line width will automatically loop over the number of groups. This\n#' automatic looping will be centered at the global line width value (i.e.,\n# ` par(\"lwd\")`) and pad on either side of that.\n#' @param bg background fill color for the open plot symbols 21:25 (see\n#' `points.default`), as well as ribbon and area plot types.\n#' Users can also supply either one of two special convenience arguments that\n#' will cause the background fill to inherit the automatic grouped coloring\n#' behaviour of `col`:\n#'\n#' - `bg = \"by\"` will insert a background fill that inherits the main color\n#' mappings from `col`.\n#' - `by = ` (i.e., a numeric in the range `[0,1]`) will insert\n#' a background fill that inherits the main color mapping(s) from `col`, but\n#' with added alpha-transparency.\n#'\n#' For both of these convenience arguments, note that the (grouped) `bg`\n#' mappings will persist even if the (grouped) `col` defaults are themselves\n#' overridden. This can be useful if you want to preserve the grouped palette\n#' mappings by background fill but not boundary color, e.g. filled points. See\n#' examples.\n#' @param fill alias for `bg`. If non-NULL values for both `bg` and `fill` are\n#' provided, then the latter will be ignored in favour of the former.\n#' @param alpha a numeric in the range `[0,1]` for adjusting the alpha channel\n#' of the color palette, where 0 means transparent and 1 means opaque. Use\n#' fractional values, e.g. `0.5` for semi-transparency.\n#' @param cex character expansion. A numerical vector (can be a single value)\n#' giving the amount by which plotting characters and symbols should be scaled\n#' relative to the default. Note that NULL is equivalent to 1.0, while NA\n#' renders the characters invisible.\n#' @param subset,na.action,drop.unused.levels arguments passed to `model.frame`\n#' when extracting the data from `formula` and `data`.\n#' @param add logical. If TRUE, then elements are added to the current plot rather\n#' than drawing a new plot window. Note that the automatic legend for the\n#' added elements will be turned off. See also [tinyplot_add], which provides\n#' a convenient wrapper around this functionality for layering on top of an\n#' existing plot without having to repeat arguments.\n#' @param draw a function that draws directly on the plot canvas (before `x` and\n#' `y` are plotted). The `draw` argument is primarily useful for adding common\n#' elements to each facet of a faceted plot, e.g.\n#' \\code{\\link[graphics]{abline}} or \\code{\\link[graphics]{text}}. Note that\n#' this argument is somewhat experimental and that _no_ internal checking is\n#' done for correctness; the provided argument is simply captured and\n#' evaluated as-is. See Examples.\n#' @param restore.par a logical value indicating whether the\n#' \\code{\\link[graphics]{par}} settings prior to calling `tinyplot` should be\n#' restored on exit. Defaults to FALSE, which makes it possible to add\n#' elements to the plot after it has been drawn. However, note the the outer\n#' margins of the graphics device may have been altered to make space for the\n#' `tinyplot` legend. Users can opt out of this persistent behaviour by\n#' setting to TRUE instead. See also [get_saved_par] for another option to\n#' recover the original \\code{\\link[graphics]{par}} settings, as well as\n#' longer discussion about the trade-offs involved.\n#' @param empty logical indicating whether the interior plot region should be\n#' left empty. The default is `FALSE`. Setting to `TRUE` has a similar effect\n#' to invoking `type = \"n\"` above, except that any legend artifacts owing to a\n#' particular plot type (e.g., lines for `type = \"l\"` or squares for\n#' `type = \"area\"`) will still be drawn correctly alongside the empty plot. In\n#' contrast,`type = \"n\"` implicitly assumes a scatterplot and so any legend\n#' will only depict points.\n#' @param file character string giving the file path for writing a plot to disk.\n#' If specified, the plot will not be displayed interactively, but rather sent\n#' to the appropriate external graphics device (i.e.,\n#' \\code{\\link[grDevices]{png}}, \\code{\\link[grDevices]{jpeg}},\n#' \\code{\\link[grDevices]{pdf}}, or \\code{\\link[grDevices]{svg}}). As a point\n#' of convenience, note that any global parameters held in `(t)par` are\n#' automatically carried over to the external device and don't need to be\n#' reset (in contrast to the conventional base R approach that requires\n#' manually opening and closing the device). The device type is determined by\n#' the file extension at the end of the provided path, and must be one of\n#' \".png\", \".jpg\" (\".jpeg\"), \".pdf\", or \".svg\". (Other file types may be\n#' supported in the future.) The file dimensions can be controlled by the\n#' corresponding `width` and `height` arguments below, otherwise will fall\n#' back to the `\"file.width\"` and `\"file.height\"` values held in\n#' \\code{\\link[tinyplot]{tpar}} (i.e., both defaulting to 7 inches, and where\n#' the default resolution for bitmap files is also specified as 300\n#' DPI).\n#' @param width numeric giving the plot width in inches. Together with `height`,\n#' typically used in conjunction with the `file` argument above, overriding the\n#' default values held in `tpar(\"file.width\", \"file.height\")`. If either `width`\n#' or `height` is specified, but a corresponding `file` argument is not\n#' provided as well, then a new interactive graphics device dimensions will be\n#' opened along the given dimensions. Note that this interactive resizing may\n#' not work consistently from within an IDE like RStudio that has an integrated\n#' graphics windows.\n#' @param height numeric giving the plot height in inches. Same considerations as\n#' `width` (above) apply, e.g. will default to `tpar(\"file.height\")` if not\n#' specified.\n#' @param asp the y/xy/x aspect ratio, see `plot.window`.\n#' @param ... other graphical parameters. If `type` is a character specification\n#' (such as `\"hist\"`) then any argument names that match those from the corresponding\n#' `type_*()` function (such as \\code{\\link{type_hist}}) are passed on to that.\n#' All remaining arguments from `...` can be further graphical parameters, see\n#' \\code{\\link[graphics]{par}}).\n#'\n#' @returns No return value, called for side effect of producing a plot.\n#'\n#' @details\n#' Disregarding the enhancements that it supports, `tinyplot` tries as far as\n#' possible to mimic the behaviour and syntax logic of the original base\n#' \\code{\\link[graphics]{plot}} function. Users should therefore be able to swap\n#' out existing `plot` calls for `tinyplot` (or its shorthand alias `plt`),\n#' without causing unexpected changes to the output.\n#'\n#' @importFrom grDevices axisTicks adjustcolor cairo_pdf colorRampPalette extendrange palette palette.colors palette.pals hcl.colors hcl.pals xy.coords png jpeg pdf svg dev.off dev.new dev.list\n#' @importFrom graphics abline arrows axis Axis axTicks box boxplot grconvertX grconvertY hist lines mtext par plot.default plot.new plot.window points polygon polypath segments rect text title\n#' @importFrom utils modifyList head tail\n#' @importFrom stats na.omit\n#' @importFrom tools file_ext\n#'\n#' @examples\n#' aq = transform(\n#' airquality,\n#' Month = factor(Month, labels = month.abb[unique(Month)])\n#' )\n#'\n#' # In most cases, `tinyplot` should be a drop-in replacement for regular\n#' # `plot` calls. For example:\n#'\n#' op = tpar(mfrow = c(1, 2))\n#' plot(0:10, main = \"plot\")\n#' tinyplot(0:10, main = \"tinyplot\")\n#' tpar(op) # restore original layout\n#'\n#' # Aside: `tinyplot::tpar()` is a (near) drop-in replacement for `par()`\n#'\n#' # Unlike vanilla plot, however, tinyplot allows you to characterize groups\n#' # using either the `by` argument or equivalent `|` formula syntax.\n#'\n#' with(aq, tinyplot(Day, Temp, by = Month)) ## atomic method\n#' tinyplot(Temp ~ Day | Month, data = aq) ## formula method\n#'\n#' # (Notice that we also get an automatic legend.)\n#'\n#' # You can also use the equivalent shorthand `plt()` alias if you'd like to\n#' # save on a few keystrokes\n#'\n#' plt(Temp ~ Day | Month, data = aq) ## shorthand alias\n#'\n#' # Use standard base plotting arguments to adjust features of your plot.\n#' # For example, change `pch` (plot character) to get filled points and `cex`\n#' # (character expansion) to increase their size.\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' pch = 16,\n#' cex = 2\n#' )\n#'\n#' # We can add alpha transparency for overlapping points\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' pch = 16,\n#' cex = 2,\n#' alpha = 0.3\n#' )\n#'\n#' # To get filled points with a common solid background color, use an\n#' # appropriate plotting character (21:25) and combine with one of the special\n#' # `bg` convenience arguments.\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' pch = 21, # use filled circles\n#' cex = 2,\n#' bg = 0.3, # numeric in [0,1] adds a grouped background fill with transparency\n#' col = \"black\" # override default color mapping; give all points a black border\n#' )\n#'\n#' # Converting to a grouped line plot is a simple matter of adjusting the\n#' # `type` argument.\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' type = \"l\"\n#' )\n#'\n#' # Similarly for other plot types, including some additional ones provided\n#' # directly by tinyplot, e.g. density plots or internal plots (ribbons,\n#' # pointranges, etc.)\n#'\n#' tinyplot(\n#' ~ Temp | Month,\n#' data = aq,\n#' type = \"density\",\n#' fill = \"by\"\n#' )\n#'\n#' # Facet plots are supported too. Facets can be drawn on their own...\n#'\n#' tinyplot(\n#' Temp ~ Day,\n#' facet = ~Month,\n#' data = aq,\n#' type = \"area\",\n#' main = \"Temperatures by month\"\n#' )\n#'\n#' # ... or combined/contrasted with the by (colour) grouping.\n#'\n#' aq = transform(aq, Summer = Month %in% c(\"Jun\", \"Jul\", \"Aug\"))\n#' tinyplot(\n#' Temp ~ Day | Summer,\n#' facet = ~Month,\n#' data = aq,\n#' type = \"area\",\n#' palette = \"dark2\",\n#' main = \"Temperatures by month and season\"\n#' )\n#'\n#' # Users can override the default square window arrangement by passing `nrow`\n#' # or `ncol` to the helper facet.args argument. Note that we can also reduce\n#' # axis label repetition across facets by turning the plot frame off.\n#'\n#' tinyplot(\n#' Temp ~ Day | Summer,\n#' facet = ~Month, facet.args = list(nrow = 1),\n#' data = aq,\n#' type = \"area\",\n#' palette = \"dark2\",\n#' frame = FALSE,\n#' main = \"Temperatures by month and season\"\n#' )\n#'\n#' # Use a two-sided formula to arrange the facet windows in a fixed grid.\n#' # LHS -> facet rows; RHS -> facet columns\n#'\n#' aq$hot = ifelse(aq$Temp >= 75, \"hot\", \"cold\")\n#' aq$windy = ifelse(aq$Wind >= 15, \"windy\", \"calm\")\n#' tinyplot(\n#' Temp ~ Day,\n#' facet = windy ~ hot,\n#' data = aq\n#' )\n#'\n#' # To add common elements to each facet, use the `draw` argument\n#'\n#' tinyplot(\n#' Temp ~ Day,\n#' facet = windy ~ hot,\n#' data = aq,\n#' draw = abline(h = 75, lty = 2, col = \"hotpink\")\n#' )\n#'\n#' # The (automatic) legend position and look can be customized using\n#' # appropriate arguments. Note the trailing \"!\" in the `legend` position\n#' # argument below. This tells `tinyplot` to place the legend _outside_ the plot\n#' # area.\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' type = \"l\",\n#' legend = legend(\"bottom!\", title = \"Month of the year\", bty = \"o\")\n#' )\n#'\n#' # The default group colours are inherited from either the \"R4\" or \"Viridis\"\n#' # palettes, depending on the number of groups. However, all palettes listed\n#' # by `palette.pals()` and `hcl.pals()` are supported as convenience strings,\n#' # or users can supply a valid palette-generating function for finer control\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' type = \"l\",\n#' palette = \"tableau\"\n#' )\n#'\n#' # It's possible to customize the look of your plots by setting graphical\n#' # parameters (e.g., via `(t)par`)... But a more convenient way is to just use\n#' # built-in themes (see `?tinytheme`).\n#'\n#' tinytheme(\"clean2\")\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' type = \"b\",\n#' alpha = 0.5,\n#' main = \"Daily temperatures by month\",\n#' sub = \"Brought to you by tinyplot\"\n#' )\n#' # reset the theme\n#' tinytheme()\n#'\n#' # For more examples and a detailed walkthrough, please see the introductory\n#' # tinyplot tutorial available online:\n#' # https://grantmcdermott.com/tinyplot/vignettes/introduction.html\n#'\n#' @rdname tinyplot\n#' @export\ntinyplot =\n function(x, ...) {\n UseMethod(\"tinyplot\")\n }\n\n#' @rdname tinyplot\n#' @export\ntinyplot.default = function(\n x = NULL,\n y = NULL,\n xmin = NULL,\n xmax = NULL,\n ymin = NULL,\n ymax = NULL,\n by = NULL,\n facet = NULL,\n facet.args = NULL,\n data = NULL,\n type = NULL,\n legend = NULL,\n main = NULL,\n sub = NULL,\n xlab = NULL,\n ylab = NULL,\n ann = par(\"ann\"),\n xlim = NULL,\n ylim = NULL,\n axes = TRUE,\n xaxt = NULL,\n yaxt = NULL,\n xaxs = NULL,\n yaxs = NULL,\n xaxb = NULL,\n yaxb = NULL,\n xaxl = NULL,\n yaxl = NULL,\n log = \"\",\n flip = FALSE,\n frame.plot = NULL,\n grid = NULL,\n palette = NULL,\n pch = NULL,\n lty = NULL,\n lwd = NULL,\n col = NULL,\n bg = NULL,\n fill = NULL,\n alpha = NULL,\n cex = 1,\n add = FALSE,\n draw = NULL,\n empty = FALSE,\n restore.par = FALSE,\n file = NULL,\n width = NULL,\n height = NULL,\n asp = NA,\n ...) {\n\n par_first = get_saved_par(\"first\")\n if (is.null(par_first)) set_saved_par(\"first\", par())\n\n assert_logical(add)\n \n # save for tinyplot_add()\n if (!add) {\n calls = sys.calls()\n idx = grep(\"^tinyplot\", sapply(calls, function(k) k[[1]]))\n if (length(idx) > 0) {\n options(tinyplot_last_call = calls[[idx[1]]])\n }\n ## TODO: remove the global option above and move to this when density is refactored\n # cal = match.call(call = sys.call(sys.parent()), expand.dots = TRUE)\n # assign(\".last_call\", cal, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n }\n\n dots = list(...)\n\n if (add) legend = FALSE\n draw = substitute(draw)\n\n\n # sanitize arguments\n\n # type factories vs. strings\n type = sanitize_type(type, x, y, dots)\n if (\"dots\" %in% names(type)) dots = type$dots\n \n # retrieve type-specific data and drawing functions\n type_data = type$data\n type_draw = type$draw\n type = type$name\n \n # area flag (mostly for legend)\n was_area_type = identical(type, \"area\")\n # check flip flag is logical \n assert_flag(flip)\n\n palette = substitute(palette)\n\n # themes\n if (is.null(palette)) palette = get_tpar(\"palette\", default = NULL)\n if (is.null(pch)) pch = get_tpar(\"pch\", default = NULL)\n\n xlabs = ylabs = NULL\n\n # type_ridge()\n ygroup = NULL\n\n # will be overwritten by some type_data() functions and ignored by others\n ribbon.alpha = sanitize_ribbon.alpha(NULL)\n\n ## handle defaults of axes, xaxt, yaxt, frame.plot\n ## - convert axes to character if necessary\n ## - set defaults of xaxt/yaxt (if these are NULL) based on axes\n ## - set logical axes based on xaxt/yaxt\n ## - set frame.plot default based on xaxt/yaxt\n if (isFALSE(axes)) {\n axes = xaxt = yaxt = \"none\"\n } else if (isTRUE(axes)) {\n axes = \"standard\"\n if (is.null(xaxt)) xaxt = get_tpar(\"xaxt\", default = \"standard\")\n if (is.null(yaxt)) yaxt = get_tpar(\"yaxt\", default = \"standard\")\n } else {\n xaxt = yaxt = axes\n }\n axis_types = c(\"standard\", \"none\", \"labels\", \"ticks\", \"axis\")\n axes = match.arg(axes, axis_types)\n xaxt = match.arg(xaxt, axis_types)\n yaxt = match.arg(yaxt, axis_types)\n xaxt = substr(match.arg(xaxt, axis_types), 1L, 1L)\n yaxt = substr(match.arg(yaxt, axis_types), 1L, 1L)\n axes = any(c(xaxt, yaxt) != \"n\")\n if (is.null(frame.plot) || !is.logical(frame.plot)) frame.plot = all(c(xaxt, yaxt) %in% c(\"s\", \"a\"))\n\n # Write plot to output file or window with fixed dimensions\n setup_device(file = file, width = width, height = height)\n if (!is.null(file)) on.exit(dev.off(), add = TRUE)\n\n # Save current graphical parameters\n opar = par(no.readonly = TRUE)\n if (restore.par || !is.null(facet)) {\n if (!is.null(file) || !is.null(width) || !is.null(height)) {\n opar$new = FALSE # catch for some interfaces\n }\n on.exit(par(opar), add = TRUE)\n }\n # set_orig_par(opar)\n set_saved_par(when = \"before\", opar)\n\n # catch for adding to existing facet plot\n if (!is.null(facet) && add) {\n recordGraphics(\n par(get_saved_par(when = \"after\")),\n list = list(),\n env = getNamespace('tinyplot')\n )\n }\n\n # Capture deparsed expressions early, before x, y and by are evaluated\n x_dep = if (!is.null(x)) {\n deparse1(substitute(x))\n } else if (type %in% c(\"rect\", \"segments\")) {\n x = NULL\n NULL\n }\n y_dep = if (is.null(y)) {\n deparse1(substitute(x))\n } else {\n deparse1(substitute(y))\n }\n by_dep = deparse1(substitute(by))\n null_by = is.null(by)\n\n ## coerce character variables to factors\n if (!is.null(x) && is.character(x)) x = factor(x)\n if (!is.null(y) && is.character(y)) y = factor(y)\n if (!null_by && is.character(by)) by = factor(by)\n\n # flag if x==by (currently only used for \"boxplot\", \"spineplot\" and \"ridges\" types)\n x_by = identical(x, by)\n\n facet_dep = deparse1(substitute(facet))\n # flag if facet==by\n facet_by = FALSE\n if (!is.null(facet) && length(facet) == 1 && facet == \"by\") {\n by = as.factor(by) ## if by==facet, then both need to be factors\n facet = by\n facet_by = TRUE\n } else if (!is.null(facet) && inherits(facet, \"formula\")) {\n facet = get_facet_fml(facet, data = data)\n if (isTRUE(attr(facet, \"facet_grid\"))) {\n facet.args[[\"nrow\"]] = attr(facet, \"facet_nrow\")\n }\n }\n facet_attr = attributes(facet) ## TODO: better solution for restoring facet attributes?\n null_facet = is.null(facet)\n\n if (is.null(x)) {\n ## Special catch for rect and segment plots without a specified y-var\n if (type %in% c(\"rect\", \"segments\")) {\n xmin_dep = deparse(substitute(xmin))\n xmax_dep = deparse(substitute(xmax))\n x_dep = paste0(\"[\", xmin_dep, \", \", xmax_dep, \"]\")\n x = rep(NA, length(x))\n }\n }\n if (is.null(y)) {\n ## Special catch for area and interval plots without a specified y-var\n if (type %in% c(\"rect\", \"segments\", \"pointrange\", \"errorbar\", \"ribbon\")) {\n ymin_dep = deparse(substitute(ymin))\n ymax_dep = deparse(substitute(ymax))\n y_dep = paste0(\"[\", ymin_dep, \", \", ymax_dep, \"]\")\n y = rep(NA, length(x))\n } else if (type == \"density\") {\n if (is.null(ylab)) ylab = \"Density\"\n } else if (type == \"function\") {\n if (is.null(ylab)) ylab = \"Frequency\"\n } else if (!(type %in% c(\"histogram\", \"barplot\"))) {\n y = x\n x = seq_along(x)\n if (is.null(xlab)) xlab = \"Index\"\n }\n }\n\n if (is.null(xlab)) xlab = x_dep\n if (is.null(ylab) && type != \"histogram\") ylab = y_dep\n \n # flag(s) indicating whether x/ylim was set by the user (needed later for\n # special case where facets are free but still want to set x/ylim manually)\n xlim_user = !is.null(xlim)\n ylim_user = !is.null(ylim)\n\n # alias\n if (is.null(bg) && !is.null(fill)) bg = fill\n\n datapoints = list(x = x, y = y, xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, ygroup = ygroup)\n datapoints = Filter(function(z) length(z) > 0, datapoints)\n datapoints = data.frame(datapoints)\n if (nrow(datapoints) > 0) {\n datapoints[[\"rowid\"]] = seq_len(nrow(datapoints))\n datapoints[[\"facet\"]] = if (!is.null(facet)) facet else \"\"\n datapoints[[\"by\"]] = if (!null_by) by else \"\"\n }\n\n ## initialize empty list with information that type_data\n ## can overwrite in order to pass on to type_draw\n type_info = list()\n\n if (!is.null(type_data)) {\n fargs = list(\n datapoints = datapoints,\n bg = bg,\n by = by,\n col = col,\n log = log,\n lty = lty,\n lwd = lwd,\n facet = facet,\n facet_by = facet_by,\n facet.args = facet.args,\n null_by = null_by,\n null_facet = null_facet,\n palette = palette,\n ribbon.alpha = ribbon.alpha,\n xaxt = xaxt,\n xaxb = xaxb,\n xaxl = xaxl,\n xlab = xlab,\n xlabs = xlabs,\n xlim = xlim,\n yaxt = yaxt,\n yaxb = yaxb,\n yaxl = yaxl,\n ylab = ylab,\n ylim = ylim\n )\n fargs = c(fargs, dots)\n list2env(do.call(type_data, fargs), environment())\n }\n\n\n # swap x and y values if flip is TRUE\n assert_flag(flip)\n # extra catch for boxplots\n # now swap the values\n if (isTRUE(flip)) {\n if (type != \"boxplot\") {\n # limits, labs, etc.\n xlim_cp = xlim\n xlim = ylim\n ylim = xlim_cp\n xlab_cp = xlab\n xlab = ylab\n ylab = xlab_cp\n xlabs_cp = xlabs\n xlabs = ylabs\n ylabs = xlabs_cp\n xaxt_cp = xaxt\n xaxt = yaxt\n yaxt = xaxt_cp\n xaxs_cp = xaxs\n xaxs = yaxs\n yaxs = xaxs_cp\n xaxb_cp = xaxb\n xaxb = yaxb\n yaxb = xaxb_cp\n xaxl_cp = xaxl\n xaxl = yaxl\n yaxl = xaxl_cp\n if (!is.null(log)) {\n log = if (log == \"x\") \"y\" else if (log == \"y\") \"x\" else log\n }\n # x/y vars\n x_cp = datapoints[[\"x\"]]\n datapoints[[\"x\"]] = datapoints[[\"y\"]]\n datapoints[[\"y\"]] = x_cp\n # x/y min and max vars\n xmin_cp = if (!is.null(datapoints[[\"xmin\"]])) datapoints[[\"xmin\"]] else NULL\n datapoints[[\"xmin\"]] = if (!is.null(datapoints[[\"ymin\"]])) datapoints[[\"ymin\"]] else NULL\n datapoints[[\"ymin\"]] = if (!is.null(xmin_cp)) xmin_cp else NULL\n xmax_cp = if (!is.null(datapoints[[\"xmax\"]])) datapoints[[\"xmax\"]] else NULL\n datapoints[[\"xmax\"]] = if (!is.null(datapoints[[\"ymax\"]])) datapoints[[\"ymax\"]] else NULL\n datapoints[[\"ymax\"]] = if (!is.null(xmax_cp)) xmax_cp else NULL\n # clean up\n rm(xlim_cp, xlab_cp, xlabs_cp, xaxt_cp, xaxs_cp, xaxb_cp, xaxl_cp, x_cp, xmin_cp, xmax_cp)\n } else {\n # We'll let boxplot(..., horizontal = TRUE) handle most of the adjustments\n # and just catch a few elements that we draw beforehand.\n xlab_cp = xlab\n xlab = ylab\n ylab = xlab_cp\n rm(xlab_cp)\n }\n }\n \n # For cases where x/yaxb is provided and corresponding x/ylabs is not null...\n # We can subset these here to provide breaks\n if (!is.null(xaxb) && !is.null(xlabs)) {\n xlabs = xlabs[names(xlabs) %in% xaxb]\n xaxb = NULL # don't need this any more\n }\n if (!is.null(yaxb) && !is.null(ylabs)) {\n ylabs = ylabs[names(ylabs) %in% yaxb]\n yaxb = NULL # don't need this any more\n }\n \n # plot limits\n fargs = lim_args(\n datapoints = datapoints,\n xlim = xlim, ylim = ylim,\n xaxb = xaxb, yaxb = yaxb,\n xlim_user = xlim_user, ylim_user = ylim_user,\n type = type\n )\n list2env(fargs, environment())\n\n\n # split data\n by_ordered = FALSE\n by_continuous = !null_by && inherits(datapoints$by, c(\"numeric\", \"integer\"))\n if (isTRUE(by_continuous) && type %in% c(\"l\", \"b\", \"o\", \"ribbon\", \"polygon\", \"polypath\", \"boxplot\")) {\n warning(\"\\nContinuous legends not supported for this plot type. Reverting to discrete legend.\")\n by_continuous = FALSE\n } else if (!null_by) {\n by_ordered = is.ordered(by)\n }\n\n if (length(unique(datapoints$facet)) == 1) {\n datapoints[[\"facet\"]] = NULL\n }\n if (!is.null(datapoints$facet)) {\n split_data = split(datapoints, datapoints$facet)\n split_data = lapply(split_data, as.list)\n } else {\n split_data = list(as.list(datapoints))\n }\n\n # aesthetics by group: col, bg, etc.\n ngrps = if (null_by) 1L else if (is.factor(by)) length(levels(by)) else if (by_continuous) 100L else length(unique(by))\n pch = by_pch(ngrps = ngrps, type = type, pch = pch)\n lty = by_lty(ngrps = ngrps, type = type, lty = lty)\n lwd = by_lwd(ngrps = ngrps, type = type, lwd = lwd)\n col = by_col(\n ngrps = ngrps, col = col, palette = palette,\n gradient = by_continuous, ordered = by_ordered, alpha = alpha)\n bg = by_bg(\n adjustcolor = adjustcolor, alpha = alpha, bg = bg, by = by, by_continuous = by_continuous,\n by_ordered = by_ordered, col = col, fill = fill, palette = substitute(palette),\n ribbon.alpha = ribbon.alpha, ngrps = ngrps, type = type)\n \n ncolors = length(col)\n lgnd_labs = rep(NA, times = ncolors)\n if (isTRUE(by_continuous)) {\n ## Identify the pretty break points for our labels\n nlabs = 5\n ncolors = length(col)\n ubyvar = unique(by)\n byvar_range = range(ubyvar)\n pbyvar = pretty(byvar_range, n = nlabs)\n pbyvar = pbyvar[pbyvar >= byvar_range[1] & pbyvar <= byvar_range[2]]\n # optional thinning\n if (length(ubyvar) == 2 && all(ubyvar %in% pbyvar)) {\n pbyvar = ubyvar\n } else if (length(pbyvar) > nlabs) {\n pbyvar = pbyvar[seq_along(pbyvar) %% 2 == 0]\n }\n ## Find the (approximate) location of our pretty labels\n pidx = rescale_num(c(byvar_range, pbyvar), to = c(1, ncolors))[-c(1:2)]\n pidx = round(pidx)\n lgnd_labs[pidx] = pbyvar\n }\n\n # Determine the number and arrangement of facets.\n # Note: We're do this up front, so we can make some adjustments to legend cex\n # next (if there are facets). But the actual drawing of the facets will only\n # come later.\n attributes(datapoints$facet) = facet_attr ## TODO: better solution for restoring facet attributes?\n fargs = facet_layout(facet = datapoints$facet, facet.args = facet.args, add = add)\n list2env(fargs, environment())\n\n #\n ## Global plot elements (legend and titles)\n #\n\n # place and draw the legend\n has_legend = FALSE # simple indicator variable for later use\n\n if (!exists(\"legend_args\")) {\n legend_args = dots[[\"legend_args\"]]\n }\n if (is.null(legend_args)) legend_args = list(x = NULL)\n legend = substitute(legend)\n\n if (isFALSE(legend)) {\n legend = \"none\"\n } else if (isTRUE(legend)) {\n legend = NULL\n }\n if (!is.null(legend) && legend == \"none\") {\n legend_args[[\"x\"]] = \"none\"\n }\n\n if (null_by) {\n if (is.null(legend)) {\n legend = \"none\"\n legend_args[[\"x\"]] = \"none\"\n }\n }\n\n if ((is.null(legend) || legend != \"none\") && !add) {\n if (isFALSE(by_continuous)) {\n if (ngrps > 1) {\n lgnd_labs = if (is.factor(datapoints$by)) levels(datapoints$by) else unique(datapoints$by)\n } else {\n lgnd_labs = ylab\n }\n }\n\n has_sub = !is.null(sub)\n\n if (isTRUE(was_area_type) || isTRUE(type %in% c(\"area\", \"rect\", \"hist\", \"histogram\"))) {\n legend_args[[\"pt.lwd\"]] = par(\"lwd\")\n legend_args[[\"lty\"]] = 0\n }\n\n draw_legend(\n legend = legend,\n legend_args = legend_args,\n by_dep = by_dep,\n lgnd_labs = lgnd_labs,\n type = type,\n pch = pch,\n lty = lty,\n lwd = lwd,\n col = col,\n bg = bg,\n gradient = by_continuous,\n cex = cex * cex_fct_adj,\n has_sub = has_sub\n )\n\n has_legend = TRUE\n } else if (legend_args[[\"x\"]] == \"none\" && !add) {\n omar = par(\"mar\")\n ooma = par(\"oma\")\n topmar_epsilon = 0.1\n\n # Catch to avoid recursive offsets, e.g. repeated tinyplot calls with\n # \"bottom!\" legend position.\n\n ## restore inner margin defaults\n ## (in case the plot region/margins were affected by the preceding tinyplot call)\n if (any(ooma != 0)) {\n if (ooma[1] != 0 && omar[1] == par(\"mgp\")[1] + 1 * par(\"cex.lab\")) omar[1] = 5.1\n if (ooma[2] != 0 && omar[2] == par(\"mgp\")[1] + 1 * par(\"cex.lab\")) omar[2] = 4.1\n if (ooma[3] == topmar_epsilon && omar[3] != 4.1) omar[3] = 4.1\n if (ooma[4] != 0 && omar[4] == 0) omar[4] = 2.1\n par(mar = omar)\n }\n ## restore outer margin defaults (with a catch for custom mfrow plots)\n if (all(par(\"mfrow\") == c(1, 1))) {\n par(omd = c(0, 1, 0, 1))\n }\n\n # clean up for now\n rm(omar, ooma, topmar_epsilon)\n\n # Draw new plot\n plot.new()\n }\n\n # Titles. Only draw these if add = FALSE\n if (!add) {\n # main title\n # Note that we include a special catch for the main title if legend is\n # \"top!\" (and main is specified in the first place).\n legend_eval = tryCatch(eval(legend), error = function(e) NULL)\n # Extra bit of footwork if user passed legend = legend(...) instead of\n # legend = list(...), since the call environment is tricky\n if (is.null(legend_eval)) {\n legend_eval = tryCatch(paste0(legend)[[2]], error = function(e) NULL)\n }\n\n adj_title = !is.null(legend) && (legend == \"top!\" || (!is.null(legend_args[[\"x\"]]) && legend_args[[\"x\"]] == \"top!\") || (is.list(legend_eval) && legend_eval[[1]] == \"top!\"))\n\n # For the \"top!\" legend case, bump main title up to make space for the\n # legend beneath it: Take the normal main title line gap (i.e., 1.7 lines)\n # and add the difference between original top margin and new one (i.e.,\n # which should equal the height of the new legend). Note that we also\n # include a 0.1 epsilon bump, which we're using to reset the tinyplot\n # window in case of recursive \"top!\" calls. (See draw_legend code.)\n\n if (isTRUE(adj_title)) {\n line_main = par(\"mar\")[3] - opar[[\"mar\"]][3] + 1.7 + 0.1\n } else {\n line_main = NULL\n }\n\n if (!is.null(sub)) {\n if (isTRUE(get_tpar(\"side.sub\", 1) == 3)) {\n if (is.null(line_main)) line_main = par(\"mgp\")[3] + 1.7 - .1\n line_main = line_main + 1.2\n }\n if (isTRUE(get_tpar(\"side.sub\", 1) == 3)) {\n line_sub = get_tpar(\"line.sub\", 1.7)\n } else {\n line_sub = get_tpar(\"line.sub\", 4)\n }\n args = list(\n text = sub,\n line = line_sub,\n cex = get_tpar(\"cex.sub\", 1.2),\n col = get_tpar(\"col.sub\", \"black\"),\n adj = get_tpar(c(\"adj.sub\", \"adj\")),\n font = get_tpar(\"font.sub\", 1),\n side = get_tpar(\"side.sub\", 1),\n las = 1\n )\n args = Filter(function(x) !is.null(x), args)\n do.call(mtext, args)\n }\n\n if (!is.null(main)) {\n args = list(\n main = main,\n line = line_main,\n cex.main = get_tpar(\"cex.main\", 1.4),\n col.main = get_tpar(\"col.main\", \"black\"),\n font.main = get_tpar(\"font.main\", 2),\n adj = get_tpar(c(\"adj.main\", \"adj\"), 3))\n args = Filter(function(x) !is.null(x), args)\n do.call(title, args)\n }\n\n\n # Axis titles\n args = list(xlab = xlab)\n args[[\"adj\"]] = get_tpar(c(\"adj.xlab\", \"adj\"))\n do.call(title, args)\n args = list(ylab = ylab)\n args[[\"adj\"]] = get_tpar(c(\"adj.ylab\", \"adj\"))\n do.call(title, args)\n }\n\n #\n ## Exterior plot elements (plot and facet windows, axes, etc.)\n #\n\n omar = NULL # Placeholder variable for now, which we re-assign as part of facet margins\n\n # placeholders for facet_window_args() call\n facet_newlines = facet_text = facet_rect = facet_font = facet_col = facet_bg = facet_border = NULL\n\n if (!is.null(facet) && !add) {\n if (is.null(omar)) omar = par(\"mar\")\n\n # Grab some of the customizable facet args that we'll be using later\n facet_rect = FALSE\n facet_text = .tpar[[\"facet.cex\"]]\n facet_font = .tpar[[\"facet.font\"]]\n facet_col = .tpar[[\"facet.col\"]]\n facet_bg = .tpar[[\"facet.bg\"]]\n facet_border = .tpar[[\"facet.border\"]]\n if (!is.null(facet.args)) {\n if (!is.null(facet.args[[\"cex\"]])) facet_text = facet.args[[\"cex\"]]\n if (!is.null(facet.args[[\"col\"]])) facet_col = facet.args[[\"col\"]]\n if (!is.null(facet.args[[\"font\"]])) facet_font = facet.args[[\"font\"]]\n if (!is.null(facet.args[[\"bg\"]])) facet_bg = facet.args[[\"bg\"]]\n if (!is.null(facet.args[[\"border\"]])) facet_border = facet.args[[\"border\"]]\n }\n if (!is.null(facet_bg) || !is.null(facet_border)) facet_rect = TRUE\n\n # Need extra adjustment to top margin if facet titles have \"\\n\" newline\n # separator. (Note that we'll also need to take account for this in the\n # individual facet margins / gaps further below.)\n facet_newlines = lengths(gregexpr(\"\\n\", grep(\"\\\\n\", facets, value = TRUE)))\n # if (length(facet_newlines)==0) facet_newlines = 0\n # omar[3] = omar[3] + max(facet_newlines)\n facet_newlines = ifelse(length(facet_newlines) == 0, 0, max(facet_newlines))\n omar[3] = omar[3] + facet_newlines * facet_text / cex_fct_adj\n # apply the changes\n par(mar = omar)\n }\n\n # Now draw the individual facet windows (incl. axes, grid lines, and facet titles)\n # Will be skipped if adding to an existing plot; see ?facet\n\n facet_window_args = recordGraphics(\n draw_facet_window(\n add = add,\n # facet-specific args\n cex_fct_adj = cex_fct_adj,\n facet.args = facet.args,\n facet_newlines = facet_newlines, facet_font = facet_font,\n facet_rect = facet_rect, facet_text = facet_text,\n facet_col = facet_col, facet_bg = facet_bg, facet_border = facet_border,\n facet = facet,\n facets = facets, ifacet = ifacet,\n nfacets = nfacets, nfacet_cols = nfacet_cols, nfacet_rows = nfacet_rows,\n # axes args\n axes = axes, flip = flip, frame.plot = frame.plot,\n oxaxis = oxaxis, oyaxis = oyaxis,\n xlabs = xlabs, xlim = xlim, xlim_user = xlim_user, xaxt = xaxt, xaxs = xaxs, xaxb = xaxb, xaxl = xaxl,\n ylabs = ylabs, ylim = ylim, ylim_user = ylim_user, yaxt = yaxt, yaxs = yaxs, yaxb = yaxb, yaxl = yaxl,\n asp = asp, log = log,\n # other args (in approx. alphabetical + group ordering)\n dots = dots,\n draw = draw,\n grid = grid,\n has_legend = has_legend,\n type = type,\n x = x, xmax = xmax, xmin = xmin,\n y = y, ymax = ymax, ymin = ymin\n ),\n list = list(\n add = add,\n cex_fct_adj = cex_fct_adj,\n facet.args = facet.args,\n facet_newlines = facet_newlines, facet_font = facet_font,\n facet_rect = facet_rect, facet_text = facet_text,\n facet_col = facet_col, facet_bg = facet_bg, facet_border = facet_border,\n facet = datapoints$facet,\n facets = facets, ifacet = ifacet,\n nfacets = nfacets, nfacet_cols = nfacet_cols, nfacet_rows = nfacet_rows,\n axes = axes, flip = flip, frame.plot = frame.plot,\n oxaxis = oxaxis, oyaxis = oyaxis,\n xlabs = xlabs, xlim = xlim, xlim_user = xlim_user, xaxt = xaxt, xaxs = xaxs, xaxb = xaxb, xaxl = xaxl,\n ylabs = ylabs, ylim = ylim, ylim_user = ylim_user, yaxt = yaxt, yaxs = yaxs, yaxb = yaxb, yaxl = yaxl,\n asp = asp, log = log,\n dots = dots,\n draw = draw,\n grid = grid,\n has_legend = has_legend,\n type = type,\n x = datapoints$x, xmax = datapoints$xmax, xmin = datapoints$xmin,\n y = datapoints$y, ymax = datapoints$ymax, ymin = datapoints$ymin\n ),\n getNamespace(\"tinyplot\")\n )\n list2env(facet_window_args, environment())\n\n\n #\n ## Interior plot elements\n #\n\n # Finally, we can draw all of the plot elements (points, lines, etc.)\n # We'll do this via a nested loops:\n # 1) Outer loop over facets\n # 2) Inner loop over groups\n\n ## Outer loop over the facets\n for (i in seq_along(split_data)) {\n # Split group-level data again to grab any \"by\" groups\n idata = split_data[[i]]\n iby = idata[[\"by\"]]\n if (!null_by) { ## maybe all(iby==\"\")\n if (isTRUE(by_continuous)) {\n idata[[\"col\"]] = col[round(rescale_num(idata$by, from = range(datapoints$by), to = c(1, 100)))]\n idata[[\"bg\"]] = bg[round(rescale_num(idata$by, from = range(datapoints$by), to = c(1, 100)))]\n idata = list(idata)\n } else {\n idata = lapply(idata, split, iby)\n idata = do.call(function(...) Map(\"list\", ...), idata)\n }\n } else {\n idata = list(idata)\n if (isTRUE(by_continuous)) {\n if (length(col) != 1) {\n idata[[1]][[\"col\"]] = col[round(rescale_num(by, to = c(1, 100)))]\n } else {\n idata[[1]][[\"col\"]] = col\n }\n if (length(bg) != 1) {\n idata[[1]][[\"bg\"]] = bg[round(rescale_num(by, to = c(1, 100)))]\n } else {\n idata[[1]][[\"bg\"]] = bg\n }\n }\n }\n \n # Set the facet \"window\" manually\n # See: https://github.com/grantmcdermott/tinyplot/issues/65\n if (nfacets > 1) {\n mfgi = ceiling(i / nfacet_cols)\n mfgj = i %% nfacet_cols\n if (mfgj == 0) mfgj = nfacet_cols\n par(mfg = c(mfgi, mfgj))\n\n # For free facets, we need to reset par(usr) based extent of that\n # particular facet... which we calculated and saved to the .fusr env var\n # (list) back in draw_facet_window()\n if (isTRUE(facet.args[[\"free\"]])) {\n fusr = get(\".fusr\", envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n par(usr = fusr[[i]])\n }\n }\n\n\n ## Inner loop over the \"by\" groupings\n for (ii in seq_along(idata)) {\n icol = col[ii]\n ibg = bg[ii]\n ipch = pch[ii]\n ilty = lty[ii]\n ilwd = lwd[ii]\n \n ix = idata[[ii]][[\"x\"]]\n iy = idata[[ii]][[\"y\"]]\n iz = idata[[ii]][[\"z\"]]\n ixmin = idata[[ii]]$xmin\n ixmax = idata[[ii]]$xmax\n iymin = idata[[ii]]$ymin\n iymax = idata[[ii]]$ymax\n ilabels = idata[[ii]][[\"labels\"]]\n\n if (isTRUE(by_continuous)) {\n icol = idata[[ii]]$col\n ibg = idata[[ii]]$bg\n }\n\n # empty plot flag\n empty_plot = FALSE\n if (isTRUE(empty) || isTRUE(type == \"n\") || ((length(ix) == 0) && !(type %in% c(\"histogram\", \"hist\", \"rect\", \"segments\", \"spineplot\")))) {\n empty_plot = TRUE\n }\n\n # Draw the individual plot elements...\n if (!isTRUE(empty_plot)) {\n if (is.null(type_draw)) {\n type_draw = switch(type,\n \"ribbon\" = type_ribbon()$draw,\n \"polygon\" = type_polygon()$draw,\n \"rect\" = type_rect()$draw,\n \"p\" = ,\n \"points\" = type_points()$draw,\n \"l\" = ,\n \"o\" = ,\n \"b\" = ,\n \"c\" = ,\n \"h\" = ,\n \"s\" = ,\n \"S\" = type_lines(type = type)$draw\n )\n }\n type_draw(\n ibg = ibg,\n icol = icol,\n ilty = ilty,\n ilwd = ilwd,\n ipch = ipch,\n ix = ix,\n ixmax = ixmax,\n ixmin = ixmin,\n iy = iy,\n iymax = iymax,\n iymin = iymin,\n ilabels = ilabels,\n iz = iz,\n cex = cex,\n dots = dots,\n type = type,\n x_by = x_by,\n by_continuous = by_continuous,\n iby = ii,\n ifacet = i,\n facet_by = facet_by,\n data_facet = idata,\n ngrps = ngrps,\n nfacets = nfacets,\n flip = flip,\n type_info = type_info,\n facet_window_args = facet_window_args\n )\n }\n }\n }\n \n if (!add) {\n # save end pars for possible recall later\n recordGraphics(\n {\n apar = par(no.readonly = TRUE)\n set_saved_par(when = \"after\", apar)\n },\n list = list(), \n env = getNamespace('tinyplot')\n )\n }\n\n}\n\n\n\n\n#' @rdname tinyplot\n#' @importFrom stats as.formula model.frame terms\n#' @export\ntinyplot.formula = function(\n x = NULL,\n data = parent.frame(),\n facet = NULL,\n facet.args = NULL,\n type = NULL,\n xmin = NULL,\n xmax = NULL,\n ymin = NULL,\n ymax = NULL,\n xlim = NULL,\n ylim = NULL,\n # log = \"\",\n main = NULL,\n sub = NULL,\n xlab = NULL,\n ylab = NULL,\n ann = par(\"ann\"),\n axes = TRUE,\n frame.plot = NULL,\n asp = NA,\n grid = NULL,\n pch = NULL,\n col = NULL,\n lty = NULL,\n lwd = NULL,\n restore.par = FALSE,\n formula = NULL,\n subset = NULL,\n na.action = NULL,\n drop.unused.levels = TRUE,\n ...) {\n ## formula for variables must be specified through 'x' or 'formula' but not both\n if (is.null(x)) {\n if (missing(formula)) {\n stop(\"plot formula must be specified by either 'x' or 'formula' argument\")\n }\n } else {\n if (missing(formula)) {\n formula = x\n } else {\n warning(\"only one of the arguments 'x' and 'formula' should be specified, defaulting to the 'formula' argument\")\n }\n }\n\n ## placeholder for legend title\n legend_args = list(x = NULL)\n\n ## turn facet into a formula if it does not evaluate successfully\n if (inherits(try(facet, silent = TRUE), \"try-error\")) {\n facet = as.formula(paste(\"~\", deparse(substitute(facet))))\n environment(facet) = environment(formula)\n }\n\n ## process all formulas\n tf = tinyformula(formula, facet)\n\n ## set up model frame\n m = match.call(expand.dots = FALSE)\n m = m[c(1L, match(c(\"formula\", \"data\", \"subset\", \"na.action\", \"drop.unused.levels\", \"xmin\", \"xmax\", \"ymin\", \"ymax\"), names(m), 0L))]\n m$formula = tf$full\n ## need stats:: for non-standard evaluation\n m[[1L]] = quote(stats::model.frame)\n mf = eval.parent(m)\n\n ## extract x\n x = tinyframe(tf$x, mf)\n xnam = names(x)[[1L]]\n if (length(names(x)) != 1L) warning(\n paste(\"formula should specify exactly one x-variable, using:\", xnam),\n \"\\nif you want to use arithmetic operators, make sure to wrap them inside I()\")\n x = x[[xnam]]\n\n ## extract y (if any)\n y = tinyframe(tf$y, mf)\n if (!is.null(y)) {\n ynam = names(y)[[1L]]\n if (length(names(y)) > 1L) warning(paste(\"formula should specify at most one y-variable, using:\", ynam),\n \"\\nif you want to use arithmetic operators, make sure to wrap them inside I()\")\n y = y[[ynam]]\n }\n\n ## extract by (if any)\n by = tinyframe(tf$by, mf)\n if (!is.null(by)) {\n bynam = names(by)\n by = if (length(bynam) == 1L) by[[bynam]] else interaction(by, sep = \":\")\n }\n\n ## extract x/y facet (if formula)\n if (!is.null(tf$xfacet) || !is.null(tf$yfacet)) {\n xfacet = tinyframe(tf$xfacet, mf)\n yfacet = tinyframe(tf$yfacet, mf)\n if (!is.null(xfacet)) xfacet = if (ncol(xfacet) == 1L) xfacet[[1L]] else interaction(xfacet, sep = \":\")\n if (!is.null(yfacet)) yfacet = if (ncol(yfacet) == 1L) yfacet[[1L]] else interaction(yfacet, sep = \":\")\n if (is.null(yfacet)) {\n facet = xfacet\n } else {\n facet = interaction(xfacet, yfacet, sep = \"~\")\n attr(facet, \"facet_grid\") = TRUE\n attr(facet, \"facet_nrow\") = length(unique(yfacet))\n }\n }\n\n ## nice axis and legend labels\n dens_type = (is.atomic(type) && identical(type, \"density\")) || (!is.atomic(type) && identical(type$name, \"density\"))\n hist_type = (is.atomic(type) && type %in% c(\"hist\", \"histogram\")) || (!is.atomic(type) && identical(type$name, \"histogram\"))\n if (!is.null(type) && dens_type) {\n # if (is.null(ylab)) ylab = \"Density\" ## rather assign ylab as part of internal type_density() logic\n if (is.null(xlab)) xlab = xnam\n } else if (!is.null(type) && hist_type) {\n # if (is.null(ylab)) ylab = \"Frequency\" ## rather assign ylab as part of internal type_histogram() logic\n if (is.null(xlab)) xlab = xnam\n } else if (is.null(y)) {\n if (is.null(ylab)) ylab = xnam\n if (is.null(xlab)) xlab = \"Index\"\n } else {\n if (is.null(ylab)) ylab = ynam\n if (is.null(xlab)) xlab = xnam\n }\n if (!is.null(by)) {\n legend_args[[\"title\"]] = if (length(bynam) == 1L) bynam else sprintf(\"interaction(%s)\", paste(bynam, collapse = \", \"))\n }\n\n tinyplot.default(\n x = x, y = y, by = by,\n facet = facet, facet.args = facet.args,\n data = data,\n type = type,\n xmin = mf[[\"(xmin)\"]],\n xmax = mf[[\"(xmax)\"]],\n ymin = mf[[\"(ymin)\"]],\n ymax = mf[[\"(ymax)\"]],\n xlim = xlim,\n ylim = ylim,\n # log = \"\",\n main = main,\n sub = sub,\n xlab = xlab,\n ylab = ylab,\n ann = ann,\n axes = axes,\n frame.plot = frame.plot,\n asp = asp,\n grid = grid,\n legend_args = legend_args,\n pch = pch,\n col = col,\n lty = lty,\n lwd = lwd,\n restore.par = restore.par,\n ...\n )\n}\n\n#' @rdname tinyplot\n#' @export\ntinyplot.density = function(\n x = NULL,\n type = c(\"l\", \"area\"),\n ...) {\n \n dots = list(...)\n \n if (!is.null(dots[[\"by\"]]) || !is.null(dots[[\"facet\"]])) {\n stop(\n '\\nGrouped and/or faceted plots are no longer supported with the tinyplot.density() method. ',\n '\\nPlease use the dedicated type argument instead, e.g. `tinyplot(..., type = \"density\")`. See `?type_density` for details.',\n '\\n\\nThis breaking change was introduced in tinyplot v0.3.0.'\n )\n }\n \n type = match.arg(type)\n \n ## override if bg = \"by\"\n if (!is.null(dots[[\"bg\"]]) || !is.null(dots[[\"fill\"]])) type = \"area\"\n \n if (inherits(x, \"density\")) {\n object = x\n # legend_args = list(x = NULL)\n # # Grab by label to pass on legend title to tinyplot.default\n # legend_args[[\"title\"]] = deparse(substitute(by))\n } else {\n ## An internal catch for non-density objects that were forcibly\n ## passed to tinyplot.density (e.g., via a one-side formula)\n if (anyNA(x)) {\n x = na.omit(x)\n x = as.numeric(x)\n }\n object = density(x)\n }\n \n x = object$x\n y = object$y\n \n if (type == \"area\") {\n ymin = rep(0, length(y))\n ymax = y\n # # set extra legend params to get bordered boxes with fill\n # legend_args[[\"x.intersp\"]] = 1.25\n # legend_args[[\"lty\"]] = 0\n # legend_args[[\"pt.lwd\"]] = 1\n }\n \n # splice in change arguments\n dots[[\"x\"]] = x\n dots[[\"y\"]] = y\n dots[[\"type\"]] = type\n \n ## axes range\n if (is.null(dots[[\"xlim\"]])) dots[[\"xlim\"]] = range(x)\n if (is.null(dots[[\"ylim\"]])) dots[[\"ylim\"]] = range(y)\n \n ## nice labels and titles\n if (is.null(dots[[\"ylab\"]])) dots[[\"ylab\"]] = \"Density\"\n if (is.null(dots[[\"xlab\"]])) dots[[\"xlab\"]] = paste0(\"N = \", object$n, \" Bandwidth = \", sprintf(\"%.4g\", object$bw))\n if (is.null(dots[[\"main\"]])) dots[[\"main\"]] = paste0(paste(object$call, collapse = \"(x = \"), \")\")\n \n do.call(tinyplot.default, args = dots)\n \n}\n\n\n#' @export\n#' @name plt\n#' @rdname tinyplot\nplt = tinyplot\n"], ["/tinyplot/R/tinytheme.R", "#' Set or Reset Plot Themes for `tinyplot`\n#'\n#' @md\n#' @description\n#' The `tinytheme` function sets or resets the theme for plots created with\n#' `tinyplot`. Themes control the appearance of plots, such as text alignment,\n#' font styles, axis labels, and even dynamic margin adjustment to reduce\n#' whitespace.\n#'\n#' @param theme A character string specifying the name of the theme to apply.\n#' Themes are arranged in an approximate hierarchy, adding or subtracting\n#' elements in the order presented below. Note that several themes are\n#' _dynamic_, in the sense that they attempt to reduce whitespace in a way\n#' that is responsive to the length of axes labels, tick marks, etc. These\n#' dynamic plots are marked with an asterisk (*) below.\n#' \n#' - `\"default\"`: inherits the user's default base graphics settings.\n#' - `\"basic\"`: light modification of `\"default\"`, only adding filled points, a panel background grid, and light gray background to facet titles.\n#' - `\"clean\"` (*): builds on `\"basic\"` by moving the subtitle above the plotting area, adding horizontal axis labels, employing tighter default plot margins and title gaps to reduce whitespace, and setting different default palettes (\"Tableau 10\" for discrete colors and \"agSunset\" for gradient colors). The first of our dynamic themes and the foundation for several derivative themes that follow below.\n#' - `\"clean2\"` (*): removes the plot frame (box) from `\"clean\"`.\n#' - `\"classic\"` (*): connects the axes in a L-shape, but removes the other top and right-hand edges of the plot frame (box). Also sets the \"Okabe-Ito\" palette as a default for discrete colors. Inspired by the **ggplot2** theme of the same name. \n#' - `\"bw\"` (*): similar to `\"clean\"`, except uses thinner lines for the plot frame (box), solid grid lines, and sets the \"Okabe-Ito\" palette as a default for discrete colors. Inspired by the **ggplot2** theme of the same name. \n#' - `\"minimal\"` (*): removes the plot frame (box) from `\"bw\"`, as well as the background for facet titles. Inspired by the **ggplot2** theme of the same name. \n#' - `\"ipsum\"` (*): similar to `\"minimal\"`, except subtitle is italicised and axes titles are aligned to the far edges. Inspired by the **hrbrthemes** theme of the same name for **ggplot2**. \n#' - `\"dark\"` (*): similar to `\"minimal\"`, but set against a dark background with foreground and a palette colours lightened for appropriate contrast.\n#' - `\"ridge\"` (*): a specialized theme for ridge plots (see [`type_ridge()`]). Builds off of `\"clean\"`, but adds ridge-specific tweaks (e.g. default \"Zissou 1\" palette for discrete colors, solid horizontal grid lines, and minor adjustments to y-axis labels). Not recommended for non-ridge plots.\n#' - `\"ridge2\"` (*): removes the plot frame (box) from `\"ridge\"`, but retains the x-axis line. Again, not recommended for non-ridge plots.\n#' - `\"tufte\"`: floating axes and minimalist plot artifacts in the style of Edward Tufte.\n#' - `\"void\"`: switches off all axes, titles, legends, etc.\n#' @param ... Named arguments to override specific theme settings. These\n#' arguments are passed to `tpar()` and take precedence over the predefined\n#' settings in the selected theme.\n#'\n#' @details\n#' Sets a list of graphical parameters using `tpar()`\n#'\n#' To reset the theme to default settings (no customization), call `tinytheme()`\n#' without arguments.\n#' \n#' **Caveat emptor:** Themes are a somewhat experimental feature of `tinyplot`.\n#' While we feel confident that themes should work as expected for most\n#' \"standard\" cases, there may be some sharp edges. Please report any unexpected\n#' behaviour to our GitHub repo:\n#' \n#' \n#' Known current limitations include:\n#' \n#' - Themes do not work well when `legend = \"top!\"`.\n#' - Dynamic margin spacing does not account for multi-line strings (e.g., axes\n#' or main titles that contain \"\\\\n\").\n#'\n#' @return The function returns nothing. It is called for its side effects.\n#' \n#' @seealso [`tpar`] which does the heavy lifting under the hood.\n#'\n#' @examples\n#' # Reusable plot function\n#' p = function() tinyplot(\n#' lat ~ long | depth, data = quakes,\n#' main = \"Earthquakes off Fiji\",\n#' sub = \"Data courtesy of the Harvard PRIM-H project\"\n#' )\n#' p()\n#' \n#' # Set a theme\n#' tinytheme(\"bw\")\n#' p()\n#'\n#' # Try a different theme\n#' tinytheme(\"dark\")\n#' p()\n#' \n#' # Customize the theme by overriding default settings\n#' tinytheme(\"bw\", fg = \"green\", font.main = 2, font.sub = 3, family = \"Palatino\")\n#' p()\n#' \n#' # Another custom theme example\n#' tinytheme(\"bw\", font.main = 2, col.axis = \"darkcyan\", family = \"HersheyScript\")\n#' p()\n#' \n#' # Aside: One or two specialized themes are only meant for certain plot types\n#' tinytheme(\"ridge2\")\n#' tinyplot(I(cut(lat, 10)) ~ depth, data = quakes, type = \"ridge\")\n#'\n#' # Reset the theme\n#' tinytheme()\n#' p()\n#' \n#' # Themes showcase\n#' ## We'll use a slightly more intricate plot (long y-axis labs and facets)\n#' ## to demonstrate dynamic margin adjustment etc.\n#' \n#' thms = eval(formals(tinytheme)$theme)\n#' \n#' for (thm in thms) {\n#' tinytheme(thm)\n#' tinyplot(\n#' I(Sepal.Length*1e4) ~ Petal.Length | Species, facet = \"by\", data = iris,\n#' main = \"Demonstration of tinyplot themes\",\n#' sub = paste0('tinytheme(\"', thm, '\")')\n#' )\n#' }\n#' \n#' # Reset\n#' tinytheme()\n#'\n#' @export\ntinytheme = function(\n theme = c(\n \"default\", \"basic\",\n \"clean\", \"clean2\", \"bw\", \"classic\",\n \"minimal\", \"ipsum\", \"dark\",\n \"ridge\", \"ridge2\",\n \"tufte\", \"void\"\n ),\n ...\n ) {\n \n theme = match.arg(theme)\n\n # in notebooks, we don't want to close the device because no image.\n # init_tpar() tries to be smart, but may fail.\n init_tpar(rm_hook = TRUE)\n\n assert_choice(\n theme,\n c(\n \"default\",\n sort(c(\"basic\", \"bw\", \"classic\", \"clean\", \"clean2\", \"dark\", \"ipsum\",\n \"minimal\", \"ridge\", \"ridge2\", \"tufte\", \"void\"))\n )\n )\n\n settings = switch(theme,\n \"default\" = theme_default,\n \"basic\" = theme_basic,\n \"bw\" = theme_bw,\n \"classic\" = theme_classic,\n \"clean\" = theme_clean,\n \"clean2\" = theme_clean2,\n \"dark\" = theme_dark,\n \"ipsum\" = theme_ipsum,\n \"minimal\" = theme_minimal,\n \"ridge\" = theme_ridge,\n \"ridge2\" = theme_ridge2,\n \"tufte\" = theme_tufte,\n \"void\" = theme_void,\n )\n\n dots = list(...)\n for (n in names(dots)) {\n settings[[n]] = dots[[n]]\n }\n\n if (length(settings) > 0) {\n if (theme == \"default\") {\n # for default theme, we want to revert the original pars and turn off the\n # before.new.plot hook (otherwise manual par(x = y) changes won't work) \n tpar(settings, hook = FALSE)\n old_hooks = get_environment_variable(\".tpar_hooks\")\n remove_hooks(old_hooks)\n } else {\n tpar(settings, hook = TRUE)\n }\n }\n\n return(invisible(NULL))\n}\n\n\n\n#\n## Themes (these are read and set at initial load time)\n\n# theme_default = list()\n\ntheme_default = list(\n tinytheme = \"default\",\n adj = par(\"adj\"), # 0.5,\n adj.main = par(\"adj\"), # 0.5,\n adj.sub = par(\"adj\"), # 0.5,\n bg = \"white\", # par(\"bg\") # \"white\"\n bty = par(\"bty\"), #\"o\",\n cex.axis = par(\"cex.axis\"), #1,\n cex.main = par(\"cex.main\"), #1.2,\n cex.xlab = par(\"cex.axis\"), #1,\n cex.ylab = par(\"cex.axis\"), #1,\n col.axis = par(\"col.axis\"), #1,\n col.xaxs = par(\"col.axis\"), #1,\n col.yaxs = par(\"col.axis\"), #1,\n col.lab = par(\"col.lab\"), #\"black\",\n col.main = par(\"col.main\"), #\"black\",\n col.sub = par(\"col.sub\"), #\"black\",\n dynmar = FALSE,\n facet.bg = NULL,\n facet.border = NA,\n family = par(\"family\"), # \"\"\n fg = par(\"fg\"),\n font = par(\"font\"), # 1,\n font.axis = par(\"font.axis\"), # 1,\n font.lab = par(\"font.lab\"), # 1,\n font.main = par(\"font.main\"), # 2,\n font.sub = par(\"font.sub\"), # 2,\n grid = FALSE,\n grid.col = \"lightgray\",\n grid.lty = \"dotted\",\n grid.lwd = 1,\n lab = par(\"lab\"), # c(5, 5, 7),\n las = par(\"las\"), # 0,\n lwd = par(\"lwd\"), # 1,\n lwd.axis = par(\"lwd\"), # 1,\n mar = c(5.1, 4.1, 4.1, 2.1), ## test\n mgp = par(\"mgp\"),\n # palette.qualitative = \"R4\",\n # palette.sequential = \"Viridis\",\n pch = par(\"pch\"), # 1,\n side.sub = 1,\n tck = NA,\n xaxt = \"standard\",\n yaxt = \"standard\"\n)\n\n# derivatives of \"default\" \n# - basic\n# - tufte\n# - void\n\ntheme_basic = modifyList(theme_default, list(\n tinytheme = \"basic\",\n facet.bg = \"gray90\",\n facet.border = \"black\",\n grid = TRUE,\n pch = 16\n))\n\ntheme_tufte = modifyList(theme_default, list(\n tinytheme = \"tufte\",\n adj.main = 0,\n adj.sub = 0,\n bty = \"n\",\n font.main = 1,\n lab = c(10, 10, 7),\n # palette.sequential = \"Grays\",\n pch = 16,\n side.sub = 3,\n tcl = 0.2\n))\n\ntheme_void = modifyList(theme_default, list(\n tinytheme = \"void\",\n adj.main = 0,\n adj.sub = 0,\n font.main = 1,\n palette.qualitative = \"Tableau 10\",\n palette.sequential = \"ag_Sunset\",\n pch = 16,\n side.sub = 3,\n # tck = -.02,\n xaxt = \"none\",\n yaxt = \"none\"\n))\n\n# derivatives of \"basic\" \n# - clean\n\ntheme_clean = modifyList(theme_basic, list(\n ## Notes:\n ## - 1. Reduce axis title gap by 0.5 lines and also reduce tcl to 0.3 lines.\n ## - 2. Sub moves to top.\n ## - 3. Also want to remove excess white on rhs of plot margin (when no legend).\n ## - Together, 1, 2, and 3 imply that...\n ## -- mgp[1] should be adjusted by 0.8 (= 0.5 + 0.3)\n ## -- mgp[2] should be adjusted by 0.3\n ## -- mar[1] should be adjusted by 1.8 (= 1 (no sub) + 0.5 + 0.3 (tighter axis labs))\n ## -- mar[2] should be adjusted by 0.8 (= 0.5 + 0.3)\n ## -- mar[3] should remain unchanged (main + sub will adjust automatically)\n ## -- mar[4] should be adjusted by 1.5 (relative to 2.1)\n ##\n tinytheme = \"clean\",\n adj.main = 0,\n adj.sub = 0,\n dynmar = TRUE,\n las = 1,\n mar = c(5.1, 4.1, 4.1, 2.1) - c(1+0.5+0.3, 0.5+0.3, 0, 1.5), ## test\n mgp = c(3, 1, 0) - c(0.5+0.3, 0.3, 0), # i.e., subtract 0.5 lines + the (abs) value of the tcl adjustment\n palette.qualitative = \"Tableau 10\",\n palette.sequential = \"ag_Sunset\",\n side.sub = 3,\n tcl = -0.3\n))\n\n# derivatives of \"clean\" \n# - clean2\n# - classic\n# - bw\n\ntheme_clean2 = modifyList(theme_clean, list(\n tinytheme = \"clean2\",\n facet.border = \"gray90\",\n xaxt = \"labels\",\n yaxt = \"labels\"\n))\n\ntheme_classic = modifyList(theme_clean, list(\n tinytheme = \"classic\",\n bty = \"l\",\n facet.bg = NULL,\n font.main = 1,\n grid = FALSE,\n palette.qualitative = \"Okabe-Ito\"\n))\n\ntheme_bw = modifyList(theme_clean, list(\n tinytheme = \"bw\",\n font.main = 1,\n grid.lty = 1,\n grid.lwd = 0.5,\n lwd = 0.5,\n lwd.axis = 0.5,\n palette.qualitative = \"Okabe-Ito\"\n))\n\n# derivatives of \"bw\"\n# - minimal\n# - ipsum\n# - dark\n \ntheme_minimal = modifyList(theme_bw, list(\n tinytheme = \"minimal\",\n bty = \"n\",\n facet.bg = NULL,\n facet.border = NULL,\n xaxt = \"labels\",\n yaxt = \"labels\"\n))\n\ntheme_ipsum = modifyList(theme_minimal, list(\n tinytheme = \"ipsum\",\n bty = \"n\",\n font.sub = 3,\n adj.ylab = 1,\n adj.xlab = 1\n))\n\ntheme_dark = modifyList(theme_minimal, list(\n tinytheme = \"dark\",\n bg = \"#1A1A1A\",\n fg = \"#BBBBBB\",\n # col = \"white\",\n col.xaxs = \"#BBBBBB\",\n col.yaxs = \"#BBBBBB\",\n col.lab = \"#BBBBBB\",\n col.main = \"#BBBBBB\",\n col.sub = \"#BBBBBB\",\n col.axis = \"#BBBBBB\",\n # facet.bg = \"gray20\",\n grid.col = \"#6D6D6D\",\n palette.qualitative = \"Set 2\",\n palette.sequential = \"Sunset\"\n))\n\n# derivative of clean/clean2\n\ntheme_ridge = modifyList(theme_clean, list(\n tinytheme = \"ridge\",\n palette.qualitative = \"Zissou 1\",\n grid = FALSE\n))\ntheme_ridge2 = modifyList(theme_clean2, list(\n tinytheme = \"ridge2\",\n palette.qualitative = \"Zissou 1\",\n grid = FALSE\n))\n"], ["/tinyplot/R/get_saved_par.R", "#' @title Retrieve the saved graphical parameters\n#' \n#' @description Convenience function for retrieving the graphical parameters\n#' (i.e., the full list of `tag = value` pairs held in\n#' \\code{\\link[graphics]{par}}) from either immediately before or\n#' immediately after the most recent [tinyplot] call.\n#'\n#' @param when character. From when should the saved parameters be retrieved?\n#' Either \"before\" (the default) or \"after\" the preceding `tinyplot` call.\n#' \n#' @details A potential side-effect of [tinyplot] is that it can change a user's\n#' \\code{\\link[graphics]{par}} settings. For example, it may adjust the inner\n#' and outer plot margins to make space for an automatic legend; see\n#' [draw_legend]. While it is possible to immediately restore the original\n#' \\code{\\link[graphics]{par}} settings upon exit via the\n#' `tinyplot(..., restore.par = TRUE)` argument, this is not the default\n#' behaviour. The reason being that we need to preserve the adjusted parameter\n#' settings in case users want to add further graphical annotations to their\n#' plot (e.g., \\code{\\link[graphics]{abline}}, \\code{\\link[graphics]{text}},\n#' etc.) Nevertheless, it may still prove desirable to recall and reset these\n#' original graphical parameters after the fact (e.g., once all these extra\n#' annotations have been added). That is the purpose of this [get_saved_par]\n#' function.\n#' \n#' Of course, users may prefer to manually capture and reset graphical\n#' parameters, as per the standard method described in the\n#' \\code{\\link[graphics]{par}} documentation. For example:\n#' \n#' ```\n#' op = par(no.readonly = TRUE) # save current par settings \n#' # \n#' par(op) # reset original pars\n#' ```\n#' \n#' This standard manual approach may be safer than [get_saved_par] because it\n#' offers more precise control. Specifically, the value of [get_saved_par] \n#' itself will be reset after ever new [tinyplot] call; i.e. it may inherit an\n#' already-changed set of parameters. Users should bear these trade-offs in\n#' mind when deciding which approach to use. As a general rule,\n#' [get_saved_par] offers the convenience of resetting the original\n#' \\code{\\link[graphics]{par}} settings even if a user forgot to save them\n#' beforehand. But one should avoid invoking it after a series of consecutive\n#' [tinyplot] calls.\n#' \n#' Finally, note that users can always call \\code{\\link[grDevices]{dev.off}}\n#' to reset all \\code{\\link[graphics]{par}} settings to their defaults.\n#' \n#' @returns A list of \\code{\\link[graphics]{par}} settings.\n#' \n#' @examples\n#' #\n#' # Contrived example where we draw a grouped scatterplot with a legend and\n#' # manually add corresponding best fit lines for each group...\n#' #\n#' \n#' # First draw the grouped scatterplot\n#' tinyplot(Sepal.Length ~ Petal.Length | Species, iris)\n#' \n#' # Preserving adjusted par settings is good for adding elements to our plot\n#' for (s in levels(iris$Species)) {\n#' abline(\n#' lm(Sepal.Length ~ Petal.Length, iris, subset = Species==s),\n#' col = which(levels(iris$Species)==s)\n#' )\n#' }\n#' \n#' # Get saved par from before the preceding tinyplot call (but don't use yet)\n#' sp = get_saved_par(\"before\")\n#' \n#' # Note the changed margins will affect regular plots too, which is probably\n#' # not desirable\n#' plot(1:10)\n#' \n#' # Reset the original parameters (could use `par(sp)` here)\n#' tpar(sp)\n#' # Redraw our simple plot with our corrected right margin\n#' plot(1:10)\n#' \n#' #\n#' # Quick example going the other way, \"correcting\" for par.restore = TRUE...\n#' #\n#' \n#' tinyplot(Sepal.Length ~ Petal.Length | Species, iris, restore.par = TRUE)\n#' # Our added best lines will be wrong b/c of misaligned par\n#' for (s in levels(iris$Species)) {\n#' abline(\n#' lm(Sepal.Length ~ Petal.Length, iris, subset = Species==s),\n#' col = which(levels(iris$Species)==s), lty = 2\n#' )\n#' }\n#' # grab the par settings from the _end_ of the preceding tinyplot call to fix\n#' tpar(get_saved_par(\"after\"))\n#' # now the best lines are correct\n#' for (s in levels(iris$Species)) {\n#' abline(\n#' lm(Sepal.Length ~ Petal.Length, iris, subset = Species==s),\n#' col = which(levels(iris$Species)==s)\n#' )\n#' }\n#' \n#' # reset again to original saved par settings before exit\n#' tpar(sp)\n#'\n#' @export\nget_saved_par = function(when = c(\"before\", \"after\", \"first\")) {\n when = match.arg(when)\n par_env_name = paste0(\".saved_par_\", when)\n return(get(par_env_name, envir = get(\".tinyplot_env\", envir = parent.env(environment()))))\n}\n\n# (non-exported) companion function(s) for setting the original pars\nset_saved_par = function(when = c(\"before\", \"after\", \"first\"), value) {\n when = match.arg(when)\n par_env_name = paste0(\".saved_par_\", when)\n assign(par_env_name, value, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n}\n"], ["/tinyplot/R/type_ridge.R", "#' Ridge plot type\n#'\n#' @description Type function for producing ridge plots (also known as joy plots),\n#' which display density distributions for multiple groups with vertical offsets.\n#' This function uses `tinyplot` scaffolding, which enables added functionality\n#' such as grouping and faceting.\n#'\n#' The line color is controlled by the `col` argument in the `tinyplot()` call.\n#' The fill color is controlled by the `bg` argument in the `tinyplot()` call.\n#'\n#' @param scale Numeric. Controls the scaling factor of each plot.\n#' Values greater than 1 means that plots overlap.\n#' @param joint.max character indicating how to scale the maximum of the densities:\n#' The default `\"all\"` indicates that all densities are scaled jointly relative to\n#' the same maximum so that the areas of all densities are comparable.\n#' Alternatively, `\"facet\"` indicates that the maximum is computed within\n#' each facet so that the areas of the densities are comparable within each\n#' facet but not necessarily across facets. Finally, `\"by\"` indicates that\n#' each row (in each facet) is scaled separately, so that the areas of the\n#' densities for `by` groups in the same row are comparable but not necessarily\n#' across rows.\n#' @param breaks Numeric. If a color gradient is used for shading, the\n#' breaks between the colors can be modified. The default is to use\n#' equidistant breaks spanning the range of the `x` variable.\n#' @param probs Numeric. Instead of specifying the same `breaks` on the\n#' x-axis for all groups, it is possible to specify group-specific quantiles\n#' at the specified `probs`. The quantiles are computed based on the density\n#' (rather than the raw original variable). Only one of `breaks` or\n#' `probs` must be specified.\n#' @param ylevels a character or numeric vector specifying in which order\n#' the levels of the y-variable should be plotted.\n#' @inheritParams stats::density\n#' @param kernel a character string giving the smoothing kernel to be used. This\n#' must partially match one of `\"gaussian\"`, `\"rectangular\"`, `\"triangular\"`,\n#' `\"epanechnikov\"`, `\"biweight\"`, `\"cosine\"` or `\"optcosine\"`, with default\n#' `\"gaussian\"`, and may be abbreviated to a unique prefix (single letter).\n#'\n#' `\"cosine\"` is smoother than `\"optcosine\"`, which is the usual 'cosine'\n#' kernel in the literature and almost MSE-efficient. However, `\"cosine\"` is\n#' the version used by S.\n#' @param joint.bw character string indicating whether (and how) the smoothing\n#' bandwidth should be computed from the joint data distribution. The default\n#' of `\"mean\"` will compute the joint bandwidth as the mean of the individual\n#' subgroup bandwidths (weighted by their number of observations). Choosing\n#' `\"full\"` will result in a joint bandwidth computed from the full\n#' distribution (merging all subgroups). For `\"none\"` the individual bandwidth\n#' will be computed independently for each subgroup. Also accepts a logical\n#' argument, where `TRUE` maps to `\"mean\"` and `FALSE` maps to `\"none\"`. See\n#' \\code{\\link{type_density}} for some discussion of practical considerations.\n#' @param gradient Logical or character. Should a gradient fill be used to\n#' shade the area under the density? If a character specification is used,\n#' then it can either be of length 1 and specify the palette to be used with\n#' `gradient = TRUE` corresponding to `gradient = \"viridis\"`. If a character\n#' vector of length greater than 1 is used, then it should specify the\n#' colors in the palette, e.g., `gradient = hcl.colors(512)`.\n#' @param raster Logical. Should the `gradient` fill be drawn using\n#' \\code{\\link[graphics]{rasterImage}}? Defaults to `FALSE`, in which case the\n#' `gradient` fill will instead be drawn using\n#' \\code{\\link[graphics]{polygon}}. See the `Technical note on gradient fills`\n#' section below.\n#' @param col Character string denoting the outline (border) color for all\n#' of the ridge densities. Note that a singular value is expected; if multiple\n#' colors are provided then only the first will be used. This argument is mostly\n#' useful for the aesthetic effect of drawing a common outline color in\n#' combination with gradient fills. See Examples.\n#' @param alpha Numeric in the range `[0,1]` for adjusting the alpha\n#' transparency of the density fills. In most cases, will default to a value of\n#' 1, i.e. fully opaque. But for some `by` grouped plots (excepting the special\n#' cases where `by==y` or `by==x`), will default to 0.6.\n#' \n#' @section Technical note on gradient fills:\n#' \n#' `tinyplot` uses two basic approaches for drawing gradient fills in ridge line\n#' plots, e.g., if `type_ridge(gradient = TRUE)`.\n#' \n#' The first (and default) polygon-based approach involves dividing up the main\n#' density region into many smaller polygons along the x-axis. Each of these\n#' smaller polygons inherits a different color \"segment\" from the underlying\n#' palette swatch, which in turn creates the effect of a continuous gradient\n#' when they are all plotted together. Internally, this polygon-based approach\n#' is vectorized (i.e., all of the sub-polygons are plotted simultaneously). It\n#' is thus efficient from a plotting perspective and generally also performs\n#' well from an aesthetic perspective. However, it can occasionally produce\n#' undesirable plotting artifacts on some graphics devices---e.g., thin but\n#' visible vertical lines---if alpha transparency is being used at the same \n#' time.\n#' \n#' For this reason, we also offer an alternative raster-based approach for\n#' gradient fills that users can invoke via\n#' `type_ridge(gradient = TRUE, raster = TRUE)`. The essential idea is that we\n#' coerce the density polygon into a raster representation (using\n#' \\code{\\link[graphics]{rasterImage}}) and achieve the gradient effect via\n#' color interpolation. The trade-off this time is potential smoothness\n#' artifacts around the top of the ridge densities at high resolutions, since we\n#' have converted a vector object into a raster object.\n#' \n#' Again, we expect that the choice between these two approaches will only\n#' matter for ridge plots that combine gradient fills with alpha transparency\n#' (and on certain graphics devices). We recommend that users experiment to\n#' determine which approach is optimal for their device.\n#'\n#' @examples\n#' aq = transform(\n#' airquality,\n#' Month = factor(month.abb[Month], levels = month.abb[5:9]),\n#' Month2 = factor(month.name[Month], levels = month.name[5:9]),\n#' Late = ifelse(Day > 15, \"Late\", \"Early\")\n#' )\n#' \n#' # default ridge plot (using the \"ridge\" convenience string)\n#' tinyplot(Month ~ Temp, data = aq, type = \"ridge\")\n#' \n#' # for ridge plots, we recommend pairing with the dedicated theme(s), which\n#' # facilitate nicer y-axis labels, grid lines, etc.\n#' \n#' tinytheme(\"ridge\")\n#' tinyplot(Month ~ Temp, data = aq, type = \"ridge\")\n#' \n#' tinytheme(\"ridge2\") # removes the plot frame (but keeps x-axis line)\n#' tinyplot(Month ~ Temp, data = aq, type = \"ridge\")\n#' \n#' # the \"ridge(2)\" themes are especially helpful for long y labels, due to\n#' # dyanmic plot adjustment\n#' tinyplot(Month2 ~ Temp, data = aq, type = \"ridge\")\n#' \n#' # pass customization arguments through type_ridge()... for example, use\n#' # the scale argument to change/avoid overlap of densities (more on scaling\n#' # further below)\n#' \n#' tinyplot(Month ~ Temp, data = aq, type = type_ridge(scale = 1))\n#' \n#' ## by grouping is also supported. two special cases of interest:\n#'\n#' # 1) by == y (color by y groups)\n#' tinyplot(Month ~ Temp | Month, data = aq, type = \"ridge\")\n#'\n#' # 2) by == x (gradient coloring along x)\n#' tinyplot(Month ~ Temp | Temp, data = aq, type = \"ridge\")\n#'\n#' # aside: pass explicit `type_ridge(col = )` arg to set a different\n#' # border color\n#' tinyplot(Month ~ Temp | Temp, data = aq, type = type_ridge(col = \"white\"))\n#'\n#' # gradient coloring along the x-axis can also be invoked manually without\n#' # a legend (the next two tinyplot calls are equivalent)\n#' \n#' # tinyplot(Month ~ Temp, data = aq, type = type_ridge(gradient = \"agsunset\"))\n#' tinyplot(Month ~ Temp, data = aq, type = type_ridge(gradient = TRUE))\n#' \n#' # aside: when combining gradient fill with alpha transparency, it may be\n#' # better to use the raster-based approach (test on your graphics device)\n#' \n#' tinyplot(Month ~ Temp, data = aq,\n#' type = type_ridge(gradient = TRUE, alpha = 0.5),\n#' main = \"polygon fill (default)\")\n#' tinyplot(Month ~ Temp, data = aq,\n#' type = type_ridge(gradient = TRUE, alpha = 0.5, raster = TRUE),\n#' main = \"raster fill\")\n#'\n#' # highlighting only the center 50% of the density (i.e., 25%-75% quantiles)\n#' tinyplot(Month ~ Temp, data = aq, type = type_ridge(\n#' gradient = hcl.colors(3, \"Dark Mint\")[c(2, 1, 2)],\n#' probs = c(0.25, 0.75), col = \"white\"))\n#'\n#' # highlighting the probability distribution by color gradient\n#' # (darkest point = median)\n#' tinyplot(Month ~ Temp, data = aq, type = type_ridge(\n#' gradient = hcl.colors(250, \"Dark Mint\")[c(250:1, 1:250)],\n#' probs = 0:500/500))\n#'\n#' # faceting also works, although we recommend switching (back) to the \"ridge\"\n#' # theme for faceted ridge plots\n#' \n#' tinytheme(\"ridge\")\n#' tinyplot(Month ~ Ozone, facet = ~ Late, data = aq,\n#' type = type_ridge(gradient = TRUE))\n#' \n#' ## use the joint.max argument to vary the maximum density used for\n#' ## determining relative scaling...\n#' \n#' # jointly across all densities (default) vs. per facet\n#' tinyplot(Month ~ Temp, facet = ~ Late, data = aq,\n#' type = type_ridge(scale = 1))\n#' tinyplot(Month ~ Temp, facet = ~ Late, data = aq,\n#' type = type_ridge(scale = 1, joint.max = \"facet\"))\n#' \n#' # jointly across all densities (default) vs. per by row\n#' tinyplot(Month ~ Temp | Late, data = aq,\n#' type = type_ridge(scale = 1))\n#' tinyplot(Month ~ Temp | Late, data = aq,\n#' type = type_ridge(scale = 1, joint.max = \"by\"))\n#' \n#' # restore the default theme\n#' tinytheme()\n#'\n#' @export\ntype_ridge = function(\n scale = 1.5,\n joint.max = c(\"all\", \"facet\", \"by\"),\n breaks = NULL,\n probs = NULL,\n ylevels = NULL,\n bw = \"nrd0\",\n joint.bw = c(\"mean\", \"full\", \"none\"),\n adjust = 1,\n kernel = c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"),\n n = 512,\n # more args from density here?\n gradient = FALSE,\n raster = FALSE,\n col = NULL,\n alpha = NULL\n ) {\n \n kernel = match.arg(kernel, c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"))\n if (is.logical(joint.bw)) {\n joint.bw = ifelse(joint.bw, \"mean\", \"none\")\n }\n joint.bw = match.arg(joint.bw, c(\"mean\", \"full\", \"none\"))\n\n out = list(\n draw = draw_ridge(),\n data = data_ridge(bw = bw, adjust = adjust, kernel = kernel, n = n,\n joint.bw = joint.bw,\n scale = scale,\n joint.max = joint.max,\n gradient = gradient,\n breaks = breaks,\n probs = probs,\n ylevels = ylevels,\n raster = raster,\n col = col,\n alpha = alpha\n ),\n name = \"ridge\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n#\n## Underlying data_ridge function\ndata_ridge = function(bw = \"nrd0\", adjust = 1, kernel = \"gaussian\", n = 512,\n joint.bw = \"mean\",\n scale = 1.5,\n joint.max = \"all\",\n gradient = FALSE,\n breaks = NULL,\n probs = NULL,\n ylevels = NULL,\n raster = FALSE,\n col = NULL,\n alpha = NULL\n ) {\n fun = function(datapoints, yaxt = NULL, null_by, ...) {\n # catch for special cases\n anyby = !null_by\n x_by = anyby && identical(datapoints$x, datapoints$by)\n y_by = anyby && identical(datapoints$y, datapoints$by)\n if (x_by) {\n gradient = TRUE\n datapoints$by = \"\"\n } else if (y_by) {\n datapoints$by = \"\"\n } else if (anyby && is.null(alpha)) {\n alpha = 0.6\n }\n # flag for (non-gradient) interior fill adjustment\n fill_by = anyby || y_by\n if (isTRUE(x_by)) fill_by = FALSE\n # if (isTRUE(anyby) && is.null(alpha)) alpha = 0.6\n\n ## reorder levels of y-variable if requested\n if (!is.null(ylevels)) {\n if (!is.factor(datapoints$y)) datapoints$y = factor(datapoints$y)\n datapoints$y = factor(datapoints$y, levels = if(is.numeric(ylevels)) levels(datapoints$y)[ylevels] else ylevels)\n if (y_by) datapoints$by = datapoints$y\n }\n\n ##\n datapoints = split(datapoints, list(datapoints$y, datapoints$by, datapoints$facet))\n\n if (joint.bw == \"none\" || is.numeric(bw)) {\n dens_bw = bw\n } else {\n if (joint.bw == \"mean\") {\n # Use weighted mean of subgroup bandwidths\n bws = sapply(datapoints, function(dat) bw_fun(kernel = bw, dat$x))\n ws = sapply(datapoints, nrow)\n dens_bw = weighted.mean(bws, ws)\n } else if (joint.bw == \"full\") {\n dens_bw = bw_fun(kernel = bw, unlist(sapply(datapoints, `[[`, \"x\")))\n }\n }\n\n datapoints = lapply(datapoints, function(dat) {\n dens = density(dat$x, bw = dens_bw, kernel = kernel, n = n)\n out = data.frame(\n by = dat$by[1], # already split\n facet = dat$facet[1], # already split\n x = dens$x,\n y = dat$y[1],\n ymin = 0L,\n ymax = dens$y\n )\n return(out)\n })\n datapoints = do.call(rbind, datapoints)\n\n if (is.character(joint.max)) {\n joint.max = match.arg(joint.max, c(\"all\", \"facet\", \"by\"))\n joint.max = switch(joint.max,\n \"all\" = rep.int(1, nrow(datapoints)),\n \"facet\" = datapoints$facet,\n \"by\" = interaction(datapoints$facet, datapoints$y)\n )\n joint.max = ave(datapoints$ymax, joint.max, FUN = max)\n }\n datapoints$ymax = datapoints$ymax / joint.max * scale\n\n datapoints = split(datapoints, datapoints$facet)\n offset_z = function(k) {\n ksplit = split(k, k$y)\n for (idx in seq_along(ksplit)) {\n ksplit[[idx]]$ymax = ksplit[[idx]]$ymax + idx - 1\n ksplit[[idx]]$ymin = ksplit[[idx]]$ymin + idx - 1\n }\n k = do.call(rbind, ksplit)\n return(k)\n }\n datapoints = do.call(rbind, lapply(datapoints, offset_z))\n\n if (y_by) {\n datapoints$y = factor(datapoints$y)\n datapoints$by = factor(datapoints$y, levels = rev(levels(datapoints$y)))\n } else if (x_by) {\n datapoints$by = datapoints$x\n }\n\n # Manual breaks flag. Only used if gradient is on\n manbreaks = !is.null(breaks) || !is.null(probs)\n\n ## use color gradient?\n xlim = range(datapoints$x, na.rm = TRUE)\n if (!is.null(probs)) {\n if (!is.null(breaks)) {\n warning(\"only one of 'breaks' and 'quantile' must be specified\")\n probs = NULL\n } else {\n if (probs[1L] > 0) probs = c(0, probs)\n if (probs[length(probs)] < 1) probs = c(probs, 1)\n }\n }\n if (!isFALSE(gradient)) {\n dotspal = list(...)[[\"palette\"]]\n palette = if (!is.null(dotspal)) dotspal else gradient\n gradient = TRUE\n if (isTRUE(palette)) {\n palette = if (!is.null(.tpar[[\"palette.sequential\"]])) .tpar[[\"palette.sequential\"]] else \"viridis\"\n }\n\n if (length(palette) > 1L || !is.character(palette)) {\n ## color vector already given\n if (is.null(breaks) && is.null(probs)) {\n breaks = seq(from = xlim[1L], to = xlim[2L], length.out = length(palette) + 1L)\n } else {\n npal = pmax(length(breaks), length(probs)) - 1L\n if (length(palette) != npal) {\n warning(\"length of 'palette' does not match 'breaks'/'probs'\")\n palette = rep_len(palette, npal)\n }\n if (isTRUE(raster)) raster = npal > 20L\n }\n } else {\n ## only palette name given\n npal = if (is.null(breaks) && is.null(probs)) 512L else pmax(length(breaks), length(probs)) - 1L\n palette = hcl.colors(npal, palette = palette)\n if (is.null(breaks) && is.null(probs)) breaks = seq(from = xlim[1L], to = xlim[2L], length.out = npal + 1L)\n if (isTRUE(raster)) raster = npal > 20L\n }\n } else {\n palette = NULL\n if (!is.null(breaks) || !is.null(probs)) gradient = TRUE\n }\n if (!is.null(breaks)) {\n breaks[1L] = pmin(breaks[1L], xlim[1L])\n breaks[length(breaks)] = pmax(breaks[length(breaks)], xlim[2L])\n }\n \n if (is.null(col) && (!anyby || x_by)) col = \"black\"\n\n out = list(\n datapoints = datapoints,\n yaxt = \"n\",\n ylim = c(min(datapoints$ymin), max(datapoints$ymax)),\n type_info = list(\n gradient = gradient,\n palette = palette,\n breaks = breaks,\n probs = probs,\n manbreaks = manbreaks,\n yaxt = yaxt,\n raster = raster,\n x_by = x_by,\n y_by = y_by,\n fill_by = fill_by,\n col = col,\n alpha = alpha\n )\n )\n return(out)\n }\n return(fun)\n}\n\n\n#\n## Underlying draw_ridge function\ndraw_ridge = function() {\n fun = function(ix, iy, iz, ibg, icol, iymin, iymax, type_info, ...) {\n ridge_theme = identical(.tpar[[\"tinytheme\"]], \"ridge\") || identical(.tpar[[\"tinytheme\"]], \"ridge2\")\n d = data.frame(x = ix, y = iy, ymin = iymin, ymax = iymax)\n dsplit = split(d, d$y)\n if (is.null(ibg)) {\n default_bg = if (!ridge_theme && !is.null(.tpar[[\"palette.qualitative\"]])) seq_palette(by_col(), n = 2)[2] else \"gray\"\n ibg = if (isTRUE(type_info[[\"fill_by\"]])) seq_palette(icol, n = 2)[2] else default_bg\n }\n if (!is.null(type_info[[\"alpha\"]]) && is.null(type_info[[\"palette\"]])) {\n ibg = adjustcolor(ibg, alpha.f = type_info[[\"alpha\"]])\n }\n if (!is.null(type_info[[\"col\"]])) icol = type_info[[\"col\"]]\n lab = if (is.factor(d$y)) levels(d$y) else unique(d$y)\n if (isTRUE(type_info[[\"y_by\"]])) {\n # avoid duplicating the y-axis labs for the special y==by case\n # val = match(lab, levels(d$y)) - 1\n val = match(d$y[1], levels(d$y))\n lab = lab[val]\n val = val - 1\n } else {\n val = cumsum(rep(1, length(lab))) - 1\n }\n if (ridge_theme) abline(h = val, col = .tpar[[\"grid.col\"]])\n draw_segments = if (type_info[[\"raster\"]]) segmented_raster else segmented_polygon\n for (i in rev(seq_along(dsplit))) {\n if (type_info[[\"gradient\"]]) {\n with(\n dsplit[[i]],\n draw_segments(\n x, ymax, ymin = ymin[1L],\n breaks = type_info[[\"breaks\"]],\n probs = type_info[[\"probs\"]],\n manbreaks = type_info[[\"manbreaks\"]],\n col = if (is.null(type_info[[\"palette\"]])) ibg else type_info[[\"palette\"]],\n # border = if (is.null(type_info[[\"palette\"]])) icol else \"transparent\",\n alpha = type_info[[\"alpha\"]]\n )\n )\n }\n with(dsplit[[i]], polygon(x, ymax, col = if (type_info[[\"gradient\"]]) \"transparent\" else ibg, border = NA))\n with(dsplit[[i]], lines(x, ymax, col = icol))\n }\n # tinyAxis(x = d$y, side = 2, at = val, labels = lab, type = type_info[[\"yaxt\"]], padj = padj)\n if (ridge_theme) {\n tinyAxis(x = d$y, side = 2, at = val, labels = lab, type = type_info[[\"yaxt\"]],\n padj = 0,\n mgp = c(3, 1, 0) - c(0.5, 0.5 + 0.3, 0),\n tcl = 0)\n if (identical(.tpar[[\"tinytheme\"]], \"ridge2\")) axis(1, labels = FALSE)\n } else {\n tinyAxis(x = d$y, side = 2, at = val, labels = lab, type = type_info[[\"yaxt\"]])\n }\n }\n return(fun)\n}\n\n\n#\n## Auxiliary functions\n\n## auxiliary function for drawing shaded segmented polygon\nsegmented_polygon = function(x, y, ymin = 0, breaks = range(x), probs = NULL, manbreaks = FALSE, col = \"lightgray\", border = \"transparent\", alpha = NULL) {\n\n if (!is.null(probs)) {\n ## map quantiles to breaks\n if (!(missing(breaks) || is.null(breaks))) stop(\"only one of 'breaks' and 'probs' must be specified\")\n breaks = quantile.density(list(x = x, y = y - ymin), probs = probs)\n }\n\n ## sanity check\n if (breaks[1L] > x[1L] || breaks[length(breaks)] < x[length(x)]) stop(\"'breaks' do no span range of 'x'\")\n\n # ## recycle color (if necessary) rather use colorRampPalette below\n # col = rep_len(col, length(breaks) - 1L)\n \n # Create individual polygons\n if (isFALSE(manbreaks)) {\n # Special case for length(breaks)==length(x). We can take a fully vectorised\n # shortcut\n xx = c(rbind(x[-length(x)], x[-1], x[-1], x[-length(x)], NA))\n yy = c(rbind(y[-length(y)], y[-1], ymin, ymin, NA))\n } else {\n # For other cases, we'll do a bit more work to make sure that the polygons\n # overlap\n bvals = do.call(c, sapply(seq_along(breaks[-1]), function(b) tail(x[x= xrange[1] & breaks < xrange[2])\n idx = c(idx, length(idx)+1)\n col = col[idx]\n col = colorRampPalette(col, alpha = TRUE)(length(x)) # support alpha?\n }\n } else if (isFALSE(manbreaks) || length(col) > length(x) || length(x) %% length(col) != 0) {\n xrange = range(xx, na.rm = TRUE)\n idx = which(breaks >= xrange[1] & breaks < xrange[2])\n idx = c(idx, length(idx)+1)\n col = col[idx]\n col = colorRampPalette(col, alpha = TRUE)(length(x)) # support alpha?\n }\n }\n border = if (is.null(alpha)) col else adjustcolor(col = col, alpha.f = alpha/2)\n \n ## draw all polygons\n polygon(xx, yy, col = col, border = border, lwd = 0.5)\n}\n\n#' @importFrom graphics rasterImage\n#' @importFrom grDevices as.raster\nsegmented_raster = function(x, y, ymin = 0, breaks = range(x), probs = NULL, manbreaks = FALSE, col = \"lightgray\", border = \"transparent\", alpha = NULL) {\n ## set up raster matrix on x-grid and 500 y-pixels \n n = length(x) - 1L\n m = 500L ## FIXME: hard-coded?\n r = matrix(1:n, ncol = n, nrow = m, byrow = TRUE)\n\n ## map quantiles to breaks\n if (!is.null(probs)) {\n if (!(missing(breaks) || is.null(breaks))) stop(\"only one of 'breaks' and 'probs' must be specified\")\n breaks = quantile.density(list(x = x, y = y - ymin), probs = probs)\n }\n\n if (!is.null(alpha)) col = adjustcolor(col, alpha.f = alpha)\n col = rev(col) ## uncomment to make extreme cols dark\n ## map colors to intervals and fill colors by column\n col = col[cut(x, breaks = breaks, include.lowest = TRUE)]\n r[] = col[r]\n\n ## clip raster pixels above density line\n ymax = max(y)\n ix = cbind(as.vector(row(r)), as.vector(col(r)))\n ix = ix[seq(from = ymax, to = ymin, length.out = m)[row(r)] > y[col(r)], , drop = FALSE]\n r[ix] = NA\n\n ## plot density and add raster gradient\n rasterImage(as.raster(r), min(x), ymin, max(x), ymax, interpolate = length(breaks) >= 20L) ## FIXME: improve quality for \"few\" breaks?\n}\n\n## auxiliary function for determining quantiles based on density function\n\n#' @importFrom stats median approx\nquantile.density = function(x, probs = seq(0, 1, 0.25), ...) {\n ## sanity check for probabilities\n if (any(probs < 0 | probs > 1)) stop(\"'probs' outside [0,1]\")\n\n ## probability density function, extrapolated to zero, use midpoints\n n = length(x$x)\n pdf = x$y\n pdf = c(0, pdf, 0)\n\n ## x variable, also extrapolated, use midpoints\n x = x$x\n delta = median(diff(x))\n x = c(x[1L] - delta, x, x[n] + delta)\n\n ## numerical integration of density\n cdf = c(0, cumsum(diff(x) * (pdf[-1L] + pdf[-(n + 2L)])/2))\n cdf = cdf/cdf[n + 2L]\n\n ## approximate quantiles\n approx(cdf, x, xout = probs, rule = 2)$y \n}\n"], ["/tinyplot/R/type_abline.R", "#' Add straight lines to a plot\n#' @description\n#' These functions add straight line(s) through the current plot.\n#' @details\n#' While `type_abline`, `type_hline`, and `type_vline` can be called in a base\n#' plot layer, we expect that they will typically be called as subsequent\n#' layers via [`tinyplot_add`].\n#' @section Recycling logic: \n#' The recycling behaviour of the line parameters (i.e., `a`, `b`, `h`, or `v`)\n#' is adaptive, depending on whether `by` or `facet` grouping is detected. While\n#' this leads to different recycling scenarios, the underlying code logic\n#' follows sensible heuristics designed to match user expectations.\n#' \n#' Parameter lengths must equal one of four options:\n#' \n#' 1. Single value (i.e., length = 1), i.e. simplest case where the same line is\n#' applied uniformly across all groups and facets. Uses the default user colour\n#' (e.g. `\"black\"`, or `tpar(\"palette.qualitative\")[1]` if a theme is set).\n#' 2. Number of `by` groups, i.e. one parameter per group. For example,\n#' `tinyplot(mpg ~ wt | factor(cyl), data = mtcars, type = type_hline(h = 21:23))`\n#' will give three horizontal lines, with colours matching the user's qualitative\n#' palette.\n#' 3. Number of `facet` groups, i.e. one parameter per facet panel. For example:\n#' `tinyplot(mpg ~ wt, facet = ~am, data = mtcars, type = type_hline(h = c(20,30)))`\n#' would give separate horizontal lines per facet, but both using the same\n#' default color.\n#' 4. Product of `by` and `facet` groups, i.e. one parameter for each unique\n#' by-facet combination. Orders over facets first and then, within that, by\n#' group. For example:\n#' `tinyplot(mpg ~ wt | factor(cyl), facet = ~am, data = mtcars, type = type_hline(h = 21:26))`\n#' will give six separate lines, with the first three (`21:23`) coloured by\n#' group in the first facet, and second three (`24:26`) coloured by by group\n#' in the second facet.\n#' \n#' Alongside these general rules, we also try to accomodate special cases when\n#' other aesthetic parameters like `lwd` or `lty` are invoked by the user. See\n#' Examples.\n#' \n#' @param a,b the intercept (default: `a` = 0) and slope (default: `b` = 1)\n#' terms. Numerics of length 1, or equal to the number of groups or number of\n#' facets (or the product thereof).\n#' @examples\n#' #\n#' ## abline\n#' \n#' tinyplot(x = -10:10, y = rnorm(21) + -10:10, grid = TRUE)\n#' tinyplot_add(type = \"abline\")\n#' # same as...\n#' # tinyplot_add(type = type_abline(a = 0, b = 1))\n#' \n#' # customize by passing bespoke intercept and slope values\n#' tinyplot_add(type = type_abline(a = -1, b = -0.5))\n#' \n#' # note that calling as abline & co. as a base plot layer will still lead to\n#' # axes limits that respect the range of the data\n#' tinyplot(x = -10:10, y = -10:10, grid = TRUE, type = \"abline\")\n#' \n#' #\n#' ## hline and vline\n#'\n#' # Base plot layer\n#' tinyplot(mpg ~ hp | cyl, facet = \"by\", data = mtcars, ylim = c(0, 40))\n#' \n#' # Add horizontal lines at the (default) 0 y-intercept\n#' tinyplot_add(type = \"hline\", col = \"grey\")\n#' \n#' # Note that group+facet aesthetics will be inherited. We can use this to\n#' # add customized lines (here: the mean `mpg` for each `cyl` group) \n#' tinyplot_add(type = type_hline(with(mtcars, tapply(mpg, cyl, mean))), lty = 2)\n#' \n#' # Similar idea for vline\n#' tinyplot_add(type = type_vline(with(mtcars, tapply(hp, cyl, mean))), lty = 2)\n#' \n#' #\n#' ## Recycling logic\n#' \n#' # length(h) == no. of groups\n#' tinyplot(mpg ~ wt | factor(cyl), data = mtcars, type = type_hline(h = 21:23))\n#' \n#' # length(h) == no. of facets\n#' tinyplot(mpg ~ wt, facet = ~am, data = mtcars, type = type_hline(h = c(20, 30)))\n#' \n#' # length(h) == no. of groups x no. of facets\n#' tinyplot(mpg ~ wt | factor(cyl), facet = ~am, data = mtcars,\n#' type = type_hline(h = 21:26))\n#' \n#' # special adjustment case (here: lwd by group)\n#' tinyplot(mpg ~ wt | factor(cyl), facet = ~am, data = mtcars,\n#' type = type_hline(c(20, 30)), lwd = c(21, 14, 7))\n#' \n#' @export\ntype_abline = function(a = 0, b = 1) {\n data_abline = function(datapoints, lwd, lty, col, ...) {\n if (nrow(datapoints) == 0) {\n msg = \"`type_abline() only works on existing plots with x and y data points.\"\n stop(msg, call. = FALSE)\n }\n # keep track of unique lty and lwd (needed for group catch / escape hatch\n # later in draw_hline)\n ul_lwd = length(unique(lwd))\n ul_lty = length(unique(lty))\n ul_col = length(unique(col))\n return(list(type_info = list(ul_lty = ul_lty, ul_lwd = ul_lwd, ul_col = ul_col)))\n }\n draw_abline = function() {\n fun = function(\n ifacet, iby, data_facet, icol, ilty, ilwd,\n ngrps, nfacets, by_continuous, facet_by,\n type_info,\n ...\n ) {\n \n # flag for aesthetics by groups\n grp_aes = type_info[[\"ul_col\"]] == 1 || type_info[[\"ul_lty\"]] == ngrps || type_info[[\"ul_lwd\"]] == ngrps\n \n if (length(a) != 1) {\n if (!length(a) %in% c(ngrps, nfacets, ngrps*nfacets)) {\n msg = \"Length of 'a' must be 1, or equal to the number of facets or number of groups (or product thereof).\"\n stop(msg, call. = FALSE)\n }\n if (!facet_by && length(a) == nfacets) {\n a = a[ifacet]\n if (!grp_aes && type_info[[\"ul_col\"]]!=ngrps) {\n icol = 1\n } else if (by_continuous) {\n icol = 1\n }\n } else if (!by_continuous && length(a) == ngrps * nfacets) {\n a = a[ifacet * ngrps - c(ngrps - iby)]\n } else if (!by_continuous) {\n a = a[iby]\n }\n } else if (!grp_aes) {\n icol = 1\n }\n \n if (length(b) != 1) {\n if (!length(b) %in% c(ngrps, nfacets, ngrps*nfacets)) {\n msg = \"Length of 'b' must be 1, or equal to the number of facets or number of groups (or product thereof).\"\n stop(msg, call. = FALSE)\n }\n if (!facet_by && length(b) == nfacets) {\n b = b[ifacet]\n if (!grp_aes && type_info[[\"ul_col\"]]!=ngrps) {\n icol = 1\n } else if (by_continuous) {\n icol = 1\n }\n } else if (!by_continuous && length(b) == ngrps * nfacets) {\n b = b[ifacet * ngrps - c(ngrps - iby)]\n } else if (!by_continuous) {\n b = b[iby]\n }\n } else if (!grp_aes) {\n icol = 1\n }\n \n if (type_info[[\"ul_col\"]]!=1 && !(type_info[[\"ul_lty\"]]==ngrps || type_info[[\"ul_lwd\"]]==ngrps)) {\n icol = 1\n }\n\n abline(a = a, b = b, col = icol, lty = ilty, lwd = ilwd)\n }\n return(fun)\n }\n out = list(\n draw = draw_abline(),\n data = data_abline,\n name = \"abline\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/facet.R", "#' Draw facet windows\n#' \n#' @description Internal functions called from `tinyplot` in order to draw the\n#' plot window with different facets, grids, axes, etc. \n#' \n#' `facet_layout` determines the layout of the facets, based on a set of inputs.\n#' \n#' `draw_facet_window` is the main workhorse function for setting the exterior\n#' plot elements as part of a `tinyplot` call, including adjustment of margins\n#' for dynamic themes, etc.\n#' \n#' @keywords internal\n#' @rdname facet\ndraw_facet_window = function(\n # add arg first, since that determines what happens (if at all)\n add,\n # facet-specific args\n cex_fct_adj,\n facet.args,\n facet_newlines, facet_font, facet_rect, facet_text,\n facet_col, facet_bg, facet_border,\n facet, facets, ifacet,\n nfacets, nfacet_cols, nfacet_rows,\n # axes args\n axes, flip, frame.plot, oxaxis, oyaxis,\n xlabs, xlim, xlim_user, xaxt, xaxs, xaxb, xaxl,\n ylabs, ylim, ylim_user, yaxt, yaxs, yaxb, yaxl,\n asp, log,\n # other args (in approx. alphabetical + group ordering)\n dots,\n draw,\n grid,\n has_legend,\n type,\n x, xmax, xmin,\n y, ymax, ymin\n ) {\n \n # if add is TRUE, just return inputs without any calculations\n if (isTRUE(add)) {\n return(as.list(environment()))\n }\n \n # if breaks are provided use these (but only if x/ylabs are null)\n if (!is.null(xaxb) && !is.null(xlabs)) xlabs = xaxb\n if (!is.null(yaxb) && !is.null(ylabs)) ylabs = yaxb\n \n # draw background color only in the grid rectangle\n grid.bg = get_tpar(\"grid.bg\")\n if (!is.null(grid.bg)) {\n corners = par(\"usr\")\n rect(corners[1], corners[3], corners[2], corners[4], col = grid.bg, border = NA)\n }\n\n ## dynamic margins flag\n dynmar = isTRUE(.tpar[[\"dynmar\"]])\n \n ## optionally allow to modify the style of axis interval calculation\n if (!is.null(xaxs)) par(xaxs = xaxs)\n if (!is.null(yaxs)) par(yaxs = yaxs)\n\n if (nfacets > 1) {\n # Set facet margins (i.e., gaps between facets)\n if (is.null(facet.args[[\"fmar\"]])) {\n fmar = tpar(\"fmar\")\n } else {\n if (length(facet.args[[\"fmar\"]]) != 4) {\n warning(\n \"`fmar` has to be a vector of length four, e.g.\",\n \"`facet.args = list(fmar = c(b,l,t,r))`.\",\n \"\\n\",\n \"Resetting to fmar = c(1,1,1,1) default.\",\n \"\\n\"\n )\n fmar = tpar(\"fmar\")\n } else {\n fmar = facet.args[[\"fmar\"]]\n }\n }\n # We need to adjust for n>=3 facet cases for correct spacing...\n if (nfacets >= 3) {\n ## ... exception for 2x2 cases\n if (!(nfacet_rows == 2 && nfacet_cols == 2)) fmar = fmar * .75\n }\n # Extra reduction if no plot frame to reduce whitespace\n if (isFALSE(frame.plot) && !isTRUE(facet.args[[\"free\"]])) {\n fmar = fmar - 0.5\n }\n\n ooma = par(\"oma\")\n\n # Bump top margin down for facet titles\n fmar[3] = fmar[3] + 1\n if (isTRUE(attr(facet, \"facet_grid\"))) {\n fmar[3] = max(0, fmar[3] - 1)\n # Indent for RHS facet_grid title strip if \"right!\" legend\n if (has_legend && ooma[4] > 0) ooma[4] = ooma[4] + 1\n }\n fmar[3] = fmar[3] + facet_newlines * facet_text / cex_fct_adj\n\n omar = par(\"mar\")\n \n ## Dynamic plot margin adjustments\n if (dynmar) {\n if (par(\"las\") %in% 1:2) {\n # extra whitespace bump on the y axis\n ## overrides for ridge and some types that use integer spacing with (named) axis labels ## FXIME\n if (type == \"ridge\") {\n yaxlabs = levels(y)\n } else if (!is.null(ylabs)) {\n yaxlabs = if (!is.null(names(ylabs))) names(ylabs) else ylabs \n } else if (type == \"boxplot\" && isTRUE(flip) && !is.null(xlabs)) {\n yaxlabs = if (!is.null(names(xlabs))) names(xlabs) else xlabs \n } else {\n # yaxl = axTicks(2)\n yaxlabs = axisTicks(usr = extendrange(ylim, f = 0.04), log = par(\"ylog\"))\n }\n if (!is.null(yaxl)) yaxlabs = tinylabel(yaxlabs, yaxl)\n # whtsbp = grconvertX(max(strwidth(yaxl, \"figure\")), from = \"nfc\", to = \"lines\") - 1\n whtsbp = grconvertX(max(strwidth(yaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - grconvertX(0, from = \"nfc\", to = \"lines\") - 1\n if (whtsbp > 0) {\n omar = omar + c(0, whtsbp, 0, 0) * cex_fct_adj\n fmar[2] = fmar[2] + whtsbp * cex_fct_adj\n }\n # Extra reduction if no plot frame to reduce whitespace\n if (isFALSE(frame.plot) && !isTRUE(facet.args[[\"free\"]])) {\n fmar[2] = fmar[2] - (whtsbp * cex_fct_adj)\n }\n }\n if (par(\"las\") %in% 2:3) {\n # extra whitespace bump on the x axis\n # xaxlabs = axTicks(1)\n xaxlabs = if (is.null(xlabs)) axisTicks(usr = extendrange(xlim, f = 0.04), log = par(\"xlog\")) else \n if (!is.null(names(xlabs))) names(xlabs) else xlabs\n if (!is.null(xaxl)) xaxlabs = tinylabel(xaxlabs, xaxl)\n whtsbp = grconvertX(max(strwidth(xaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - 1\n if (whtsbp > 0) {\n omar = omar + c(whtsbp, 0, 0, 0) * cex_fct_adj\n fmar[1] = fmar[1] + whtsbp * cex_fct_adj\n }\n # Extra reduction if no plot frame to reduce whitespace\n if (isFALSE(frame.plot) && !isTRUE(facet.args[[\"free\"]])) {\n fmar[1] = fmar[1] - (whtsbp * cex_fct_adj)\n }\n }\n # FIXME: Is this causing issues for lhs legends with facet_grid?\n # catch for missing rhs legend\n if (isTRUE(attr(facet, \"facet_grid\")) && !has_legend) {\n omar[4] = omar[4] + 1\n }\n }\n\n # Now we set the margins. The trick here is that we simultaneously adjust\n # inner (mar) and outer (oma) margins by the same amount, but in opposite\n # directions, to preserve the overall facet and plot centroids.\n nmar = (fmar + .1) / cex_fct_adj\n noma = (ooma + omar - fmar - .1) / cex_fct_adj\n # Catch in case of negative oma values. (Probably only occurs with some\n # user-supplied tpar(lmar) values and a \"left!\" positioned legend.)\n if (any(noma < 0)) {\n noma_orig = noma\n noma[noma < 0] = 0\n # noma_diff = noma-noma_orig\n # nmar = nmar + noma_diff\n }\n # apply changes\n par(oma = noma)\n par(mar = nmar)\n\n # Now that the margins have been set, arrange facet rows and columns based\n # on our earlier calculations.\n par(mfrow = c(nfacet_rows, nfacet_cols))\n } else if (dynmar) {\n # Dynamic plot margin adjustments\n omar = par(\"mar\")\n omar = omar - c(0, 0, 1, 0) # reduce top whitespace since no facet (title)\n if (type == \"spineplot\") omar[4] = 2.1 # FIXME catch for spineplot RHS axis labs\n if (par(\"las\") %in% 1:2) {\n # extra whitespace bump on the y axis\n ## overrides for ridge and some types that use integer spacing with (named) axis labels ## FXIME\n if (type == \"ridge\") {\n yaxlabs = levels(y)\n } else if (!is.null(ylabs)) {\n yaxlabs = if (!is.null(names(ylabs))) names(ylabs) else ylabs \n } else if (type == \"boxplot\" && isTRUE(flip) && !is.null(xlabs)) {\n yaxlabs = if (!is.null(names(xlabs))) names(xlabs) else xlabs \n } else {\n # yaxl = axTicks(2)\n yaxlabs = axisTicks(usr = extendrange(ylim, f = 0.04), log = par(\"ylog\"))\n }\n if (!is.null(yaxl)) yaxlabs = tinylabel(yaxlabs, yaxl)\n # whtsbp = grconvertX(max(strwidth(yaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - 1\n whtsbp = grconvertX(max(strwidth(yaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - grconvertX(0, from = \"nfc\", to = \"lines\") - 1\n if (whtsbp > 0) {\n omar[2] = omar[2] + whtsbp\n }\n }\n if (par(\"las\") %in% 2:3) {\n # extra whitespace bump on the x axis\n # xaxl = axTicks(1)\n xaxlabs = if (is.null(xlabs)) axisTicks(usr = extendrange(xlim, f = 0.04), log = par(\"xlog\")) else \n if (!is.null(names(xlabs))) names(xlabs) else xlabs\n if (!is.null(xaxl)) xaxlabs = tinylabel(xaxlabs, xaxl)\n whtsbp = grconvertX(max(strwidth(xaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - 1\n if (whtsbp > 0) {\n omar[1] = omar[1] + whtsbp\n }\n }\n par(mar = omar)\n }\n\n ## Loop over the individual facet windows and draw the plot region\n ## components (axes, titles, box, grid, etc.)\n for (ii in ifacet) {\n # See: https://github.com/grantmcdermott/tinyplot/issues/65\n if (nfacets > 1) {\n mfgi = ceiling(ii / nfacet_cols)\n mfgj = ii %% nfacet_cols\n if (mfgj == 0) mfgj = nfacet_cols\n par(mfg = c(mfgi, mfgj))\n }\n\n ## Set the plot window\n ## Problem: Passing extra args through ... (e.g., legend_args) to plot.window\n ## triggers an annoying warning about unrecognized graphical params.\n # plot.window(\n # xlim = xlim, ylim = ylim,\n # asp = asp, log = log,\n # # ...\n # )\n ## Solution: Only pass on relevant args using name checking and do.call.\n ## Idea borrowed from here: https://stackoverflow.com/a/4128401/4115816\n pdots = dots[names(dots) %in% names(formals(plot.default))]\n ## catch for flipped boxplots...\n if (type == \"boxplot\" && isTRUE(flip)) {\n log_flip = log\n if (!is.null(log)) {\n if (log == \"x\") log_flip = \"y\"\n if (log == \"y\") log_flip = \"x\"\n }\n do.call(\n \"plot.window\",\n c(list(xlim = ylim, ylim = xlim, asp = asp, log = log_flip), pdots)\n )\n xside = 2\n yside = 1\n } else {\n ## ... standard plot window for all other cases\n do.call(\n \"plot.window\",\n c(list(xlim = xlim, ylim = ylim, asp = asp, log = log), pdots)\n )\n xside = 1\n yside = 2\n }\n\n\n # axes, frame.plot and grid\n if (isTRUE(axes) || isTRUE(facet.args[[\"free\"]])) {\n args_x = list(x,\n side = xside,\n type = xaxt,\n labeller = xaxl,\n cex = get_tpar(c(\"cex.xaxs\", \"cex.axis\"), 0.8),\n lwd = get_tpar(c(\"lwd.xaxs\", \"lwd.axis\"), 1),\n lty = get_tpar(c(\"lty.xaxs\", \"lty.axis\"), 1)\n )\n args_y = list(y,\n side = yside,\n type = yaxt,\n labeller = yaxl,\n cex = get_tpar(c(\"cex.yaxs\", \"cex.axis\"), 0.8),\n lwd = get_tpar(c(\"lwd.yaxs\", \"lwd.axis\"), 1),\n lty = get_tpar(c(\"lty.yaxs\", \"lty.axis\"), 1)\n )\n if (!is.null(xaxb)) args_x$at = xaxb\n if (!is.null(yaxb)) args_y$at = yaxb\n type_range_x = type %in% c(\"barplot\", \"pointrange\", \"errorbar\", \"ribbon\", \"boxplot\", \"p\", \"violin\") && !is.null(xlabs)\n type_range_y = !is.null(ylabs) && (type == \"p\" || (isTRUE(flip) && type %in% c(\"barplot\", \"pointrange\", \"errorbar\", \"ribbon\", \"boxplot\", \"violin\")))\n if (type_range_x) {\n args_x = modifyList(args_x, list(at = xlabs, labels = names(xlabs)))\n }\n if (type_range_y) {\n args_y = modifyList(args_y, list(at = ylabs, labels = names(ylabs)))\n }\n\n if (isTRUE(facet.args[[\"free\"]]) && (par(\"xlog\") || par(\"ylog\"))) {\n warning(\n \"\\nFree scale axes for faceted plots are currently not supported if the axes are logged. Reverting back to fixed scales.\",\n \"\\nIf support for this feature is important to you, please raise an issue on our GitHub repo:\",\n \"\\nhttps://github.com/grantmcdermott/tinyplot/issues\\n\"\n )\n facet.args[[\"free\"]] = FALSE\n }\n\n # Special logic if facets are free...\n if (isTRUE(facet.args[[\"free\"]])) {\n # First, we need to calculate the plot extent and axes range of each\n # individual facet.\n xfree = split(c(x, xmin, xmax), facet)[[ii]]\n yfree = split(c(y, ymin, ymax), facet)[[ii]]\n if (!xlim_user) xlim = range(xfree, na.rm = TRUE)\n if (!ylim_user) ylim = range(yfree, na.rm = TRUE)\n xext = extendrange(xlim, f = 0.04)\n yext = extendrange(ylim, f = 0.04)\n # We'll save this in a special .fusr env var (list) that we'll re-use\n # when it comes to plotting the actual elements later\n if (ii == 1) {\n fusr = replicate(4, vector(\"double\", length = nfacets), simplify = FALSE)\n assign(\".fusr\", fusr, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n }\n fusr = get(\".fusr\", envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n fusr[[ii]] = c(xext, yext)\n assign(\".fusr\", fusr, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n # Explicitly set (override) the current facet extent\n par(usr = fusr[[ii]])\n # if plot frame is true then print axes per normal...\n if (type %in% c(\"barplot\", \"pointrange\", \"errorbar\", \"ribbon\", \"boxplot\", \"p\", \"violin\") && !is.null(xlabs)) {\n tinyAxis(xfree, side = xside, at = xlabs, labels = names(xlabs), type = xaxt, labeller = xaxl)\n } else {\n tinyAxis(xfree, side = xside, type = xaxt, labeller = xaxl)\n }\n if (isTRUE(flip) && type %in% c(\"barplot\", \"pointrange\", \"errorbar\", \"ribbon\", \"boxplot\", \"p\", \"violin\") && !is.null(ylabs)) {\n tinyAxis(yfree, side = yside, at = ylabs, labels = names(ylabs), type = yaxt, labeller = yaxl)\n } else {\n tinyAxis(yfree, side = yside, type = yaxt, labeller = yaxl)\n }\n\n # For fixed facets we can just reuse the same plot extent and axes limits\n } else if (isTRUE(frame.plot)) {\n # if plot frame is true then print axes per normal...\n do.call(tinyAxis, args_x)\n do.call(tinyAxis, args_y)\n } else {\n # ... else only print the \"outside\" axes.\n if (ii %in% oxaxis) do.call(tinyAxis, args_x)\n if (ii %in% oyaxis) do.call(tinyAxis, args_y)\n }\n }\n\n # facet titles\n ## Note: facet titles could be done more simply with mtext... but then we\n ## couldn't adjust background features (e.g., fill), or rotate the rhs\n ## facet grid text. So we're rolling our own \"manual\" versions with text\n ## and rect.\n if (!is.null(facet)) {\n # Get the four corners of plot area (x1, x2, y1, y2)\n corners = par(\"usr\")\n # catch for logged axes\n xlog = isTRUE(par(\"xlog\"))\n ylog = isTRUE(par(\"ylog\"))\n if (xlog) corners[1:2] = 10^(corners[1:2])\n if (ylog) corners[3:4] = 10^(corners[3:4])\n # special logic for facet grids\n if (is.null(facet_newlines) || facet_newlines == 0) {\n facet_title_lines = 1\n } else {\n facet_title_lines = 1 + facet_newlines\n }\n # different logic for facet grids versus regular facets\n if (isTRUE(attr(facet, \"facet_grid\"))) {\n ## top facet strips\n if (ii %in% 1:nfacet_cols) {\n if (isTRUE(facet_rect)) {\n line_height = (facet_title_lines + .1) * facet_text / cex_fct_adj\n if (ylog) {\n line_height = grconvertY(line_height, from = \"lines\", to = \"user\") / grconvertY(0, from = \"lines\", to = \"user\")\n rect_height = corners[4] * line_height\n } else {\n line_height = grconvertY(line_height, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\")\n rect_height = corners[4] + line_height\n }\n rect(\n corners[1], corners[4], corners[2], rect_height,\n col = facet_bg, border = facet_border,\n xpd = NA\n )\n }\n xpos = if (xlog) 10^(mean(log10(corners[1:2]))) else mean(corners[1:2])\n if (ylog) {\n ypos = grconvertY(0.4, from = \"lines\", to = \"user\") / grconvertY(0, from = \"lines\", to = \"user\")\n ypos = corners[4] * ypos\n } else {\n ypos = grconvertY(0.4, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\")\n ypos = corners[4] + ypos\n }\n text(\n x = xpos,\n y = ypos,\n labels = sub(\"^(.*?)~.*\", \"\\\\1\", facets[[ii]]),\n adj = c(0.5, 0),\n cex = facet_text / cex_fct_adj,\n col = facet_col,\n font = facet_font,\n xpd = NA,\n )\n }\n ## right facet strips\n if (ii %% nfacet_cols == 0 || ii == nfacets) {\n if (isTRUE(facet_rect)) {\n line_height = (facet_title_lines + .1) * facet_text / cex_fct_adj\n if (xlog) {\n line_height = grconvertX(line_height, from = \"lines\", to = \"user\") / grconvertX(0, from = \"lines\", to = \"user\")\n rect_width = corners[2] * line_height\n } else {\n line_height = grconvertX(line_height, from = \"lines\", to = \"user\") - grconvertX(0, from = \"lines\", to = \"user\")\n rect_width = corners[2] + line_height\n }\n rect(\n corners[2], corners[3], rect_width, corners[4],\n col = facet_bg, border = facet_border,\n xpd = NA\n )\n }\n if (xlog) {\n xpos = grconvertX(0.4, from = \"lines\", to = \"user\") / grconvertX(0, from = \"lines\", to = \"user\")\n xpos = corners[2] * xpos\n } else {\n xpos = grconvertX(0.4, from = \"lines\", to = \"user\") - grconvertX(0, from = \"lines\", to = \"user\")\n xpos = corners[2] + xpos\n }\n ypos = if (ylog) 10^(mean(log10(corners[3:4]))) else mean(corners[3:4])\n text(\n x = xpos,\n y = ypos,\n labels = sub(\"^.*?~(.*)\", \"\\\\1\", facets[[ii]]),\n srt = 270,\n adj = c(0.5, 0),\n cex = facet_text / cex_fct_adj,\n col = facet_col,\n font = facet_font,\n xpd = NA\n )\n }\n } else {\n if (isTRUE(facet_rect)) {\n line_height = (facet_title_lines + .1) * facet_text / cex_fct_adj\n if (ylog) {\n line_height = grconvertY(line_height, from = \"lines\", to = \"user\") / grconvertY(0, from = \"lines\", to = \"user\")\n rect_height = corners[4] * line_height\n } else {\n line_height = grconvertY(line_height, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\")\n rect_height = corners[4] + line_height\n }\n rect(\n corners[1], corners[4], corners[2], rect_height,\n col = facet_bg, border = facet_border,\n xpd = NA\n )\n }\n xpos = if (xlog) 10^(mean(log10(corners[1:2]))) else mean(corners[1:2])\n if (ylog) {\n ypos = grconvertY(0.4, from = \"lines\", to = \"user\") / grconvertY(0, from = \"lines\", to = \"user\")\n ypos = corners[4] * ypos\n } else {\n ypos = grconvertY(0.4, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\")\n ypos = corners[4] + ypos\n }\n text(\n x = xpos,\n y = ypos,\n labels = paste(facets[[ii]]),\n adj = c(0.5, 0),\n cex = facet_text / cex_fct_adj,\n col = facet_col,\n font = facet_font,\n xpd = NA\n )\n }\n }\n\n # plot frame\n if (frame.plot) box()\n\n # panel grid lines\n if (is.null(grid)) grid = .tpar[[\"grid\"]]\n if (!is.null(grid)) {\n if (is.logical(grid)) {\n ## If grid is TRUE create a default grid. Rather than just calling the default grid()\n ## abline(... = pretty(extendrange(...)), ...) is used. Reason: pretty() is generic\n ## and works better for axes based on date/time classes. Exception: For axes in logs,\n ## resort to using grid() which is likely better handled there.\n if (isTRUE(grid)) {\n gnx = gny = NULL\n if (!is.null(xaxb)) {\n abline(v = xaxb, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n gnx = NA\n } else if (!any(c(par(\"xlog\"), type == \"boxplot\"))) {\n xg = if (!inherits(x, c(\"POSIXt\", \"Date\"))) axTicks(side = 1) else axTicksDateTime(side = 1, x = x)\n abline(v = xg, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n gnx = NA\n }\n if (!is.null(yaxb)) {\n abline(h = yaxb, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n gny = NA\n } else if (!any(c(par(\"ylog\"), type == \"boxplot\"))) {\n yg = if (!inherits(y, c(\"POSIXt\", \"Date\"))) axTicks(side = 2) else axTicksDateTime(side = 2, x = x)\n abline(h = yg, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n gny = NA\n }\n grid(nx = gnx, ny = gny, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n }\n } else {\n grid\n }\n }\n\n # add any drawn elements\n if (!is.null(draw)) eval(draw)\n } # end of ii facet loop\n\n return(as.list(environment()))\n}\n\n\n#' @rdname facet\n#' @keywords internal\nfacet_layout = function(facet, add = FALSE, facet.args = list()) {\n nfacet_rows = 1\n nfacet_cols = 1\n if (!is.null(facet)) {\n facets = if (is.factor(facet)) levels(facet) else sort(unique(facet))\n ifacet = seq_along(facets)\n nfacets = length(facets)\n if (isTRUE(add)) {\n omfrow = par(\"mfrow\")\n nfacet_rows = omfrow[1]\n nfacet_cols = omfrow[2]\n } else {\n if (isTRUE(attr(facet, \"facet_grid\"))) {\n facet.args[[\"nrow\"]] = attr(facet, \"facet_nrow\")\n }\n if (!is.null(facet.args[[\"nrow\"]])) {\n nfacet_rows = facet.args[[\"nrow\"]]\n nfacet_cols = ceiling(nfacets / nfacet_rows)\n } else if (!is.null(facet.args[[\"ncol\"]])) {\n nfacet_cols = facet.args[[\"ncol\"]]\n nfacet_rows = ceiling(nfacets / nfacet_cols)\n } else {\n if (nfacets > 3) {\n nfacet_cols = ceiling(sqrt(nfacets))\n nfacet_rows = ceiling(nfacets / nfacet_cols)\n } else {\n nfacet_rows = 1L\n nfacet_cols = nfacets\n }\n }\n }\n\n oxaxis = tail(ifacet, nfacet_cols)\n oyaxis = seq(1, nfacets, by = nfacet_cols)\n\n if (nfacet_rows >= 3 || nfacet_cols >= 3) {\n cex_fct_adj = 0.66\n } else if (nfacet_rows == 2 && nfacet_cols == 2) {\n cex_fct_adj = 0.83\n } else {\n cex_fct_adj = 1\n }\n } else {\n facets = ifacet = nfacets = oxaxis = oyaxis = 1\n cex_fct_adj = 1\n }\n\n list(\n facets = facets,\n ifacet = ifacet,\n nfacets = nfacets,\n nfacet_rows = nfacet_rows,\n nfacet_cols = nfacet_cols,\n oxaxis = oxaxis,\n oyaxis = oyaxis,\n cex_fct_adj = cex_fct_adj\n )\n}\n\n\n\n#\n# helper functions\n#\n\n\n# utility function for converting facet formulas into variables\nget_facet_fml = function(formula, data = NULL) {\n xfacet = yfacet = NULL\n\n ## catch one-sided formula ~ x or ~ x | z with no \"y\" variable\n if (!inherits(formula, \"formula\")) formula = as.formula(formula)\n no_yfacet = length(formula) == 2L\n fml_rhs = if (no_yfacet) 2L else 3L\n\n ## set up model frame\n m = match.call(expand.dots = FALSE)\n\n if (!is.null(data)) {\n m = m[c(1L, match(c(\"formula\", \"data\", \"subset\", \"na.action\", \"drop.unused.levels\"), names(m), 0L))]\n }\n\n m$formula = formula\n ## need stats:: for non-standard evaluation\n m[[1L]] = quote(stats::model.frame)\n mf = eval.parent(m)\n\n ## extract variables: x, y (if any)\n if (no_yfacet) {\n yfacet_loc = NULL\n xfacet_loc = 1L\n } else {\n yfacet_loc = 1L\n xfacet_loc = 2L\n }\n if (NCOL(mf) < xfacet_loc) stop(\"formula should specify at least one variable on the right-hand side\")\n yfacet = if (no_yfacet) NULL else mf[, yfacet_loc]\n xfacet = mf[, xfacet_loc:NCOL(mf)]\n\n ## return object\n xfacet = interaction(xfacet, sep = \":\")\n if (no_yfacet) {\n ret = xfacet\n } else {\n # yfacet = interaction(yfacet, sep = \":\")\n ## NOTE: We \"swap\" the formula LHS and RHS since mfrow plots rowwise\n ret = interaction(xfacet, yfacet, sep = \"~\")\n attr(ret, \"facet_grid\") = TRUE\n attr(ret, \"facet_nrow\") = length(unique(yfacet))\n }\n\n return(ret)\n}\n\n\n## internal convenience function to determine whether the current facet panel\n## has the position \"left\", \"right\", \"top\", or \"bottom\" in the facet grid\nis_facet_position = function(position, ifacet, facet_window_args) {\n id = facet_window_args$ifacet\n nc = facet_window_args$nfacet_cols\n ni = tail(id, 1L)\n switch(position,\n \"left\" = ifacet %in% seq(1L, ni, by = nc),\n \"right\" = ifacet %in% pmin(ni, seq(1L, ni, by = nc) + nc - 1L),\n \"top\" = ifacet %in% head(id, nc),\n \"bottom\" = ifacet %in% tail(id, nc),\n NA\n )\n}\n"], ["/tinyplot/R/type_barplot.R", "#' Barplot type\n#'\n#' @description Type function for producing barplots. For formulas of type\n#' `~ x` (without left-hand side) the barplot visualizes the counts (absolute\n#' frequencies) of the levels of `x`. For formulas of type `y ~ x` the value\n#' of `y` within each level of `x` is visualized, if necessary aggregated\n#' using some function (default: mean).\n#'\n#' @param width numeric, optional vector of bar widths. (The distance between\n#' the midpoints of the bars is always 1.)\n#' @param beside logical. In case of a `by` grouping variable, should bars be\n#' juxtaposed? Default is to use stacked bars instead.\n#' @param center logical or numeric. In case of stacked barplots (`beside = FALSE`)\n#' should the bars be centered (or all start at zero, default)? If set to\n#' `TRUE` the center is at the mid-point of the middle category (in case of\n#' uneven number of categories) or between the two middle categories (in case\n#' of an even number). Additionally it is possible to set `center = 2` or\n#' `center = 2.5` to indicate that centering should be after the second category\n#' or the mid-way in the third category, respectively.\n#' @param FUN a function to compute the summary statistic for `y` within each\n#' group of `x` in case of using a two-sided formula `y ~ x` (default: mean).\n#' @param xlevels a character or numeric vector specifying the ordering of the\n#' levels of the `x` variable (if character) or the corresponding indexes\n#' (if numeric) for the plot.\n#' @param xaxlabels a character vector with the axis labels for the `x` variable,\n#' defaulting to the levels of `x`.\n#' @param drop.zeros logical. Should bars with zero height be dropped? If set\n#' to `FALSE` (default) a zero height bar is still drawn for which the border\n#' lines will still be visible.\n#'\n#' @examples\n#' # Basic examples of frequency tables (without y variable)\n#' tinyplot(~ cyl, data = mtcars, type = \"barplot\")\n#' tinyplot(~ cyl | vs, data = mtcars, type = \"barplot\")\n#' tinyplot(~ cyl | vs, data = mtcars, type = \"barplot\", beside = TRUE)\n#' tinyplot(~ cyl | vs, data = mtcars, type = \"barplot\", beside = TRUE, fill = 0.2)\n#' \n#' # Reorder x variable categories either by their character levels or numeric indexes\n#' tinyplot(~ cyl, data = mtcars, type = \"barplot\", xlevels = c(\"8\", \"6\", \"4\"))\n#' tinyplot(~ cyl, data = mtcars, type = \"barplot\", xlevels = 3:1)\n#' \n#' # Note: Above we used automatic argument passing for `beside`. But this\n#' # wouldn't work for `width`, since it would conflict with the top-level\n#' # `tinyplot(..., width = )` argument. It's safer to pass these args\n#' # through the `type_barplot()` functional equivalent.\n#' tinyplot(~ cyl | vs, data = mtcars, fill = 0.2,\n#' type = type_barplot(beside = TRUE, drop.zeros = TRUE, width = 0.65))\n#'\n#' tinytheme(\"clean2\")\n#' \n#' # Example for numeric y aggregated by x (default: FUN = mean) + facets\n#' tinyplot(extra ~ ID | group, facet = \"by\", data = sleep,\n#' type = \"barplot\", fill = 0.6)\n#' \n#' # Fancy frequency table:\n#' tinyplot(Freq ~ Sex | Survived, facet = ~ Class, data = as.data.frame(Titanic),\n#' type = \"barplot\", facet.args = list(nrow = 1), flip = TRUE, fill = 0.6)\n#'\n#' # Centered barplot for conditional proportions of hair color (black/brown vs.\n#' # red/blond) given eye color and sex\n#' tinytheme(\"clean2\", palette.qualitative = c(\"black\", \"sienna\", \"indianred\", \"goldenrod\"))\n#' hec = as.data.frame(proportions(HairEyeColor, 2:3))\n#' tinyplot(Freq ~ Eye | Hair, facet = ~ Sex, data = hec, type = \"barplot\",\n#' center = TRUE, flip = TRUE, facet.args = list(ncol = 1), yaxl = \"percent\")\n#'\n#' tinytheme()\n#' \n#' @export\ntype_barplot = function(width = 5/6, beside = FALSE, center = FALSE, FUN = NULL, xlevels = NULL, xaxlabels = NULL, drop.zeros = FALSE) {\n out = list(\n data = data_barplot(width = width, beside = beside, center = center, FUN = FUN, xlevels = xlevels, xaxlabels = xaxlabels, drop.zeros = drop.zeros),\n draw = draw_rect(),\n name = \"barplot\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n#' @importFrom stats aggregate\ndata_barplot = function(width = 5/6, beside = FALSE, center = FALSE, FUN = NULL, xlevels = NULL, xaxlabels = NULL, drop.zeros = FALSE) {\n fun = function(datapoints, col, bg, lty, lwd, palette, xlab = NULL, ylab = NULL, xlim = NULL, ylim = NULL, xaxt = NULL, yaxl = NULL, yaxt = NULL, axes = TRUE, null_by, facet_by, ...) {\n\n \n ## tabulate/aggregate datapoints\n if (is.null(datapoints$y)) {\n xlab = ylab\n ylab = \"Count\"\n \n datapoints$y = numeric(nrow(datapoints)) \n if (!is.null(FUN)) warning(\"without 'y' variable 'FUN' specification is ignored\")\n FUN = length\n } else {\n if (is.null(FUN)) FUN = function(x, ...) mean(x, ..., na.rm = TRUE)\n }\n if (!is.factor(datapoints$x)) datapoints$x = factor(datapoints$x)\n if (!is.null(xlevels)) {\n xlevels = if(is.numeric(xlevels)) levels(datapoints$x)[xlevels] else xlevels\n if (any(is.na(xlevels)) || !all(xlevels %in% levels(datapoints$x))) warning(\"not all 'xlevels' correspond to levels of 'x'\")\n datapoints$x = factor(datapoints$x, levels = xlevels)\n }\n if (!is.null(xaxlabels)) levels(datapoints$x) <- xaxlabels\n datapoints = aggregate(datapoints[, \"y\", drop = FALSE], datapoints[, c(\"x\", \"by\", \"facet\")], FUN = FUN, drop = FALSE)\n datapoints$y[is.na(datapoints$y)] = 0 #FIXME: always?#\n if (!is.factor(datapoints$by)) datapoints$by = factor(datapoints$by)\n if (!is.factor(datapoints$facet)) datapoints$facet = factor(datapoints$facet)\n \n if (isFALSE(null_by) && isFALSE(facet_by) && !beside && any(datapoints$y < 0)) {\n warning(\"'beside' must be TRUE if there are negative 'y' values\")\n beside = TRUE\n }\n if (beside & !isFALSE(center)) {\n warning(\"'center' is currently only supported for 'beside = FALSE'\")\n }\n offset_sum = function(z, center = TRUE, na.rm = TRUE) {\n n = length(z)\n if (isFALSE(center) || n < 1L) return(0)\n mid = if (isTRUE(center)) n/2 else center\n z[floor(mid) + 1L] = (mid - floor(mid)) * z[floor(mid) + 1L]\n sum(z[0L:floor(mid) + 1L], na.rm = TRUE)\n }\n if (is.null(xlim)) xlim = c(1, length(levels(datapoints$x))) + c(-0.5, 0.5) * width\n if (is.null(ylim)) ylim = if (beside || length(unique(datapoints$by)) == 1L) {\n c(pmin(0, min(datapoints$y, na.rm = TRUE) * 1.02), pmax(0, max(datapoints$y, na.rm = TRUE) * 1.02))\n } else {\n range(unlist(tapply(\n datapoints$y,\n interaction(datapoints$x, datapoints$facet),\n function(z) c(0, sum(z, na.rm = TRUE)) - offset_sum(z, center = center)\n ))) * 1.02\n }\n\n ## default color palette\n ngrps = length(unique(datapoints$by))\n if (ngrps == 1L && is.null(palette)) {\n if (is.null(col)) col = par(\"fg\")\n if (is.null(bg)) bg = \"grey\"\n } else {\n if (is.null(bg)) bg = \"by\"\n }\n\n ## calculate bar rectangles per facet \n sdat = split(datapoints, datapoints$facet)\n datapoints = lapply(sdat, function(df) {\n \n df = df[order(df$x), , drop = FALSE]\n nx = length(levels(df$x))\n nb = length(levels(df$by))\n \n if (beside) { \n xl = as.numeric(df$x) - width/2 + (as.numeric(df$by) - 1) * width/nb * as.numeric(!facet_by)\n xr = if (facet_by) xl + width else xl + width/nb\n yb = 0\n yt = df$y\n } else {\n cs = tapply(df$y, df$x, function(z) cumsum(c(0, z)) - offset_sum(z, center = center))\n xl = as.numeric(df$x) - width/2\n xr = xl + width\n yb = if (facet_by) 0 else unlist(lapply(cs, `[`, -(nb + 1L)))\n yt = if (facet_by) df$y else unlist(lapply(cs, `[`, -1L))\n }\n \n df$xmin = xl\n df$xmax = xr\n df$ymin = yb\n df$ymax = yt\n df$nx = nx\n \n if (drop.zeros) {\n yb = rep_len(yb, length(yt))\n yok = abs(yt - yb) > 0\n df = df[yok, , drop = FALSE]\n }\n \n return(df)\n })\n datapoints = do.call(\"rbind\", datapoints)\n nx = datapoints$nx[1]\n datapoints$nx = NULL\n xlabs = 1L:nx\n names(xlabs) = levels(datapoints$x)\n \n if (!isFALSE(center)) {\n if (is.null(yaxl)) {\n yaxl = abs\n } else if (is.character(yaxl)) {\n yaxl = paste0(\"abs_\", yaxl)\n }\n }\n \n out = list(\n datapoints = datapoints,\n xlab = xlab,\n ylab = ylab,\n xlim = xlim,\n ylim = ylim,\n axes = FALSE, #FIXME\n axes = TRUE,\n xlabs = xlabs, \n frame.plot = FALSE,\n xaxs = \"r\",\n xaxt = if (xaxt == \"s\") \"l\" else xaxt,\n yaxl = yaxl,\n yaxs = \"i\",\n col = col,\n bg = bg\n )\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_density.R", "#' Density plot type\n#' \n#' @md\n#' @description Type function for density plots.\n#' @inheritParams stats::density\n#' @param kernel a character string giving the smoothing kernel to be used. This\n#' must partially match one of `\"gaussian\"`, `\"rectangular\"`, `\"triangular\"`,\n#' `\"epanechnikov\"`, `\"biweight\"`, `\"cosine\"` or `\"optcosine\"`, with default\n#' `\"gaussian\"`, and may be abbreviated to a unique prefix (single letter).\n#'\n#' `\"cosine\"` is smoother than `\"optcosine\"`, which is the usual 'cosine'\n#' kernel in the literature and almost MSE-efficient. However, `\"cosine\"` is\n#' the version used by S.\n#' @inheritParams type_ribbon\n#' @param joint.bw character string indicating whether (and how) the smoothing\n#' bandwidth should be computed from the joint data distribution when there\n#' are multiple subgroups. The options are `\"mean\"` (the default), `\"full\"`,\n#' and `\"none\"`. Also accepts a logical argument, where `TRUE` maps to\n#' `\"mean\"` and `FALSE` maps to `\"none\"`. See the \"Bandwidth selection\"\n#' section below for a discussion of practical considerations.\n#' @inherit stats::density details\n#' @section Bandwidth selection: While the choice of smoothing bandwidth will\n#' always stand to affect a density visualization, it gains an added\n#' importance when multiple densities are drawn simultaneously (e.g., for\n#' subgroups with respect to `by` or `facet`). Allowing each subgroup to\n#' compute its own separate bandwidth independently offers greater flexibility\n#' in capturing the unique characteristics of each subgroup, particularly when\n#' distributions differ substantially in location and/or scale. However, this\n#' approach may overemphasize small random variations and make it harder to\n#' visually compare densities across subgroups. Hence, it is often useful to\n#' employ the same (\"joint\") bandwidth across all subgroups. The following\n#' strategies are available via the `joint.bw` argument:\n#' \n#' - The default `joint.bw = \"mean\"` first computes the individual bandwidths\n#' for each group but then computes their mean, weighted by the number of\n#' observations in each group. This will work well when all groups have\n#' similar amounts of scatter (similar variances), even when they have\n#' potentially rather different locations. The weighted averaging stabilizes\n#' potential fluctuations in the individual bandwidths, especially when some\n#' subgroups are rather small.\n#' \n#' - Alternatively, `joint.bw = \"full\"` can be used to compute the joint\n#' bandwidth from the full joint distribution (merging all groups). This will\n#' yield an even more robust bandwidth, especially when the groups overlap\n#' substantially (i.e., have similar locations and scales). However, it may\n#' lead to too large bandwidths and thus too much smoothing, especially when\n#' the locations of the groups differ substantially.\n#' \n#' - Finally, `joint.bw = \"none\"` disables the joint bandwidth so that each\n#' group just employs its individual bandwidth. This is often the best choice\n#' if the amounts of scatter differ substantially between the groups, thus\n#' necessitating different amounts of smoothing.\n#' @section Titles: This tinyplot method for density plots differs from the base\n#' \\code{\\link[stats]{plot.density}} function in its treatment of titles. The\n#' x-axis title displays only the variable name, omitting details about the\n#' number of observations and smoothing bandwidth. Additionally, the main\n#' title is left blank by default for a cleaner appearance.\n#' @examples\n#' # \"density\" type convenience string\n#' tinyplot(~Sepal.Length, data = iris, type = \"density\")\n#' \n#' # grouped density example\n#' tinyplot(~Sepal.Length | Species, data = iris, type = \"density\")\n#' \n#' # use `bg = \"by\"` (or, equivalent `fill = \"by\"`) to get filled densities\n#' tinyplot(~Sepal.Length | Species, data = iris, type = \"density\", fill = \"by\")\n#' \n#' # use `type_density()` to pass extra arguments for customization\n#' tinyplot(\n#' ~Sepal.Length | Species, data = iris,\n#' type = type_density(bw = \"SJ\"),\n#' main = \"Bandwidth computed using Sheather & Jones (1991)\"\n#' )\n#' \n#' # The default for grouped density plots is to use the mean of the\n#' # individual subgroup bandwidths (weighted by group size) as the\n#' # joint bandwidth. Alternatively, the bandwidth from the \"full\"\n#' # data or separate individual bandwidths (\"none\") can be used.\n#' tinyplot(~Sepal.Length | Species, data = iris,\n#' ylim = c(0, 1.25), type = \"density\") # mean (default)\n#' tinyplot_add(joint.bw = \"full\", lty = 2) # full data\n#' tinyplot_add(joint.bw = \"none\", lty = 3) # none (individual)\n#' legend(\"topright\", c(\"Mean\", \"Full\", \"None\"), lty = 1:3, bty = \"n\", title = \"Joint BW\")\n#' \n#' @importFrom stats density weighted.mean\n#' @importFrom stats bw.SJ bw.bcv bw.nrd bw.nrd0 bw.ucv \n#' @export\ntype_density = function(\n bw = \"nrd0\",\n joint.bw = c(\"mean\", \"full\", \"none\"),\n adjust = 1,\n kernel = c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"),\n n = 512,\n # more args from density here?\n alpha = NULL\n ) {\n kernel = match.arg(kernel, c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"))\n if (is.logical(joint.bw)) {\n joint.bw = ifelse(joint.bw, \"mean\", \"none\")\n }\n joint.bw = match.arg(joint.bw, c(\"mean\", \"full\", \"none\"))\n out = list(\n data = data_density(bw = bw, adjust = adjust, kernel = kernel, n = n,\n joint.bw = joint.bw, alpha = alpha),\n draw = NULL,\n name = \"density\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\ndata_density = function(bw = \"nrd0\", adjust = 1, kernel = \"gaussian\", n = 512,\n joint.bw = \"none\", alpha = NULL) {\n fun = function(by, facet, ylab, col, bg, ribbon.alpha, datapoints, ...) {\n \n ribbon.alpha = if (is.null(alpha)) .tpar[[\"ribbon.alpha\"]] else (alpha)\n \n if (is.null(ylab)) ylab = \"Density\"\n \n datapoints = split(datapoints, list(datapoints$by, datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n \n if (joint.bw == \"none\" || is.numeric(bw)) {\n dens_bw = bw\n } else {\n if (joint.bw == \"mean\") {\n # Use weighted mean of subgroup bandwidths\n bws = sapply(datapoints, function(dat) bw_fun(kernel = bw, dat$x))\n ws = sapply(datapoints, nrow)\n dens_bw = weighted.mean(bws, ws)\n } else if (joint.bw == \"full\") {\n dens_bw = bw_fun(kernel = bw, unlist(sapply(datapoints, `[[`, \"x\")))\n }\n }\n \n datapoints = lapply(datapoints, function(dat) {\n d = density(dat$x, bw = dens_bw, kernel = kernel, n = n)\n out = data.frame(\n by = dat$by[1], # already split\n facet = dat$facet[1], # already split\n y = d$y,\n x = d$x\n )\n return(out)\n })\n datapoints = do.call(rbind, datapoints)\n datapoints$ymax = datapoints$y\n datapoints$ymin = rep.int(0, nrow(datapoints))\n \n # flags for legend and fill\n dtype = if (!is.null(bg)) \"ribbon\" else \"l\"\n dwas_area_type = !is.null(bg)\n \n out = list(\n ylab = ylab,\n type = dtype,\n was_area_type = dwas_area_type,\n ribbon.alpha = ribbon.alpha,\n datapoints = datapoints,\n by = if (length(unique(datapoints$by)) == 1) by else datapoints$by, \n facet = if (length(unique(datapoints$facet)) == 1) facet else datapoints$facet\n )\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/tinyplot_add.R", "#' Add new elements to the current `tinyplot`\n#'\n#' @description\n#' This convenience function grabs the preceding `tinyplot` call and updates it\n#' with any new arguments that have been explicitly provided by the user. It\n#' then injects `add=TRUE` and evaluates the updated call, thereby drawing a new\n#' layer on top of the existing plot. `plt_add()` is a shorthand alias for\n#' `tinyplot_add()`.\n#'\n#' @section Limitations:\n#' - `tinyplot_add()` works reliably only when adding to a plot originally\n#' created using the [`tinyplot.formula`] method with a valid `data` argument.\n#' We cannot guarantee correct behavior if the original plot was created with\n#' the atomic [`tinyplot.default`] method, due to potential environment\n#' mismatches. (An exception is when the original plot arguments---`x`, `y`,\n#' etc.---are located in the global environment.)\n#'\n#' - Automatic legends for the added elements will be turned off.\n#'\n#' @param ... All named arguments override arguments from the previous calls.\n#' Arguments not supplied to [tinyplot_add] remain unchanged from the previous\n#' call.\n#'\n#' @examples\n#' tinyplot(Sepal.Width ~ Sepal.Length | Species,\n#' facet = ~Species,\n#' data = iris)\n#'\n#' tinyplot_add(type = \"lm\") ## or : plt_add(type = \"lm\")\n#'\n#' ## Note: the previous function is equivalent to (but much more convenient\n#' ## than) re-writing the full call with the new type and `add=TRUE`:\n#'\n#' # tinyplot(Sepal.Width ~ Sepal.Length | Species,\n#' # facet = ~Species,\n#' # data = iris,\n#' # type = \"lm\",\n#' # add = TRUE)\n#'\n#' @returns No return value, called for side effect of producing a plot.\n#'\n#' @export\ntinyplot_add = function(...) {\n cal = getOption(\"tinyplot_last_call\", default = NULL)\n\n ## TODO: remove the global option above and move to this when density is refactored\n # cal = get(\".last_call\", envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n\n if (is.null(cal)) {\n stop(\"No previous tinyplot call found.\")\n }\n\n args = list(...)\n for (n in names(args)) {\n if (n != \"\") {\n cal[[n]] = args[[n]]\n }\n }\n\n # allow first argument in tinyplot_add() to be unnamed\n if (isTRUE(names(args)[1] == \"\")) {\n cal[[2]] = args[[1]]\n }\n\n cal[[\"add\"]] = TRUE\n eval(cal)\n}\n\n\n\n#' @export\n#' @name plt_add\n#' @rdname tinyplot_add\nplt_add = tinyplot_add\n"], ["/tinyplot/R/tinyAxis.R", "#' @title Generic function for adding an axis to a (tiny)plot\n#' \n#' @description Internal function used for adding an axis to a [`tinyplot`]\n#' call.\n#' @details `tinyAxis` provides a thin(ish) wrapper around\n#' \\code{\\link[graphics]{Axis}}, but with enhanced flexibility to (i) match\n#' parameter combinations based on the axis type and plotting theme, (ii)\n#' provide better support for date-time variables, and (iii) enable convenient\n#' formatting of axis tick labels.\n#' @inheritParams graphics::Axis\n#' @param type the type of axis to be drawn; inherited from the `xaxt` or `yaxt`\n#' arguments of the parent [`tinyplot()`] call. One of either: `\"standard\"`\n#' (default that draws the axis, ticks, and labels), `\"none\"` (no axes),\n#' `\"ticks\"` (only ticks and labels without axis line), `\"labels\"` (only\n#' labels without ticks and axis line), or `\"axis\"` (only axis line and labels\n#' but no ticks). Partial matching is allowed, e.g. `type = \"s\"`.\n#' @inheritParams tinylabel\n#' @examples\n#' \\dontrun{\n#' \n#' # plot without axes\n#' tinyplot(0:10, axes = \"n\")\n#' # add x-axis (labels only)\n#' tinyplot:::tinyAxis(x = 0:10, side = 1, type = \"l\")\n#' # add y-axis (with custom label formatting)\n#' tinyplot:::tinyAxis(x = 0:10, side = 2, type = \"s\", labeller = \"$\")\n#' }\n#' @keywords internal\ntinyAxis = function(x = NULL, ..., type = \"standard\", labeller = NULL) {\n type = match.arg(type, c(\"standard\", \"none\", \"labels\", \"ticks\", \"axis\"))\n if (type == \"none\") {\n invisible(numeric(0L))\n } else {\n args = list(x = x, ...)\n if (type == \"labels\") {\n args$tick = FALSE\n } else if (type == \"ticks\") {\n args$lwd = 0\n if (!(\"lwd.ticks\" %in% names(args))) args$lwd.ticks = 1\n } else if (type == \"axis\") {\n args$lwd.ticks = 0\n } else {\n args$tick = TRUE\n }\n if (!is.null(labeller)) {\n if (!is.null(args$at)) {\n args$labels = if (!is.null(args$labels)) tinylabel(args$labels, labeller) else tinylabel(args$at, labeller)\n } else {\n args$at = if (!inherits(x, c(\"POSIXt\", \"Date\"))) axTicks(args$side) else axTicksDateTime(args$side, x = x) \n args$labels = tinylabel(args$at, labeller)\n }\n }\n do.call(\"Axis\", args)\n }\n}\n\n# Special case for Date-Time, adapted/simplified from axis.date()\naxTicksDateTime = function(side, x, ...) {\n if (inherits(x, \"POSIXt\")) {\n tz = attr(x, \"tz\")\n range = extendrange(x)\n rangeDateTime = .POSIXct(range, tz = tz)\n } else {\n range = sort(par(\"usr\")[if (side%%2) 1L:2L else 3:4L])\n range[1L] = ceiling(range[1L])\n range[2L] = floor(range[2L])\n rangeDateTime = range\n class(rangeDateTime) = \"Date\"\n }\n z = pretty(rangeDateTime, n = par(\"lab\")[2 - side%%2])\n keep = z >= range[1L] & z <= range[2L]\n z = z[keep]\n return(z)\n}\n"], ["/tinyplot/R/type_hline.R", "#' @rdname type_abline\n#' @param h y-value(s) for horizontal line(s). Numeric of length 1, or equal to\n#' the number of groups or number of facets (or the product thereof).\n#' @export\ntype_hline = function(h = 0) {\n assert_numeric(h)\n data_hline = function(datapoints, lwd, lty, col, ...) {\n if (nrow(datapoints) == 0) {\n msg = \"`type_hline() only works on existing plots with x and y data points.\"\n stop(msg, call. = FALSE)\n }\n # keep track of unique lty and lwd (needed for group catch / escape hatch\n # later in draw_hline)\n ul_lwd = length(unique(lwd))\n ul_lty = length(unique(lty))\n ul_col = length(unique(col))\n return(list(type_info = list(ul_lty = ul_lty, ul_lwd = ul_lwd, ul_col = ul_col)))\n }\n draw_hline = function() {\n fun = function(\n ifacet, iby, data_facet, icol, ilty, ilwd,\n ngrps, nfacets, by_continuous, facet_by,\n type_info,\n ...\n ) {\n \n # flag for aesthetics by groups\n grp_aes = type_info[[\"ul_col\"]] == 1 || type_info[[\"ul_lty\"]] == ngrps || type_info[[\"ul_lwd\"]] == ngrps\n \n if (length(h) != 1) {\n if (!length(h) %in% c(ngrps, nfacets, ngrps*nfacets)) {\n msg = \"Length of 'h' must be 1, or equal to the number of facets or number of groups (or product thereof).\"\n stop(msg, call. = FALSE)\n }\n if (!facet_by && length(h) == nfacets) {\n h = h[ifacet]\n if (!grp_aes && type_info[[\"ul_col\"]]!=ngrps) {\n icol = 1\n } else if (by_continuous) {\n icol = 1\n }\n } else if (!by_continuous && length(h) == ngrps * nfacets) {\n h = h[ifacet * ngrps - c(ngrps - iby)]\n } else if (!by_continuous) {\n h = h[iby]\n }\n } else if (!grp_aes) {\n icol = 1\n }\n\n abline(h = h, col = icol, lty = ilty, lwd = ilwd)\n }\n return(fun)\n }\n out = list(\n draw = draw_hline(),\n data = data_hline,\n name = \"hline\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_spineplot.R", "#' Spineplot and spinogram types\n#'\n#' @description Type function(s) for producing spineplots and spinograms, which\n#' are modified versions of histograms or mosaic plots, and particularly\n#' useful for visualizing factor variables. Note that [`tinyplot`] defaults\n#' to `type_spineplot()` if `y` is a factor variable.\n#' @param xlevels,ylevels a character or numeric vector specifying the ordering of the\n#' levels of the `x` and `y` variables (if character) or the corresponding indexes\n#' (if numeric) for the plot.\n#' @inheritParams graphics::spineplot\n#' @examples\n#' # \"spineplot\" type convenience string\n#' tinyplot(Species ~ Sepal.Width, data = iris, type = \"spineplot\")\n#' \n#' # Aside: specifying the type is redundant for this example, since tinyplot()\n#' # defaults to \"spineplot\" if y is a factor (just like base plot).\n#' tinyplot(Species ~ Sepal.Width, data = iris)\n#' \n#' # Use `type_spineplot()` to pass extra arguments for customization\n#' tinyplot(Species ~ Sepal.Width, data = iris, type = type_spineplot(breaks = 4))\n#' \n#' p = palette.colors(3, \"Pastel 1\")\n#' tinyplot(Species ~ Sepal.Width, data = iris, type = type_spineplot(breaks = 4, col = p))\n#' rm(p)\n#' \n#' # More idiomatic tinyplot way of drawing the previous plot: use y == by\n#' tinyplot(\n#' Species ~ Sepal.Width | Species, data = iris, type = type_spineplot(breaks = 4),\n#' palette = \"Pastel 1\", legend = FALSE\n#' )\n#' \n#' # Grouped and faceted spineplots\n#' \n#' ttnc = as.data.frame(Titanic)\n#' \n#' tinyplot(\n#' Survived ~ Sex, facet = ~ Class, data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq)\n#' )\n#' \n#' # For grouped \"by\" spineplots, it's better visually to facet as well\n#' tinyplot(\n#' Survived ~ Sex | Class, facet = \"by\", data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq)\n#' )\n#' \n#' # Fancier version. Note the smart inheritance of spacing etc.\n#' tinyplot(\n#' Survived ~ Sex | Class, facet = \"by\", data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq),\n#' palette = \"Dark 2\", facet.args = list(nrow = 1), axes = \"t\"\n#' )\n#'\n#' # Reorder x and y variable categories either by their character levels or numeric indexes\n#' tinyplot(\n#' Survived ~ Sex, facet = ~ Class, data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq, xlevels = c(\"Female\", \"Male\"), ylevels = 2:1)\n#' )\n#'\n#' # Note: It's possible to use \"by\" on its own (without faceting), but the\n#' # overlaid result isn't great. We will likely overhaul this behaviour in a\n#' # future version of tinyplot...\n#' tinyplot(Survived ~ Sex | Class, data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq), alpha = 0.3\n#' )\n#' \n#' @export\ntype_spineplot = function(breaks = NULL, tol.ylab = 0.05, off = NULL, xlevels = NULL, ylevels = NULL, col = NULL, xaxlabels = NULL, yaxlabels = NULL, weights = NULL) {\n col = col\n out = list(\n data = data_spineplot(off = off, breaks = breaks, xlevels = xlevels, ylevels = ylevels, xaxlabels = xaxlabels, yaxlabels = yaxlabels, weights = weights),\n draw = draw_spineplot(tol.ylab = tol.ylab, off = off, col = col, xaxlabels = xaxlabels, yaxlabels = yaxlabels),\n name = \"spineplot\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n#' @importFrom grDevices nclass.Sturges\ndata_spineplot = function(off = NULL, breaks = NULL, xlevels = xlevels, ylevels = ylevels, xaxlabels = NULL, yaxlabels = NULL, weights = NULL) {\n fun = function(\n datapoints,\n by = NULL, col = NULL, bg = NULL, palette = NULL,\n facet = NULL, facet.args = NULL,\n xlim = NULL, ylim = NULL,\n axes = TRUE, xaxt = NULL, yaxt = NULL, xaxb = NULL, yaxb = NULL,\n null_by, null_facet, \n ...\n ) {\n \n ## process weights\n if (!is.null(weights)) {\n ny = length(datapoints$y)\n if (length(weights) != ny && length(weights) != 1L) {\n stop(sprintf(\"'weights' must have either length 1 or %s\", ny))\n }\n }\n datapoints$weights = weights\n \n ## process x variable\n if (is.factor(datapoints$x)) {\n breaks = NULL\n off = if(is.null(off)) 0.02 else off/100\n if (is.null(xlim)) xlim = c(0, 1 + (nlevels(datapoints$x) - 1L) * off)\n } else {\n off = 0\n if (is.null(xlim)) xlim = c(0, 1)\n \t x = as.numeric(datapoints$x)\n if (is.null(breaks)) {\n breaks = if (!is.null(xaxb)) xaxb else if (is.null(weights)) nclass.Sturges(x) else ceiling(log2(sum(weights)) + 1)\n\t }\n breaks = as.numeric(breaks)\n if (length(breaks) == 1L) {\n if (!is.numeric(breaks) || !is.finite(breaks) || breaks < 1L) stop(\"invalid number of 'breaks'\")\n if (breaks > 1e6) {\n warning(gettextf(\"'breaks = %g' is too large and set to 1e6\", breaks))\n breaks = 1000000L\n }\n rg = if (is.null(weights)) range(x, na.rm = TRUE) else range(x[weights > 0], na.rm = TRUE)\n breaks = pretty(rg, n = breaks, min.n = 1L) \n }\n }\n\n ## process y variable\n if (!is.factor(datapoints$y)) datapoints$y = factor(datapoints$y)\n if (is.null(ylim)) ylim = c(0, 1)\n\n ## adjust facet margins\n if (!is.null(facet) && is.null(facet.args[[\"fmar\"]])) {\n facet.args[[\"fmar\"]] = c(2, 2, 2, 2)\n }\n \n x_by = identical(datapoints$x, datapoints$by)\n y_by = identical(datapoints$y, datapoints$by)\n \n x.categorical = is.factor(datapoints$x)\n if (!is.null(xlevels) && x.categorical) {\n xlevels = if(is.numeric(xlevels)) levels(datapoints$x)[xlevels] else xlevels\n if (any(is.na(xlevels)) || !all(xlevels %in% levels(datapoints$x))) warning(\"not all 'xlevels' correspond to levels of 'x'\")\n datapoints$x = factor(datapoints$x, levels = xlevels)\n if (x_by) datapoints$by = datapoints$x\n }\n if (!is.null(ylevels)) {\n ylevels = if(is.numeric(ylevels)) levels(datapoints$y)[ylevels] else ylevels\n if (any(is.na(ylevels)) || !all(ylevels %in% levels(datapoints$y))) warning(\"not all 'ylevels' correspond to levels of 'y'\")\n datapoints$y = factor(datapoints$y, levels = ylevels)\n if (y_by) datapoints$by = datapoints$y\n }\n \n x = datapoints$x\n y = datapoints$y\n \n # if either x_by or y_by are TRUE, we'll only split by facets and then\n # use some simple logic to assign colouring on the backend\n if (isTRUE(x_by) || isTRUE(y_by)) {\n datapoints = split(datapoints, list(datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n } else {\n datapoints = split(datapoints, list(datapoints$by, datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n }\n \n # construct spineplot rectangles and breaks points for each by-facet combo\n datapoints = Map(function(dat, x.categorical, off) {\n ## set up frequency table\n x = dat$x\n if(!x.categorical) {\n x = cut(as.numeric(x), breaks = breaks, include.lowest = TRUE)\n }\n ## TODO: process by grouping via: interaction + spacing + labeling\n ## (for now just do interaction)\n ## FIXME: data_facet only contains the first by group?\n ## if (any(dat$by != \"\")) x = interaction(dat$by, x)\n if(is.null(dat$weights)) {\n tab = table(x, dat$y)\n } else {\n tab = as.table(tapply(dat$weights, list(x, dat$y), FUN = sum, na.rm = TRUE))\n tab[is.na(tab)] = 0\n }\n nx = nrow(tab)\n ny = ncol(tab)\n \n ## compute coordinates\n ## cumulative proportions of x (plus off) vs. conditional cumulative proportions of y\n yat = rbind(0, apply(proportions(tab[, ny:1L, drop = FALSE], 1L), 1L, cumsum))\n yat[is.na(yat)] = 1\n xat = c(0, cumsum(proportions(marginSums(tab, 1L)) + off))\n \n ybottom = as.vector(yat[-(ny + 1L),])\n ytop = as.vector(yat[-1L,])\n xleft = rep(xat[1L:nx], rep(ny, nx))\n xright = rep(xat[2L:(nx+1L)] - off, rep(ny, nx))\n \n out = data.frame(\n by = dat$by[1], # already split\n facet = dat$facet[1], # already split\n ymin = ybottom,\n ymax = ytop,\n xmin = xleft,\n xmax = xright\n )\n \n attr(out, \"nx\") = nx\n attr(out, \"ny\") = ny\n attr(out, \"xat\") = xat\n attr(out, \"yat\") = yat\n return(out)\n }, \n dat = datapoints,\n x.categorical = x.categorical,\n off = off\n )\n \n nx = attr(datapoints[[1]], \"nx\") ## should be the same for all by/facet groups\n ny = attr(datapoints[[1]], \"ny\") ## ditto\n xat = lapply(datapoints, attr, \"xat\")\n yat = lapply(datapoints, attr, \"yat\")\n datapoints = do.call(rbind, datapoints)\n \n if (is.null(yaxlabels)) yaxlabels = rev(levels(y))\n \n ## axis labels\n yaxlabels = if(is.null(yaxlabels)) levels(y) else rep_len(yaxlabels, ny)\n if (!is.null(yaxb)) {\n # yaxlabels = yaxlabels[yaxlabels %in% yaxb]\n ## rather use the \"\" assignment workaround below, since otherwise we \n ## get a mismatch between the label names and ticks \n yaxlabels[!(yaxlabels %in% yaxb)] = \"\"\n }\n if(x.categorical) {\n xaxlabels = if(is.null(xaxlabels)) {\n levels(x)\n } else {\n rep_len(xaxlabels, nx)\n }\n } else {\n xaxlabels = if(is.null(xaxlabels)) {\n if(is.numeric(x)) breaks else c(x[1L], x[c(diff(as.numeric(x)) > 0, TRUE)])\n } else {\n rep_len(xaxlabels, nx + 1L)\n }\n }\n \n # catch for x_by / y/by\n if (isTRUE(x_by)) datapoints$by = factor(rep(xaxlabels, each = ny)) # each x label extends over ny rows\n if (isTRUE(y_by)) datapoints$by = factor(rep(yaxlabels, length.out = nrow(datapoints)))\n \n ## grayscale flag\n grayscale = null_by && is.null(palette) && is.null(.tpar[[\"palette.qualitative\"]])\n \n out = list(\n x = c(datapoints$xmin, datapoints$xmax), \n y = c(datapoints$ymin, datapoints$ymax),\n ymin = datapoints$ymin, \n ymax = datapoints$ymax, \n xmin = datapoints$xmin, \n xmax = datapoints$xmax, \n col = col,\n bg = bg,\n datapoints = datapoints,\n by = if (null_by) by else datapoints$by, \n facet = if (null_facet) facet else datapoints$facet,\n axes = FALSE,\n frame.plot = FALSE,\n xaxt = \"n\",\n yaxt = \"n\",\n xaxs = \"i\",\n yaxs = \"i\",\n ylabs = yaxlabels,\n type_info = list(\n off = off,\n x.categorical = x.categorical,\n nx = nx,\n ny = ny,\n xat = xat,\n yat = yat,\n xaxlabels = xaxlabels,\n yaxlabels = yaxlabels,\n breaks = breaks,\n axes = axes,\n xaxt = xaxt, \n yaxt = yaxt,\n grayscale = grayscale,\n x_by = x_by,\n y_by = y_by\n ),\n facet.args = facet.args\n )\n \n return(out)\n \n }\n return(fun)\n}\n\n#' @importFrom grDevices gray.colors\ndraw_spineplot = function(tol.ylab = 0.05, off = NULL, col = NULL, xaxlabels = NULL, yaxlabels = NULL) {\n fun = function(ixmin, iymin, ixmax, iymax, ilty, ilwd, icol, ibg, \n flip,\n facet_window_args,\n type_info,\n ifacet,\n ...) {\n \n if (is.null(off)) off = type_info[[\"off\"]]\n if (is.null(xaxlabels)) xaxlabels = type_info[[\"xaxlabels\"]]\n if (is.null(yaxlabels)) yaxlabels = type_info[[\"yaxlabels\"]]\n xat = type_info[[\"xat\"]][[ifacet]]\n yat = type_info[[\"yat\"]][[ifacet]]\n nx = type_info[[\"nx\"]]\n ny = type_info[[\"ny\"]]\n x.categorical = type_info[[\"x.categorical\"]]\n grayscale = type_info[[\"grayscale\"]]\n x_by = type_info[[\"x_by\"]]\n y_by = type_info[[\"y_by\"]]\n \n ## graphical parameters\n if (is.null(col)) {\n if (is.null(ibg)) ibg = icol\n if (isFALSE(y_by)) {\n ibg = if (isTRUE(grayscale)) gray.colors(ny) else seq_palette(ibg, ny)\n }\n ibg = rep_len(ibg, ny)\n } else {\n ibg = col\n }\n \n if (type_info[[\"xaxt\"]] %in% c(\"l\", \"t\", \"n\") &&\n type_info[[\"yaxt\"]] %in% c(\"l\", \"t\", \"n\") &&\n !all(c(type_info[[\"xaxt\"]], type_info[[\"yaxt\"]]) == \"n\")) ilwd = 0\n \n rect(\n xleft = ixmin, ybottom = iymin, xright = ixmax, ytop = iymax,\n lty = ilty,\n lwd = ilwd,\n border = par(\"fg\"), #icol,\n col = ibg\n )\n \n ## axes\n ## - standard categorical axes (xaxt/yaxt == \"s\") _without_ ticks\n ## - never draw additional axis lines, box always for spinogram\n if(type_info[[\"axes\"]]) {\n if (x.categorical) {\n spine_axis(if (flip) 2 else 1, at = (xat[1L:nx] + xat[2L:(nx+1L)] - off)/2, labels = xaxlabels,\n type = type_info[[\"xaxt\"]], categorical = TRUE)\n } else {\n spine_axis(if (flip) 2 else 1, at = xat, labels = xaxlabels,\n type = type_info[[\"xaxt\"]], categorical = FALSE)\n }\n yat = yat[, if(flip) ncol(yat) else 1L]\n equidist = any(diff(yat) < tol.ylab)\n yat = if(equidist) seq.int(1/(2*ny), 1-1/(2*ny), by = 1/ny) else (yat[-1L] + yat[-length(yat)])/2\n spine_axis(if (flip) 3 else 2, at = yat, labels = yaxlabels,\n type = type_info[[\"yaxt\"]], categorical = TRUE)\n if (is_facet_position(if(flip) \"bottom\" else \"right\", ifacet, facet_window_args)) spine_axis(if (flip) 1 else 4,\n type = type_info[[\"yaxt\"]], categorical = FALSE)\n }\n if(!x.categorical && (is.null(ilwd) || ilwd > 0)) box()\n \n }\n return(fun)\n}\n\n\n\n\nspine_axis = function(side, ..., type = \"standard\", categorical = TRUE) {\n type = match.arg(type, c(\"standard\", \"none\", \"labels\", \"ticks\", \"axis\"))\n ## standard: with axis, ticks (unless categorical), and labels\n ## none: no axes\n ## labels: only labels without ticks and axis line\n ## ticks: only ticks and labels without axis line\n ## axis: only axis line and labels but no ticks\n\n if (type == \"none\") {\n invisible(numeric(0L))\n } else {\n args = list(side = side, ...)\n if (type == \"labels\") {\n args$tick = FALSE\n } else if (type == \"ticks\") {\n args$lwd = 0\n if (!(\"lwd.ticks\" %in% names(args))) args$lwd.ticks = if (categorical) 0 else 1\n } else if (type == \"axis\") {\n if (categorical) {\n args$tick = FALSE\n } else {\n args$lwd.ticks = 0\n }\n } else {\n args$tick = !categorical\n }\n do.call(\"axis\", args)\n }\n}\n\n#' @importFrom grDevices col2rgb convertColor hcl\nto_hcl = function(x) {\n x = t(col2rgb(x, alpha = TRUE)/255)\n alpha = x[, 4]\n x = x[, 1:3]\n x = convertColor(x, from = \"sRGB\", to = \"Luv\")\n x = cbind(H = atan2(x[, 3L], x[, 2L]) * 180/pi, C = sqrt(x[, 2L]^2 + x[, 3L]^2), L = x[, 1L])\n x[is.na(x[, 1L]), 1L] = 0\n x[x[, 1L] < 0, 1L] = x[x[, 1L] < 0, 1L] + 360\n attr(x, \"alpha\") = alpha\n return(x)\n}\n\nseq_palette = function(x, n, power = 1.5) {\n x = drop(to_hcl(x[1L]))\n alpha = attr(x, \"alpha\")\n hcl(\n h = x[1L],\n c = seq.int(from = x[2L]^(1/power), to = 0, length.out = n + 1)[1L:n]^power,\n l = 100 - seq.int(from = (100 - x[3L])^(1/power), to = pmin(8, (100 - x[3L])/2)^(1/power), length.out = n)^power,\n alpha = alpha\n )[1L:n]\n}\n"], ["/tinyplot/R/tinylabel.R", "#' Format labels\n#' \n#' @description Function for formatting label appearance, e.g. axis\n#' ticks labels. This is what the top-level `xaxl` and `yaxl` arguments\n#' from [`tinyplot`] ultimately get passed to.\n#' @param x a numeric or character vector\n#' @param labeller a formatting function to be applied to `x`, e.g. [`format`],\n#' [`toupper`], [`abs`], or other custom function (including from the popular\n#' **scales** package). Can also be one of the following convenience strings\n#' (symbols), for which common formatting transformations are provided:\n#' `\"percent\"` (`\"%\"`), `\"comma\"` (`\",\"`), `\"log\"` (`\"l\"`), `\"dollar\"`\n#' (`\"$\"`), `\"euro\"` (`\"€\"`), or `\"sterling\"` (`\"£\"`).\n#' @examples\n#' x = 1e4\n#' tinylabel(x, \"comma\")\n#' tinylabel(x, \",\") # same\n#' tinylabel(x, \"$\") # or \"dollar\"\n#' \n#' # pass to xaxl/yaxl for adjusting axes tick labels in a tinyplot call\n#' tinyplot(I(mpg/hp) ~ hp, data = mtcars, yaxl = \"%\")\n#' \n#' # log example (combined with axis scaling)\n#' tinyplot(x = 10^c(10:0), y = 0:10, type = \"b\", log = \"x\", xaxl = \"log\")\n#' \n#' # combine with `x/yaxb` to adjust the actual tick marks (\"break points\")\n#' # at the same time\n#' tinyplot(x = 10^c(10:0), y = 0:10, type = \"b\", log = \"x\", xaxl = \"log\",\n#' xaxb = 10^c(1,3,5,7,9))\n#' \n#' #\n#' ## custom function examples\n#' \n#' ## example I: date formatting\n#' \n#' dat = data.frame(\n#' date = seq(as.Date(\"2000/1/1\"), by = \"month\", length.out = 12),\n#' trend = 1:12 + rnorm(12, sd = 1)\n#' )\n#' \n#' tinyplot(trend ~ date, data = dat, xaxl = function(x) format(x, \"%b, %Y\"))\n#' \n#' ## example II: string wrapping \n#' \n#' # create a \"vectorised\" version of `base::strwrap` that breaks long\n#' # strings into new lines every 18 characters\n#' strwrap18 = function(x) sapply(\n#' strwrap(x, width = 18, simplify = FALSE),\n#' paste,\n#' collapse = \"\\n\"\n#' )\n#' \n#' # now demonstrate on a dataset with long y-tick labels\n#' dat2 = data.frame(\n#' x = rep(rnorm(100), 3),\n#' y = c(\n#' \"tinyplot is a lightweight extension of the base R graphics system.\",\n#' \"R is a language for statistical computing.\",\n#' \"Data visualization is an essential skill.\"\n#' )\n#' )\n#' \n#' tinytheme(\"bw\")\n#' tinyplot(y ~ x, data = dat2, type = \"j\", yaxl = strwrap18)\n#' tinytheme()\n#' @export\ntinylabel = function(x, labeller = NULL) {\n if (is.null(labeller)) return(x)\n if (is.character(labeller)) labeller = labeller_fun((labeller))\n return(labeller(x))\n}\n\n\nlabeller_fun = function(label = \"percent\") {\n \n labels = c(\n \"%\" = \"percent\",\n \",\" = \"comma\",\n \"$\" = \"dollar\",\n \"\\u20ac\" = \"euro\",\n \"\\u00a3\" = \"sterling\",\n \"l\" = \"log\"\n )\n if (label %in% names(labels)) label = labels[label]\n \n ## all labels plus absolute value version\n # labels = c(\"percent\", \"comma\", \"dollar\", \"euro\", \"sterling\")\n labels = c(labels, paste0(\"abs_\", labels))\n\n ## match full label first, then store abs_ info separately\n label = match.arg(label, labels)\n abs_ = substr(label, 1L, 4L) == \"abs_\"\n if (abs_) label = substr(label, 5L, nchar(label))\n\n ## actual formatting function\n format_percent = function(x) {\n sprintf(\"%.0f%%\", x * 100)\n }\n \n format_comma = function(x) {\n prettyNum(x, big.mark = \",\", scientific = FALSE)\n }\n \n format_dollar = function(x) {\n paste0(\"$\", prettyNum(x, big.mark = \",\", scientific = FALSE))\n }\n \n format_euro = function(x) {\n paste0(\"\\u20ac\", prettyNum(x, big.mark = \",\", scientific = FALSE))\n }\n \n format_sterling = function(x) {\n paste0(\"\\u00a3\", prettyNum(x, big.mark = \",\", scientific = FALSE))\n }\n \n format_log = function(x) {\n parse(text = paste0(10, \"^\", format(log10(x), digits = 3)))\n }\n \n fun = switch(\n label,\n percent = format_percent,\n comma = format_comma,\n dollar = format_dollar,\n euro = format_euro,\n sterling = format_sterling,\n log = format_log\n )\n\n ## combine with absolute value if necessary\n if (abs_) function(x) fun(abs(x)) else fun\n}\n"], ["/tinyplot/R/assertions.R", "check_dependency = function(library_name) {\n flag = requireNamespace(library_name, quietly = TRUE)\n if (isFALSE(flag)) {\n msg = sprintf(\"Please install the `%s` package.\", library_name)\n return(msg)\n } else {\n return(TRUE)\n }\n}\n\nassert_dependency = function(library_name) {\n flag = check_dependency(library_name)\n if (!isTRUE(flag)) stop(flag, call. = FALSE)\n return(invisible())\n}\n\nassert_choice = function(x, choice, null.ok = FALSE, name = as.character(substitute(x))) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(TRUE)\n }\n if (is.character(x) && length(x) == 1 && x %in% choice) {\n return(TRUE)\n }\n msg = sprintf(\n \"`%s` must be one of: %s\",\n name,\n paste(choice, collapse = \", \")\n )\n stop(msg, call. = FALSE)\n}\n\ncheck_true = function(x, null.ok = FALSE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(invisible(TRUE))\n }\n if (isTRUE(x)) {\n return(invisible(TRUE))\n }\n return(FALSE)\n}\n\nassert_true = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be true.\", name)\n if (!isTRUE(check_true(x, null.ok = null.ok))) {\n stop(msg, call. = FALSE)\n }\n}\n\ncheck_string = function(x, null.ok = FALSE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(invisible(TRUE))\n }\n if (is.character(x) && length(x) == 1) {\n return(invisible(TRUE))\n }\n return(FALSE)\n}\n\nassert_string = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be a string.\", name)\n if (!isTRUE(check_string(x, null.ok = null.ok))) {\n stop(msg, call. = FALSE)\n }\n}\n\ncheck_flag = function(x, null.ok = FALSE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(TRUE)\n }\n if (is.logical(x) && length(x) == 1) {\n return(TRUE)\n }\n return(FALSE)\n}\n\nassert_flag = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be a logical flag.\", name)\n if (!isTRUE(check_flag(x, null.ok = null.ok))) {\n stop(msg, call. = FALSE)\n }\n}\n\nassert_length = function(x, len = 1, null.ok = FALSE, name = as.character(substitute(x))) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(invisible(TRUE))\n }\n msg = sprintf(\"`%s` must be one of these lengths: %s\", name, paste(len, collapse = \", \"))\n if (!length(x) %in% len) {\n stop(msg, call. = FALSE)\n }\n}\n\nassert_logical = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(invisible(TRUE))\n }\n msg = sprintf(\"`%s` must be a logical vector\", name)\n if (!is.logical(x)) stop(msg, call. = FALSE)\n}\n\n\ncheck_integerish = function(x, len = NULL, lower = NULL, upper = NULL, null.ok = TRUE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(TRUE)\n }\n if (!is.numeric(x)) {\n return(FALSE)\n }\n x = stats::na.omit(x)\n if (!is.null(len) && length(x) != len) {\n return(FALSE)\n }\n if (!is.null(lower) && any(x < lower)) {\n return(FALSE)\n }\n if (!is.null(upper) && any(x > upper)) {\n return(FALSE)\n }\n if (isTRUE(any(abs(x - round(x)) > (.Machine$double.eps)^0.5))) {\n return(FALSE)\n }\n return(TRUE)\n}\n\nassert_integerish = function(x, len = NULL, lower = NULL, upper = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(invisible())\n }\n msg = sprintf(\"`%s` must be integer-ish\", name)\n if (is.null(x) && !isTRUE(null.ok)) stop(sprintf(\"%s should not be NULL.\", name), call. = FALSE)\n if (!isTRUE(check_integerish(x, len = len, lower = lower, upper = upper, null.ok = null.ok))) {\n if (!is.numeric(x)) msg = paste0(msg, \"; it is not numeric\")\n if (!is.null(len) && length(x) != len) msg = paste0(msg, sprintf(\"; its length must be %s\", len))\n if (!is.null(lower) && any(x < lower)) msg = paste0(msg, sprintf(\"; all values must be greater than or equal to %s\", lower))\n if (!is.null(upper) && any(x > upper)) msg = paste0(msg, sprintf(\"; all values must be less than or equal to %s\", upper))\n if (isTRUE(any(abs(x - round(x)) > (.Machine$double.eps)^0.5))) msg = paste0(msg, \"; all values must be close to integers\")\n stop(msg, call. = FALSE)\n }\n}\n\ncheck_numeric = function(x, len = NULL, lower = NULL, upper = NULL, null.ok = TRUE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(TRUE)\n }\n if (!is.numeric(x)) {\n return(FALSE)\n }\n if (!is.null(len) && length(x) != len) {\n return(FALSE)\n }\n if (!is.null(lower) && any(x < lower)) {\n return(FALSE)\n }\n if (!is.null(upper) && any(x > upper)) {\n return(FALSE)\n }\n return(TRUE)\n}\n\nassert_numeric = function(x, len = NULL, lower = NULL, upper = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be numeric\", name)\n if (!isTRUE(check_numeric(x, len = len, lower = lower, upper = upper, null.ok = null.ok))) {\n if (!is.null(len) && length(x) != len) msg = paste0(msg, sprintf(\"; its length must be %s\", len))\n if (!is.null(lower) && any(x < lower)) msg = paste0(msg, sprintf(\"; all values must be greater than or equal to %s\", lower))\n if (!is.null(upper) && any(x > upper)) msg = paste0(msg, sprintf(\"; all values must be less than or equal to %s\", upper))\n stop(msg, call. = FALSE)\n }\n}\n\nassert_data_frame = function(x, min_rows = 0, min_cols = 0, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be a data.frame.\", name)\n if (!is.data.frame(x)) stop(msg, call. = FALSE)\n msg = sprintf(\"Number of rows in `%s` must be at least `%s`\", name, min_rows)\n if (nrow(x) < min_rows) stop(msg, call. = FALSE)\n msg = sprintf(\"Number of columns in `%s` must be at least `%s`\", name, min_cols)\n if (ncol(x) < min_cols) stop(msg, call. = FALSE)\n}\n\n\ncheck_character = function(x, len = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(TRUE)\n } else if (!is.character(x)) {\n msg = sprintf(\"`%s` must be character.\", name)\n return(msg)\n } else if (!is.null(len) && length(x) != len) {\n msg = sprintf(\"`%s` must have length %s.\", name, len)\n return(msg)\n }\n return(TRUE)\n}\n\nassert_character = function(x, len = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n flag = check_character(x, len = len, null.ok = null.ok, name = name)\n if (!isTRUE(flag)) {\n stop(flag, call. = FALSE)\n } else {\n return(invisible(TRUE))\n }\n}\n\nassert_list = function(x, named = FALSE, len = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(invisible(TRUE))\n }\n if (!is.list(x)) stop(\"Input is not a list.\", call. = FALSE)\n if (isTRUE(named)) {\n if (is.null(names(x))) {\n stop(sprintf(\"`%s` should be named list.\", name), call. = FALSE)\n }\n }\n if (!is.null(len)) {\n if (length(x) != len) {\n stop(sprintf(\"`%s` must be of length %s.\", name, len), call. = FALSE)\n }\n }\n}\n\nassert_function = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(invisible(TRUE))\n }\n if (!is.function(x)) {\n msg = sprintf(\"`%s` must be a function.\", name)\n stop(msg, call. = FALSE)\n }\n}\n\ncheck_atomic_vector = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(invisible(TRUE))\n }\n # doesn't work on glue::glue() output\n # flag = is.atomic(x) && is.vector(x) && !is.list(x)\n flag = is.atomic(x) && is.null(dim(x)) && length(x) > 0 && !is.list(x)\n if (flag) {\n out = TRUE\n } else if (is.factor(x) && is.null(dim(x))) {\n out = TRUE\n } else {\n out = sprintf(\"`%s` must be an atomic vector.\", name)\n }\n return(out)\n}\n\nassert_atomic_vector = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n flag = check_atomic_vector(x, null.ok = null.ok, name = name)\n if (!isTRUE(flag)) {\n stop(flag, call. = FALSE)\n } else {\n return(invisible(TRUE))\n }\n}\n\nassert_class = function(x, classname) {\n if (!inherits(x, classname)) {\n msg = sprintf(\"`x` must be of class `%s`.\", classname)\n stop(msg, call. = FALSE)\n }\n}\n\n"], ["/tinyplot/R/type_histogram.R", "#' Histogram plot type\n#' \n#' @md\n#' @description Type function for histogram plots. `type_hist` is an alias for\n#' `type_histogram`.\n#' @param breaks Passed to \\code{\\link[graphics]{hist}}. One of:\n#' - a vector giving the breakpoints between histogram cells,\n#' - a function to compute the vector of breakpoints,\n#' - a single number giving the number of cells for the histogram,\n#' - a character string naming an algorithm to compute the number of cells (see ‘Details’ of \\code{\\link[graphics]{hist}}),\n#' - a function to compute the number of cells.\n#' In the last three cases the number is a suggestion only; as the breakpoints\n#' will be set to pretty values, the number is limited to 1e6 (with a warning if\n#' it was larger). If breaks is a function, the x vector is supplied to it as\n#' the only argument (and the number of breaks is only limited by the amount of\n#' available memory).\n#' @param free.breaks Logical indicating whether the breakpoints should be\n#' computed separately for each group or facet? Default is `FALSE`, meaning\n#' that the breakpoints are computed from the full dataset; thus ensuring\n#' common bin widths across each group/facet. Can also use `free` as an\n#' acceptable argument alias. Ignored if there are no groups and/or facets.\n#' @param drop.zeros Logical indicating whether bins with zero counts should be\n#' dropped before plotting. Default is `TRUE`. Note that switching to `FALSE`\n#' may interfere with faceted plot behaviour if `facet.args = list(free)`,\n#' since the `x` variable is effectively recorded over the full range of the\n#' x-axis (even if it does not extend over this range for every group).\n#' @inheritParams graphics::hist\n#' @examples\n#' # \"histogram\"/\"hist\" type convenience string(s)\n#' tinyplot(Nile, type = \"histogram\")\n#' \n#' # Use `type_histogram()` to pass extra arguments for customization\n#' tinyplot(Nile, type = type_histogram(breaks = 30))\n#' tinyplot(Nile, type = type_histogram(breaks = 30, freq = FALSE))\n#' # etc.\n#' \n#' # Grouped histogram example\n#' tinyplot(\n#' ~Petal.Width | Species,\n#' type = \"histogram\",\n#' data = iris\n#' )\n#' \n#' # Faceted version\n#' tinyplot(\n#' ~Petal.Width, facet = ~Species,\n#' type = \"histogram\",\n#' data = iris\n#' )\n#' \n#' # For visualizing faceted histograms across varying scales, you may also wish\n#' # to impose free histogram breaks too (i.e., calculate breaks separately for\n#' # each group). Compare:\n#' \n#' # free facet scales + shared histogram breaks, versus...\n#' tinyplot(\n#' ~Petal.Width, facet = ~Species,\n#' facet.args = list(free = TRUE),\n#' type = type_histogram(),\n#' data = iris\n#' )\n#' # ... free facet scales + free histogram breaks\n#' tinyplot(\n#' ~Petal.Width, facet = ~Species,\n#' facet.args = list(free = TRUE),\n#' type = type_histogram(free = TRUE),\n#' data = iris\n#' )\n#' \n#' @export\ntype_histogram = function(breaks = \"Sturges\",\n freq = NULL, right = TRUE,\n free.breaks = FALSE, drop.zeros = TRUE) {\n out = list(\n data = data_histogram(breaks = breaks,\n free.breaks = free.breaks, drop.zeros = drop.zeros,\n freq = freq, right = right),\n draw = draw_rect(),\n name = \"histogram\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n#' @export\n#' @name type_hist\n#' @rdname type_histogram\ntype_hist = type_histogram\n\n\ndata_histogram = function(breaks = \"Sturges\",\n free.breaks = FALSE, drop.zeros = TRUE,\n freq = NULL, right = TRUE) {\n \n hbreaks = breaks\n hfree.breaks = free.breaks\n hdrop.zeros = drop.zeros\n hfreq = freq\n hright = right\n \n fun = function(by, facet, ylab, col, bg, ribbon.alpha, datapoints, .breaks = hbreaks, .freebreaks = hfree.breaks, .freq = hfreq, .right = hright, .drop.zeros = hdrop.zeros, ...) {\n \n hbreaks = ifelse(!sapply(.breaks, is.null), .breaks, \"Sturges\")\n \n if (is.null(by) && is.null(palette)) {\n if (is.null(col)) col = par(\"fg\")\n if (is.null(bg)) bg = \"lightgray\"\n } else {\n if (is.null(bg)) bg = ribbon.alpha\n }\n\n if (!.freebreaks) xbreaks = hist(datapoints$x, breaks = hbreaks, right = .right, plot = FALSE)$breaks\n datapoints = split(datapoints, list(datapoints$by, datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n \n datapoints = lapply(datapoints, function(k) {\n if (.freebreaks) xbreaks = breaks\n h = hist(k$x, breaks = xbreaks, right = .right, plot = FALSE)\n # zero count cases\n if (.drop.zeros) {\n nzidx = which(h$counts > 0)\n h$density = h$density[nzidx]\n h$counts = h$counts[nzidx]\n h$breaks = h$breaks[c(1, nzidx+1)]\n h$mids = h$mids[nzidx]\n }\n freq = if(!is.null(.freq)) .freq else is.null(.freq) && h$equidist\n out = data.frame(\n by = k$by[1], # already split\n facet = k$facet[1], # already split\n ymin = 0,\n ymax = if (freq) h$counts else h$density,\n xmin = h$breaks[-1],\n xmax = h$mids + (h$mids - h$breaks[-1]),\n freq = freq\n )\n return(out)\n })\n datapoints = do.call(rbind, datapoints)\n \n if (is.null(ylab)) {\n ylab = ifelse(datapoints$freq[1], \"Frequency\", \"Density\")\n }\n\n out = list(\n x = c(datapoints$xmin, datapoints$xmax), \n y = c(datapoints$ymin, datapoints$ymax),\n ymin = datapoints$ymin, \n ymax = datapoints$ymax, \n xmin = datapoints$xmin, \n xmax = datapoints$xmax, \n ylab = ylab, \n col = col, \n bg = bg, \n datapoints = datapoints,\n by = if (length(unique(datapoints$by)) == 1) by else datapoints$by, \n facet = if (length(unique(datapoints$facet)) == 1) facet else datapoints$facet\n )\n return(out)\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_text.R", "#' Text annotations plot type\n#'\n#' @description Type function for adding text annotations to a plot. This function allows\n#' you to draw text at specified (x,y) coordinates.\n#'\n#' @param labels Character vector of length 1 or of the same length as the\n#' number of x,y coordinates.\n#' @param font Font to be used, following [graphics::par()].\n#' @param xpd Logical value or `NA` denoting text clipping behaviour, following\n#' [graphics::par()].\n#' @param srt Numeric giving the desired string rotation in degrees.\n#' @inheritParams graphics::text\n#' @examples\n#' tinyplot(mpg ~ hp | factor(cyl),\n#' data = mtcars,\n#' type = type_text(\n#' labels = row.names(mtcars),\n#' font = 2,\n#' adj = 0\n#' )\n#' )\n#' \n#' # to avoid clipping text at the plot region, we can use xpd = NA\n#' tinyplot(mpg ~ hp | factor(cyl),\n#' data = mtcars,\n#' type = type_text(\n#' labels = row.names(mtcars),\n#' font = 2,\n#' adj = 0,\n#' xpd = NA\n#' )\n#' )\n#'\n#' @export\ntype_text = function(labels, adj = NULL, pos = NULL, offset = 0.5, vfont = NULL, font = NULL, xpd = NULL, srt = 0) {\n out = list(\n draw = draw_text(adj = adj, pos = pos, offset = offset, vfont = vfont, font = font, xpd = xpd, srt = srt),\n data = data_text(labels = labels),\n name = \"text\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\ndata_text = function(labels) {\n fun = function(datapoints, ...) {\n if (length(labels) != 1 && length(labels) != nrow(datapoints)) {\n msg <- sprintf(\"`labels` must be of length 1 or %s.\", nrow(datapoints))\n stop(msg, call. = FALSE)\n }\n datapoints$labels = labels\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\ndraw_text = function(adj = NULL, pos = NULL, offset = 0.5, vfont = NULL, font = NULL, xpd = NULL, srt = 0) {\n if (is.null(xpd)) xpd = par(\"xpd\")\n fun = function(ix, iy, ilabels, icol, cex, ...) {\n text(\n x = ix, y = iy, labels = ilabels, col = icol,\n adj = adj, pos = pos, offset = offset,\n vfont = vfont, font = font,\n xpd = xpd,\n srt = srt,\n cex = cex\n )\n }\n}\n"], ["/tinyplot/R/type_violin.R", "#' Violin plot type\n#' \n#' @md\n#' @description Type function for violin plots, which are an alternative to box\n#' plots for visualizing continuous distributions (by group) in the form of\n#' mirrored densities.\n#' @inheritParams type_density\n#' @param trim logical indicating whether the violins should be trimmed to the\n#' range of the data. Default is `FALSE`.\n#' @param width numeric (ideally in the range `[0, 1]`, although this isn't\n#' enforced) giving the normalized width of the individual violins.\n#' @inherit stats::density details\n#' @details See [`type_density`] for more details and considerations related to\n#' bandwidth selection and kernel types.\n#' \n#' @examples\n#' # \"violin\" type convenience string\n#' tinyplot(count ~ spray, data = InsectSprays, type = \"violin\")\n#' \n#' # aside: to match the defaults of `ggplot2::geom_violin()`, use `trim = TRUE`\n#' # and `joint.bw = FALSE`\n#' tinyplot(count ~ spray, data = InsectSprays, type = \"violin\",\n#' trim = TRUE, joint.bw = FALSE)\n#' \n#' # use flip = TRUE to reorient the axes\n#' tinyplot(count ~ spray, data = InsectSprays, type = \"violin\", flip = TRUE)\n#' \n#' # for flipped plots with long group labels, it's better to use a theme for\n#' # dynamic plot resizing\n#' tinytheme(\"clean\")\n#' tinyplot(weight ~ feed, data = chickwts, type = \"violin\", flip = TRUE)\n#' \n#' # you can group by the x var to add colour (here with the original orientation)\n#' tinyplot(weight ~ feed | feed, data = chickwts, type = \"violin\", legend = FALSE)\n#' \n#' # dodged grouped violin plot example (different dataset)\n#' tinyplot(len ~ dose | supp, data = ToothGrowth, type = \"violin\", fill = 0.2)\n#' \n#' # note: above we relied on `...` argument passing alongside the \"violin\"\n#' # type convenience string. But this won't work for `width`, since it will\n#' # clash with the top-level `tinyplot(..., width = )` arg. To ensure\n#' # correct arg passing, it's safer to use the formal `type_violin()` option.\n#' tinyplot(len ~ dose | supp, data = ToothGrowth, fill = 0.2,\n#' type = type_violin(width = 0.8))\n#' \n#' # reset theme\n#' tinytheme()\n#' \n#' @importFrom stats density weighted.mean\n#' @importFrom stats bw.SJ bw.bcv bw.nrd bw.nrd0 bw.ucv \n#' @export\ntype_violin = function(\n bw = \"nrd0\",\n joint.bw = c(\"mean\", \"full\", \"none\"),\n adjust = 1,\n kernel = c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"),\n n = 512,\n # more args from density here?\n trim = FALSE,\n width = 0.9\n ) {\n kernel = match.arg(kernel, c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"))\n if (is.logical(joint.bw)) {\n joint.bw = ifelse(joint.bw, \"mean\", \"none\")\n }\n joint.bw = match.arg(joint.bw, c(\"mean\", \"full\", \"none\"))\n out = list(\n data = data_violin(bw = bw, adjust = adjust, kernel = kernel, n = n,\n joint.bw = joint.bw, trim = trim, width = width),\n # draw = NULL,\n # name = \"polygon\"\n draw = draw_polygon(density = NULL),\n name = \"violin\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\ndata_violin = function(bw = \"nrd0\", adjust = 1, kernel = \"gaussian\", n = 512,\n joint.bw = \"none\", trim = FALSE, width = 0.9) {\n fun = function(datapoints, by, facet, ylab, col, bg, palette, log, null_by, null_facet, ...) {\n \n # Handle ordering based on by and facet variables\n ngrps = if (null_by) 1 else length(unique(datapoints$by))\n nfacets = if (null_facet) 1 else length(unique(datapoints$facet))\n \n # catch for special cases\n x_by = y_by = facet_by = FALSE\n if (!null_by) {\n x_by = identical(datapoints$x, datapoints$by)\n y_by = identical(datapoints$y, datapoints$by)\n if (!null_facet) facet_by = identical(datapoints$facet, datapoints$by)\n }\n \n # FIXME (once we add support for gradient fill to draw_polygon)\n if (y_by) {\n warning(\"\\n`y` == `by` is not currently supported for `type_violin`. We hope to support this in a future release, but for now `y` grouping will be turned off automatically.\\n\")\n by = NULL\n datapoints$by = \"\"\n ngrps = 1\n null_by = TRUE\n }\n \n # Convert x to factor if it's not already\n datapoints$x = as.factor(datapoints$x)\n if (x_by) datapoints$by = datapoints$x\n\n # Handle factor levels and maintain order\n xlvls = levels(datapoints$x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n # xlabs = levels(datapoints$x)\n datapoints$x = as.integer(datapoints$x)\n\n if (null_by && null_facet) {\n xord = order(datapoints$x)\n } else if (null_facet) {\n xord = order(datapoints$by, datapoints$x)\n } else if (null_by) {\n xord = order(datapoints$facet, datapoints$x)\n } else {\n xord = order(datapoints$by, datapoints$facet, datapoints$x)\n }\n\n if (length(unique(datapoints[[\"by\"]])) == 1 && is.null(palette)) {\n if (is.null(col)) col = par(\"fg\")\n if (is.null(bg)) bg = \"lightgray\"\n } else if (is.null(bg)) {\n bg = \"by\"\n }\n\n # Reorder x, y, ymin, and ymax based on the order determined\n datapoints = datapoints[xord,]\n\n \n datapoints = split(datapoints, list(datapoints$x, datapoints$by, datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n \n if (joint.bw == \"none\" || is.numeric(bw)) {\n dens_bw = bw\n } else {\n if (joint.bw == \"mean\") {\n # Use weighted mean of subgroup bandwidths\n bws = sapply(datapoints, function(dat) bw_fun(kernel = bw, dat$y))\n ws = sapply(datapoints, nrow)\n dens_bw = weighted.mean(bws, ws)\n } else if (joint.bw == \"full\") {\n dens_bw = bw_fun(kernel = bw, unlist(sapply(datapoints, `[[`, \"x\")))\n }\n }\n \n datapoints = lapply(seq_along(datapoints), function(d) {\n dat = datapoints[[d]]\n if (trim) {\n yrng = range(dat$y)\n dens = density(dat$y, bw = dens_bw, kernel = kernel, n = n, from = yrng[1], to = yrng[2])\n } else {\n dens = density(dat$y, bw = dens_bw, kernel = kernel, n = n)\n }\n \n x = dens$y\n y = dens$x\n \n \n if (log %in% c(\"y\", \"xy\")) {\n if (x[1] <= 0) {\n warning(\"\\nNon-positive density values have been trimmed as part of the logarthmic transformation.\\n\")\n xidx = x > 0\n x = x[xidx]\n y = y[xidx]\n } \n }\n \n x = c(x, rev(-x))\n y = c(y, rev(y))\n \n xwidth = xwidth_orig = width\n # dodge groups (if any)\n if ((ngrps > 1) && isFALSE(x_by) && isFALSE(facet_by)) {\n xwidth = xwidth_orig / ngrps - 0.01\n x = rescale_num(x, to = c(0, xwidth))\n x = x + as.numeric(sub(\"^([0-9]+)\\\\..*\", \"\\\\1\", names(datapoints)[d])) - xwidth/2\n x = x + seq(-((xwidth_orig - xwidth) / 2), ((xwidth_orig - xwidth) / 2), length.out = ngrps)[dat$by[1]]\n } else if (nfacets > 1) {\n x = rescale_num(x, to = c(0, xwidth))\n x = x + as.numeric(sub(\"^([0-9]+)\\\\..*\", \"\\\\1\", names(datapoints)[d])) - xwidth/2\n } else {\n x = rescale_num(x, to = c(0, xwidth))\n x = x + d - xwidth/2\n }\n \n x = c(x, NA)\n y = c(y, NA)\n \n out = data.frame(\n by = dat$by[1], # already split\n facet = dat$facet[1], # already split\n y = y,\n x = x\n )\n return(out)\n })\n datapoints = do.call(rbind, datapoints)\n datapoints = datapoints[1:(nrow(datapoints)-1), ]\n \n out = list(\n datapoints = datapoints,\n by = if (length(unique(datapoints$by)) == 1) by else datapoints$by, \n facet = if (length(unique(datapoints$facet)) == 1) facet else datapoints$facet,\n ylab = ylab,\n xlabs = xlabs,\n col = col,\n bg = bg\n )\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/by_aesthetics.R", "by_col = function(ngrps = 1L, col = NULL, palette = NULL, gradient = NULL, ordered = NULL, alpha = NULL) {\n if (is.null(alpha)) alpha = 1\n if (is.null(ordered)) ordered = FALSE\n if (is.null(gradient)) gradient = FALSE\n assert_logical(ordered)\n assert_logical(gradient)\n if (gradient) {\n ngrps = 100L\n }\n \n # pal_qual = get_tpar(\"palette.qualitative\", default = NULL)\n pal_theme = get_tpar(\"palette.qualitative\", default = NULL)\n theme_flag = !is.null(pal_theme)\n\n # palette = substitute(palette, env = parent.env(environment()))\n\n # special \"by\" convenience keyword (will treat as NULL & handle grouping below)\n if (!anyNA(col) && !is.null(col) && length(col) == 1 && col == \"by\") col = NULL\n\n #\n ## Base case: If no color or palette provided, pass colors as a sequence of\n ## numbers (will inherit from / cycle over the user's default palette)\n \n if (is.null(col) && (is.null(palette) && !theme_flag)) {\n if (ngrps <= length(palette()) && !ordered) {\n col = palette()[seq_len(ngrps)]\n if (alpha) col = adjustcolor(col, alpha.f = alpha)\n } else {\n # fallback to restricted viridis palette\n col = colorRampPalette(\n hcl.colors(n = 100, palette = \"Viridis\", alpha = alpha)[(100 * 0.1 + 1):(100 * 0.9)],\n alpha = TRUE\n )(ngrps)\n }\n if (gradient || ordered) col = rev(col)\n return(col)\n }\n\n #\n ## Next simplest case: No palette, but color(s) provided directly. We do\n ## some simple sanity checks, apply alpha transparency and return as-is.\n\n if (is.atomic(col) && is.vector(col)) {\n if (length(col) == 1) {\n col = rep(col, ngrps)\n if (alpha) col = adjustcolor(col, alpha.f = alpha)\n return(col)\n } else if (length(col) < ngrps) {\n # if (!gradient) {\n # stop(sprintf(\"`col` must be of length 1, or greater than or equal to %s.\", ngrps), call. = FALSE)\n # } else {\n # # interpolate gradient colors\n # col = colorRampPalette(colors = col, alpha = TRUE)(ngrps)\n # }\n # if manual colours < ngrps, either (1) interpolate for gradient\n # colors, or (2) recycle for discrete colours\n if (gradient) {\n col = colorRampPalette(colors = col, alpha = TRUE)(ngrps)\n } else {\n ncolsstr = paste0(\"(\", length(col), \")\")\n ngrpsstr = paste0(\"(\", ngrps, \")\")\n warning(\n \"\\nFewer colours \", ncolsstr, \" provided than than there are groups \",\n ngrpsstr, \". Recycling to make up the shortfall.\"\n )\n col = rep(col, length.out = ngrps)\n }\n \n }\n if (gradient) {\n col = rev(col)\n } else if (!ordered && is.numeric(col)) {\n # col = palette()[col]\n if (ngrps <= length(palette())) {\n col = palette()[col]\n # if (alpha) col = adjustcolor(col, alpha.f = alpha)\n } else {\n col = hcl.colors(max(col), alpha = alpha)[col]\n }\n }\n if (anyNA(col) || is.character(col)) {\n if (alpha) col = adjustcolor(col, alpha.f = alpha)\n return(col)\n }\n }\n \n \n #\n ## Theme case: No palette provided, but fallback to tinytheme palette\n\n # we need to fix palette string, determine if in palette.pals() and then\n # determine no. of groups, before kicking over to sequential\n if (is.null(palette) && theme_flag) {\n if (length(pal_theme) == 1) {\n qual_match = match_pal(pal_theme, palette.pals())\n if (!is.na(qual_match)) {\n if (ngrps >= get_pal_lens(pal_theme) || ordered) {\n pal_theme = get_tpar(\"palette.sequential\", default = NULL)\n }\n # mostly a catch for x-gradient fills, e.g. type_ridge\n } else if (gradient && !is.na(match_pal(pal_theme, hcl.pals()))) {\n pal_theme = get_tpar(\"palette.sequential\", default = NULL)\n }\n }\n if (length(pal_theme) == 1) {\n palette_fun = gen_pal_fun(pal = pal_theme, gradient = gradient, alpha = alpha)\n args = list(n = ngrps, palette = pal_theme, alpha = alpha)\n }\n palette = pal_theme\n }\n \n if (is.null(palette)) {\n if (ngrps <= length(palette()) && !ordered && !gradient) {\n palette_fun = function(alpha) adjustcolor(palette(), alpha) # must be function to avoid arg ambiguity\n args = list(alpha = alpha)\n } else {\n if (ngrps <= 8 && !ordered) { # ngrps < 100 so we know gradient is FALSE too\n palette = \"R4\"\n palette_fun = palette.colors\n } else {\n palette = \"Viridis\"\n if (!gradient && !ordered) {\n palette_fun = hcl.colors\n } else {\n palette_fun_gradient = function(n, palette, from = 0.1, to = 0.9, alpha = 1) {\n colorRampPalette(\n hcl.colors(n = 100, palette = palette, alpha = alpha)[(100 * from + 1):(100 * to)],\n alpha = TRUE\n )(n)\n }\n palette_fun = palette_fun_gradient\n }\n }\n args = list(n = ngrps, palette = palette, alpha = alpha)\n }\n } else {\n if (is.character(palette)) {\n # special case: if vector of character strings, we assume that the user\n # must have passed a vector of colours (e.g., c(\"red\", \"blue\")) rather\n # than a known/named colour palette (e.g. \"Harmonic\")\n if (length(palette) > 1) {\n palette_fun = \"c\"\n if (!is.null(alpha)) palette = adjustcolor(palette, alpha.f = alpha)\n args = as.list(palette)\n if (length(args) < ngrps && length(args) != 1) {\n # if manual colours < ngrps, either (1) interpolate for gradient\n # colors, or (2) recycle for discrete colours\n if (gradient) {\n args = list(colorRampPalette(args, alpha = TRUE)(ngrps))\n } else {\n ncolsstr = paste0(\"(\", length(args), \")\")\n ngrpsstr = paste0(\"(\", ngrps, \")\")\n warning(\n \"\\nFewer colours \", ncolsstr, \" provided than than there are groups \",\n ngrpsstr, \". Recycling to make up the shortfall.\"\n )\n args = rep(args, length.out = ngrps)\n }\n }\n } else {\n palette_fun = gen_pal_fun(palette, gradient = gradient, alpha = alpha, n = ngrps)\n args = list(n = ngrps, palette = palette, alpha = alpha)\n }\n } else if (inherits(palette, c(\"call\", \"name\"))) {\n # catch for when using passes palette as named object (e.g,\n # pal26 = palette.colors(\"Alphabet\"))\n if (inherits(palette, \"name\") && is.character(eval(palette))) {\n args = as.list(eval(palette))\n palette_fun = \"c\"\n } else {\n args = as.list(palette)\n palette_fun = paste(args[[1]])\n args[[1]] = NULL\n }\n # catch for direct vector or list\n if (palette_fun %in% c(\"c\", \"list\")) {\n if (palette_fun == \"list\") palette_fun = \"c\"\n if (!is.null(alpha)) args = lapply(args, function(a) adjustcolor(a, alpha.f = alpha))\n if (length(args) < ngrps && length(args) != 1) {\n # if manual colours < ngrps, either (1) interpolate for gradient\n # colors, or (2) recycle for discrete colours\n if (gradient) {\n args = list(colorRampPalette(args, alpha = TRUE)(ngrps))\n } else {\n ncolsstr = paste0(\"(\", length(args), \")\")\n ngrpsstr = paste0(\"(\", ngrps, \")\")\n warning(\n \"\\nFewer colours \", ncolsstr, \" provided than than there are groups \",\n ngrpsstr, \". Recycling to make up the shortfall.\"\n )\n args = rep(args, length.out = ngrps)\n }\n }\n } else {\n args[[\"n\"]] = ngrps\n # remove unnamed arguments to prevent unintentional argument sliding\n if (any(names(args) == \"\")) args[[which(names(args) == \"\")]] = NULL\n }\n } else if (inherits(palette, \"function\")) {\n args = list()\n palette_fun = palette\n } else {\n stop(\n \"\\nInvalid palette argument. Must be a recognized keyword, or a \",\n \"palette-generating function with named arguments.\\n\"\n )\n }\n }\n\n cols = tryCatch(\n do.call(palette_fun, args),\n error = function(e) do.call(eval(palette), args) # catch for bespoke palette generating funcs\n )\n\n if (length(cols) > ngrps) cols = cols[1:ngrps]\n\n # For gradient and ordered colors, we'll run high to low\n if (gradient || ordered) cols = rev(cols)\n\n return(cols)\n}\n\n# Some utility functions for palette matching, etc.\n\nmatch_pal = function(pal, pals) {\n fx = function(x) tolower(gsub(\"[-, _, \\\\,, (, ), \\\\ , \\\\.]\", \"\", x))\n charmatch(fx(pal), fx(pals))\n}\n\nget_pal_lens = function(pal) {\n pal_lens = c(\n R3 = 8L, R4 = 8L, ggplot2 = 8L, `Okabe-Ito` = 9L, Accent = 8L,\n `Dark 2` = 8L, Paired = 12L, `Pastel 1` = 9L, `Pastel 2` = 8L, \n `Set 1` = 9L, `Set 2` = 8L, `Set 3` = 12L, `Tableau 10` = 10L, \n `Classic Tableau` = 10L, `Polychrome 36` = 36L, Alphabet = 26L\n )\n pal_lens[pal]\n}\n\n# take a character string, match to either palette.pals() pr hcl.pals(), and\n# generate the corresponding function factor with alpha transparency\ngen_pal_fun = function(pal, gradient = FALSE, alpha = NULL, n = NULL) {\n pal_match = match_pal(pal, palette.pals())\n if (!is.na(pal_match)) {\n if (pal_match < 1L) stop(\"'palette' is ambiguous\")\n pal_fun = palette.colors\n if (!is.null(n) && n >= get_pal_lens(pal_match)) {\n warning(\n \"\\nFewer colours \", get_pal_lens(pal_match), \" provided than than there are groups \",\n n, \". Recycling to make up the shortfall.\"\n )\n pal_fun = function(n, palette, alpha) palette.colors(n = n, palette = pal, alpha = alpha, recycle = TRUE)\n }\n if (gradient) {\n pal_fun = function(n, palette, alpha) colorRampPalette(palette.colors(palette = pal, alpha = alpha))(n)\n }\n } else {\n pal_match = match_pal(pal, hcl.pals())\n if (!is.na(pal_match)) {\n if (pal_match < 1L) stop(\"'palette' is ambiguous\")\n pal_fun = hcl.colors\n } else {\n stop(\n \"\\nPalette string not recogized. Must be a value produced by either\",\n \"`palette.pals()` or `hcl.pals()`.\\n\",\n call. = FALSE\n )\n }\n }\n return(pal_fun)\n}\n\n\nby_pch = function(ngrps, type, pch = NULL) {\n no_pch = FALSE\n if (identical(type, \"text\")) {\n pch <- rep(15, ngrps)\n } else if (!type %in% c(\"p\", \"b\", \"o\", \"pointrange\", \"errorbar\", \"boxplot\", \"qq\")) {\n no_pch = TRUE\n pch = NULL\n\n # special \"by\" convenience keyword\n } else if (!is.null(pch) && length(pch) == 1 && pch == \"by\") {\n no_pch = TRUE # skip checks below\n pch = 1:ngrps + par(\"pch\") - 1\n # correctly recycle if over max pch type\n pch_ceiling = 25 # see ?pch\n if (max(pch) > pch_ceiling) {\n pch_below = pch[pch <= pch_ceiling]\n pch_above = pch[pch > pch_ceiling]\n pch_above = rep_len(0:pch_ceiling, length(pch_above))\n pch = c(pch_below, pch_above)\n }\n\n # return NULL if not a valid point type\n } else if (is.null(pch)) {\n pch = par(\"pch\")\n }\n\n if (!no_pch) {\n if (!is.atomic(pch) || !is.vector(pch) || !(is.numeric(pch) || is.character(pch)) || (length(pch) != 1 && length(pch) != ngrps)) {\n # if (!is.atomic(pch) || !is.vector(pch) || !is.numeric(pch) || (length(pch) != 1 && length(pch) != ngrps)) {\n stop(sprintf(\"`pch` must be `NULL`, or a numeric or character vector of length 1 or %s.\", ngrps), call. = FALSE)\n }\n\n if (length(pch) == 1) {\n pch = rep(pch, ngrps)\n }\n }\n\n return(pch)\n}\n\n\nby_lty = function(ngrps, type, lty = NULL) {\n # We only care about line types, otherwise return NULL\n if (!type %in% c(\"l\", \"b\", \"o\", \"c\", \"h\", \"s\", \"S\", \"ribbon\", \"barplot\", \"boxplot\", \"rect\", \"segments\", \"qq\", \"abline\", \"hline\", \"vline\")) {\n out = NULL\n\n # special \"by\" convenience keyword\n } else if (!is.null(lty) && length(lty) == 1 && lty == \"by\") {\n lty_dict = c(\"solid\", \"dashed\", \"dotted\", \"dotdash\", \"longdash\", \"twodash\")\n par_lty = par(\"lty\")\n\n if (!par_lty %in% lty_dict) {\n warning(\n \"\\nBesoke lty specifications (i.e., using string combinations) are not\",\n \"currently supported alongside the lty='by' keyword argument.\",\n \"Defaulting to 1 and looping from there.\\n\"\n )\n par_lty = 1\n } else {\n par_lty = which(par_lty == lty_dict)\n }\n out = 1:ngrps + par_lty - 1\n # correctly recycle if over max pch type\n lty_ceiling = 6 # see ?pch\n if (max(out) > lty_ceiling) {\n lty_below = out[out <= lty_ceiling]\n lty_above = out[out > lty_ceiling]\n lty_above = rep_len(1:lty_ceiling, length(lty_above))\n out = c(lty_below, lty_above)\n }\n\n # NULL -> solid (or default) line\n } else if (is.null(lty)) {\n if (identical(type, \"boxplot\")) {\n out = NULL\n } else {\n out = rep(par(\"lty\"), ngrps)\n }\n\n # atomic vector: sanity check length\n } else if (is.atomic(lty) && is.vector(lty)) {\n if (length(lty) == 1) {\n out = rep(lty, ngrps)\n } else {\n if (length(lty) != ngrps) {\n stop(sprintf(\"`lty` must be `NULL` or a numeric vector of length 1 or %s.\", ngrps), call. = FALSE)\n }\n out = lty\n }\n }\n\n return(out)\n}\n\n\nby_lwd = function(ngrps, type, lwd = NULL) {\n lwd_base = par(\"lwd\")\n lwd_floor = lwd_base / min(5, max((ngrps - 1), 1))\n lwd_ceiling = lwd_base * min(5, ngrps)\n\n no_lwd = FALSE\n # special \"by\" convenience keyword\n if (!is.null(lwd) && length(lwd) == 1 && lwd == \"by\") {\n no_lwd = TRUE # skip checks below\n lwd = seq(lwd_floor, lwd_ceiling, length.out = ngrps)\n } else if (is.null(lwd)) {\n no_lwd = TRUE\n lwd = NULL\n }\n\n if (!no_lwd) {\n if (!is.atomic(lwd) || !is.vector(lwd) || !is.numeric(lwd) || (length(lwd) != 1 && length(lwd) != ngrps)) {\n stop(sprintf(\"`lwd` must be `NULL` or a numeric vector of length 1 or %s.\", ngrps), call. = FALSE)\n }\n if (length(lwd) == 1) {\n lwd = rep(lwd, ngrps)\n }\n }\n\n return(lwd)\n}\n\n\nby_bg = function(\n adjustcolor,\n alpha,\n bg,\n by,\n by_continuous,\n by_ordered,\n col,\n fill,\n ngrps,\n palette,\n ribbon.alpha,\n type) {\n if (is.null(bg) && !is.null(fill)) bg = fill\n if (!is.null(bg) && length(bg) == 1 && is.numeric(bg) && bg >= 0 && bg <= 1) {\n alpha = bg\n bg = \"by\"\n }\n if (!is.null(bg) && length(bg) == 1 && bg == \"by\") {\n bg = by_col(\n ngrps = ngrps,\n col = NULL,\n palette = palette,\n gradient = by_continuous,\n ordered = by_ordered,\n alpha = alpha\n )\n } else if (length(bg) != ngrps) {\n bg = rep(bg, ngrps)\n }\n if (type == \"ribbon\" || (type == \"boxplot\" && !is.null(by))) {\n if (!is.null(bg)) {\n bg = adjustcolor(bg, ribbon.alpha)\n } else if (!is.null(col)) {\n bg = adjustcolor(col, ribbon.alpha)\n }\n }\n\n return(bg)\n}\n"], ["/tinyplot/R/zzz.R", "#' Operations on package load\n#' @importFrom utils globalVariables\n#' @param libname library name\n#' @param pkgname package name name\n#' @keywords internal\n#' @noRd\n.onLoad = function(libname, pkgname) {\n # https://stackoverflow.com/questions/12598242/global-variables-in-packages-in-r\n # https://stackoverflow.com/questions/49056642/r-how-to-make-variable-available-to-namespace-at-loading-time?noredirect=1&lq=1\n init_environment()\n init_tpar()\n set_environment_variable(\".saved_par_before\", NULL)\n set_environment_variable(\".saved_par_after\", NULL)\n set_environment_variable(\".saved_par_first\", NULL)\n set_environment_variable(\".last_call\", NULL)\n set_environment_variable(\".tpar_hooks\", NULL)\n\n globalVariables(c(\n \"add\",\n \"asp\",\n \"axes\",\n \"by_continuous\",\n \"by_ordered\",\n \"cex_fct_adj\",\n \"dots\",\n \"draw\",\n \"facet_bg\",\n \"facet_border\",\n \"facet_col\",\n \"facet_font\",\n \"facet_newlines\",\n \"facet_rect\",\n \"facet_text\",\n \"facet.args\",\n \"facet\",\n \"facets\",\n \"fill\",\n \"flip\",\n \"frame.plot\",\n \"has_legend\",\n \"iby\",\n \"ifacet\",\n \"nfacet_cols\",\n \"nfacet_rows\",\n \"nfacets\",\n \"ngrps\",\n \"oxaxis\",\n \"oyaxis\",\n \"ribbon.alpha\",\n \"split_data\",\n \"type\",\n \"x\",\n \"xaxl\",\n \"xaxs\",\n \"xaxt\",\n \"xlabs\",\n \"xlim\",\n \"xlim_user\",\n \"xlvls\",\n \"xmax\",\n \"xmin\",\n \"y\",\n \"yaxl\",\n \"yaxs\",\n \"yaxt\",\n \"ylabs\",\n \"ylim\",\n \"ylim_user\",\n \"ymax\",\n \"ymin\"\n ))\n}\n"], ["/tinyplot/R/type_ribbon.R", "#' Ribbon and area plot types\n#' \n#' @param alpha numeric value between 0 and 1 specifying the opacity of ribbon shading\n#' If no `alpha` value is provided, then will default to `tpar(\"ribbon.alpha\")` \n#' (i.e., probably `0.2` unless this has been overridden by the user in their global \n#' settings.)\n#'\n#' @description Type constructor functions for producing polygon ribbons, which \n#' define a `y` interval (usually spanning from `ymin` to `ymax`) for each\n#' `x` value. Area plots are a special case of ribbon plot where `ymin` is\n#' set to 0 and `ymax` is set to `y`.\n#' \n#' @examples\n#' x = 1:100/10\n#' y = sin(x)\n#' \n#' #\n#' ## Ribbon plots\n#' \n#' # \"ribbon\" convenience string\n#' tinyplot(x = x, ymin = y-1, ymax = y+1, type = \"ribbon\")\n\n#' # Same result with type_ribbon()\n#' tinyplot(x = x, ymin = y-1, ymax = y+1, type = type_ribbon())\n#' \n#' # y will be added as a line if it is specified\n#' tinyplot(x = x, y = y, ymin = y-1, ymax = y+1, type = \"ribbon\")\n#'\n#' #\n#' ## Area plots\n#' \n#' # \"area\" type convenience string\n#' tinyplot(x, y, type = \"area\")\n#' \n#' # Same result with type_area()\n#' tinyplot(x, y, type = type_area())\n#' \n#' # Area plots are often used for time series charts\n#' tinyplot(AirPassengers, type = \"area\")\n#' @export\ntype_ribbon = function(alpha = NULL) {\n out = list(\n draw = draw_ribbon(),\n data = data_ribbon(ribbon.alpha = alpha),\n name = \"ribbon\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_ribbon = function() {\n fun = function(ix, iy, ixmin, ixmax, iymin, iymax, ibg, ilty, ilwd, icol, ipch, i, flip = FALSE, ...) {\n polyg = type_polygon()$draw\n lin = type_lines()$draw\n if (isFALSE(flip)) {\n polyg(ix = c(ix, rev(ix)), iy = c(iymin, rev(iymax)), icol = NA, ibg = ibg)\n } else {\n polyg(c(ixmin, rev(ixmax)), iy = c(iy, rev(iy)), icol = NA, ibg = ibg)\n }\n lin(ix = ix, iy = iy, icol = icol, ipch = ipch, ibg = ibg, ilty = ilty, ilwd = ilwd, type = \"l\")\n }\n return(fun)\n}\n\n\ndata_ribbon = function(ribbon.alpha = NULL) {\n ribbon.alpha = sanitize_ribbon.alpha(ribbon.alpha)\n fun = function(datapoints, xlabs, null_by, null_facet, ...) {\n # Convert x to factor if it's not already\n if (is.character(datapoints$x)) {\n datapoints$x = as.factor(datapoints$x)\n }\n\n if (is.factor(datapoints$x)) {\n xlvls = levels(datapoints$x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n datapoints$x = as.integer(datapoints$x)\n } else {\n xlabs = NULL\n }\n\n if (null_by && null_facet) {\n xord = order(datapoints$x)\n } else if (null_facet) {\n xord = order(datapoints$by, datapoints$x)\n } else if (null_by) {\n xord = order(datapoints$facet, datapoints$x)\n } else {\n xord = order(datapoints$by, datapoints$facet, datapoints$x)\n }\n\n # Reorder x, y, ymin, and ymax based on the order determined\n datapoints = datapoints[xord,]\n\n # Catch for missing ymin and ymax \n if (is.null(datapoints$ymin)) datapoints$ymin = datapoints$y \n if (is.null(datapoints$ymax)) datapoints$ymax = datapoints$y\n\n out = list(\n x = datapoints$x,\n y = datapoints$y,\n ymin = datapoints$ymin,\n ymax = datapoints$ymax,\n xlabs = xlabs,\n datapoints = datapoints,\n ribbon.alpha = ribbon.alpha)\n\n if (length(unique(datapoints$by)) > 1) out[[\"by\"]] = datapoints$by\n if (length(unique(datapoints$facet)) > 1) out[[\"facet\"]] = datapoints$facet\n\n return(out)\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_function.R", "#' Plot a function\n#'\n#' @details\n#' When using `type_function()` in a `tinyplot()` call, the `x` value indicates\n#' the range of values to plot on the x-axis.\n#'\n#' @param fun Function of `x` to plot. Defaults to \\code{\\link[stats]{dnorm}}.\n#' @param args List of additional arguments to be passed to `fun`.\n#' @param n Number of points to interpolate on the x axis.\n#' @param ... Additional arguments are passed to the `lines()` function,\n#' ex: `type=\"p\"`, `col=\"pink\"`.\n#' @importFrom stats dnorm\n#' \n#' @examples\n#' # Plot the normal density (default function)\n#' tinyplot(x = -4:4, type = \"function\")\n#' # tinyplot(x = -4:4, type = type_function()) # same\n#'\n#' # Customize by passing explicit arguments to your function\n#' tinyplot(x = -1:10, type = type_function(\n#' fun = dnorm, args = list(mean = 3)\n#' ))\n#'\n#' # Additional arguments are passed to the `lines()` function.\n#' tinyplot(x = -4:4, type = type_function(\n#' fun = dnorm,\n#' col = \"pink\", type = \"p\", pch = 3\n#' ))\n#' \n#' # Custom function example\n#' ## (Here using `function(x)`, but you could also use the shorter `\\(x)`\n#' ## anonymous function syntax introduced in R 4.1.0)\n#' tinyplot(x = -4:4, type = type_function(fun = function(x) 0.5 * exp(-abs(x))))\n#'\n#' @export\ntype_function = function(fun = dnorm, args = list(), n = 101, ...) {\n assert_function(fun)\n lines_args = list(...)\n data_function = function(args, fun) {\n funky = function(xlim, ylim, datapoints, ...) {\n if (nrow(datapoints) == 0 || !\"x\" %in% names(datapoints)) {\n stop(\"Need to provide x values to plot the function.\", call. = FALSE)\n }\n if (is.null(xlim)) {\n xlim = range(datapoints[[\"x\"]])\n }\n if (is.null(ylim)) {\n tmp = c(list(datapoints[[\"x\"]]), args)\n tmp = range(tmp)\n tmp = seq(tmp[1], tmp[2], length.out = n)\n tmp = c(list(tmp), args)\n tmp = do.call(fun, tmp)\n ylim = c(min(tmp), max(tmp))\n }\n out = list(xlim = xlim, ylim = ylim)\n return(out)\n }\n }\n draw_function = function() {\n funky = function(ifacet, data_facet, ...) {\n xrange = range(data_facet[[ifacet]][[\"x\"]])\n x = seq(xrange[1], xrange[2], length.out = n)\n y = do.call(fun, c(list(x), args))\n tmp = c(list(x, y), lines_args)\n do.call(lines, tmp)\n }\n return(funky)\n }\n out = list(\n draw = draw_function(),\n data = data_function(args = args, fun = fun),\n name = \"function\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_qq.R", "#' Quantile-Quantile plot (QQ)\n#'\n#' @description Plots the theoretical quantiles of `x` on the horizontal axis\n#' against observed values of `x` on the vertical axis.\n#'\n#' @param distribution Distribution function to use.\n#' @examples\n#' tinyplot(~mpg, data = mtcars, type = type_qq())\n#'\n#' # suppress the line\n#' tinyplot(~mpg, data = mtcars, lty = 0, type = type_qq())\n#' @importFrom stats qnorm ppoints quantile\n#' @export\ntype_qq = function(distribution = qnorm) {\n data_qq = function(distribution) {\n fun = function(datapoints, ...) {\n y = sort(datapoints$y)\n x = datapoints$x\n x = distribution(ppoints(x))\n datapoints$x = x\n datapoints$y = y\n out = list(datapoints = datapoints)\n return(out)\n }\n }\n\n draw_qq = function() {\n fun = function(ix, iy, icol, ibg, ipch, ilwd, ilty, cex, xlab, ...) {\n points(\n x = ix,\n y = iy,\n col = icol,\n bg = ibg,\n type = \"p\",\n pch = ipch,\n lwd = ilwd,\n cex = cex\n )\n\n if (!is.null(ilty)) {\n iy <- quantile(iy, c(0.25, 0.75))\n ix <- quantile(ix, c(0.25, 0.75))\n slope <- diff(iy) / diff(ix)\n intercept <- iy[1] - slope * ix[1]\n abline(a = intercept, b = slope, lty = ilty, col = icol, lwd = ilwd)\n }\n }\n return(fun)\n }\n\n out = list(\n draw = draw_qq(),\n data = data_qq(distribution = distribution),\n name = \"qq\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/tinyformula.R", "## auxiliary functions for formula/facet parsing\n\ntinyformula = function(formula, facet = NULL) {\n ## input\n ## - formula: y ~ x or y ~ x | z or ~ x or ~ x | z\n ## - facet: ~ a or ~ a + b or b ~ a\n ##\n ## output:\n ## - x: ~ x\n ## - y: NULL or ~ y\n ## - by: NULL or ~ z or ~ z1 + z2 + ... (use interaction of all)\n ## - xfacet: NULL or ~ a or ~ a + b etc.\n ## - yfacet: NULL or ~ b\n ## - full: e.g. ~ x + y + z + a + b\n\n ## preliminaries\n if (!inherits(formula, \"formula\")) formula = as.formula(formula)\n nf = length(formula)\n\n ## basic formula types\n x = ~ x\n y = if (nf == 2L) NULL else ~ y\n by = if (!inherits(formula[[nf]], \"call\") || formula[[nf]][[1L]] != as.name(\"|\")) NULL else ~ z\n if (is.null(facet) || !inherits(facet, \"formula\")) {\n xfacet = NULL\n yfacet = NULL\n } else {\n xfacet = ~ a\n yfacet = if (length(facet) == 2L) NULL else ~ b\n }\n\n ## fill with actual terms\n environment(x) = environment(formula)\n if (!is.null(y)) {\n environment(y) = environment(formula)\n y[[2L]] = formula[[2L]]\n }\n if (is.null(by)) {\n x[[2L]] = formula[[nf]]\n } else {\n environment(by) = environment(formula)\n by[[2L]] = formula[[nf]][[3L]]\n x[[2L]] = formula[[nf]][[2L]]\n }\n if (!is.null(xfacet)) {\n environment(xfacet) = environment(formula)\n xfacet[[2L]] = facet[[length(facet)]]\n }\n if (!is.null(yfacet)) {\n environment(yfacet) = environment(formula)\n yfacet[[2L]] = facet[[2L]]\n }\n\n ## combine everything\n full = x\n if (!is.null(y)) full[[2L]] = call(\"+\", full[[2L]], y[[2L]])\n if (!is.null(by)) full[[2L]] = call(\"+\", full[[2L]], by[[2L]])\n if (!is.null(xfacet)) full[[2L]] = call(\"+\", full[[2L]], xfacet[[2L]])\n if (!is.null(yfacet)) full[[2L]] = call(\"+\", full[[2L]], yfacet[[2L]])\n\n ## return list of all formulas\n return(list(\n x = x,\n y = y,\n by = by,\n xfacet = xfacet,\n yfacet = yfacet,\n full = full\n ))\n}\n\ntinyframe = function(formula, data, drop = FALSE) {\n ## input\n ## - formula: (sub-)formula\n ## - data: model.frame from full formula\n if (is.null(formula)) return(NULL)\n names = sapply(attr(terms(formula), \"variables\")[-1L], deparse, width.cutoff = 500L)\n data[, names, drop = drop]\n}\n"], ["/tinyplot/R/type_rug.R", "#' Add a rug to a plot\n#' \n#' @description\n#' Adds a rug representation (1-d plot) of the data to the plot.\n#' \n#' @details\n#' This function should only be used as part of [`tinyplot_add()`], i.e. adding\n#' to an existing plot.\n#' \n#' In most cases, determining which variable receives the rug representation\n#' will be based on the `side` argument (i.e., x-variable if side is 1 or 3, and\n#' y-variable if side is 2 or 4). An exception is if the preceding plot type was\n#' either `\"density\"` or `\"histogram\"`; for these latter cases, the x-variable\n#' will always be used. See Examples.\n#' \n#' @inheritParams graphics::rug\n#' @param jitter Logical. Add jittering to separate ties? Default is `FALSE`.\n#' @param amount Numeric. Amount of jittering (see \\code{\\link[base]{jitter}}).\n#' Only used if `jitter` is `TRUE`.\n#' @examples\n#' tinyplot(~wt | am, data = mtcars, type = \"density\", facet = \"by\", fill = \"by\")\n#' tinyplot_add(type = \"rug\")\n#' # use type_rug() to pass extra options\n#' tinyplot_add(type = type_rug(side = 3, ticksize = 0.05))\n#' \n#' # For ties, use jittering\n#' tinyplot(eruptions ~ waiting, data = faithful, type = \"lm\")\n#' tinyplot_add(type = type_rug(jitter = TRUE, amount = 0.3))\n#' tinyplot_add(type = type_rug(jitter = TRUE, amount = 0.1, side = 2))\n#' # Add original points just for reference\n#' tinyplot_add(type = \"p\")\n#' \n#' @importFrom graphics rug\n#' @export\ntype_rug = function(ticksize = 0.03, side = 1, quiet = getOption(\"warn\") < 0, jitter = FALSE, amount = NULL) {\n data_rug = function(datapoints, ...) {\n if (nrow(datapoints) == 0) {\n msg = \"`type_rug() only works on existing plots with x and y data points.\"\n stop(msg, call. = FALSE)\n }\n return(datapoints)\n }\n draw_rug = function(.ticksize = ticksize, .side = side, .quiet = quiet, .jitter = jitter, .amount = amount) {\n fun = function(ix, iy, icol, ilwd, ...) {\n lc = getOption(\"tinyplot_last_call\", default = NULL)\n swapy = !is.null(lc$type) && lc$type %in% c(\"density\", \"hist\", \"histogram\")\n rugx = if (swapy) iy else if (side %in% c(1, 3)) ix else iy\n if (isTRUE(jitter)) rugx = jitter(rugx, amount = .amount)\n rug(\n x = rugx,\n col = icol,\n lwd = ilwd,\n ticksize = .ticksize,\n side = .side,\n quiet = .quiet\n )\n }\n return(fun)\n }\n\n out = list(\n draw = draw_rug(),\n data = data_rug,\n name = \"rug\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_summary.R", "#' Plot summary values of `y` at unique values of `x`\n#'\n#' @md\n#' @description\n#' Applies a summary function to `y` along unique values of `x`. For example,\n#' plot the mean `y` value for each `x` value. Internally,\n#' `type_summary()` applies a thin wrapper around \\code{\\link[stats]{ave}} and\n#' then passes the result to [`type_lines`] for drawing.\n#'\n#' @param fun summarizing function. Should be compatible with\n#' \\code{\\link[stats]{ave}}. Defaults to \\code{\\link[base]{mean}}.\n#' @param ... Additional arguments are passed to the `lines()` function,\n#' ex: `type=\"p\"`, `col=\"pink\"`.\n#' @seealso [`ave`] which performs the summarizing (averaging) behind the\n#' scenes.\n#' @examples\n#' # Plot the mean chick weight over time\n#' tinyplot(weight ~ Time, data = ChickWeight, type = \"summary\")\n#' \n#' # Note: \"mean\" is the default function, so these are also equivalent:\n#' # tinyplot(weight ~ Time, data = ChickWeight, type = type_summary())\n#' # tinyplot(weight ~ Time, data = ChickWeight, type = type_summary(mean))\n#' \n#' # Plot the median instead\n#' tinyplot(weight ~ Time, data = ChickWeight, type = type_summary(median))\n#' \n#' # Works with groups and/or facets too\n#' tinyplot(weight ~ Time | Diet, facet = \"by\", data = ChickWeight, type = \"summary\")\n#'\n#' # Custom/complex function example\n#' tinyplot(\n#' weight ~ Time | Diet, facet = \"by\", data = ChickWeight,\n#' type = type_summary(function(y) quantile(y, probs = 0.9)/max(y))\n#' )\n#' \n#' @importFrom stats ave\n#' @export\ntype_summary = function(fun = mean, ...) {\n assert_function(fun)\n lines_args = list(...)\n data_summary = function(fun) {\n funky = function(datapoints, ...) {\n datapoints = split(datapoints, list(datapoints$facet, datapoints$by), drop = TRUE)\n datapoints = lapply(datapoints, function(dat) {\n newy = ave(dat$y, dat$x, FUN = fun)\n dat$y = newy\n dat = dat[order(dat$x), ]\n return(dat)\n })\n datapoints = do.call(rbind, datapoints)\n out = list(datapoints = datapoints)\n return(out)\n }\n return(funky)\n }\n out = list(\n draw = draw_lines(...),\n data = data_summary(fun = fun),\n name = \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_boxplot.R", "#' Boxplot type\n#' \n#' @description Type function for producing box-and-whisker plots.\n#' Arguments are passed to \\code{\\link[graphics]{boxplot}}, although `tinyplot`\n#' scaffolding allows added functionality such as grouping and faceting.\n#' Box-and-whisker plots are the default plot type if `x` is a factor and `y` is\n#' numeric.\n#'\n#' @inheritParams graphics::boxplot\n#' @examples\n#' # \"boxplot\" type convenience string\n#' tinyplot(count ~ spray, data = InsectSprays, type = \"boxplot\")\n#' \n#' # Note: Specifying the type here is redundant. Like base plot, tinyplot\n#' # automatically produces a boxplot if x is a factor and y is numeric\n#' tinyplot(count ~ spray, data = InsectSprays)\n#' \n#' # Grouped boxplot example\n#' tinyplot(len ~ dose | supp, data = ToothGrowth, type = \"boxplot\")\n#' \n#' # Use `type_boxplot()` to pass extra arguments for customization\n#' tinyplot(\n#' len ~ dose | supp, data = ToothGrowth, lty = 1,\n#' type = type_boxplot(boxwex = 0.3, staplewex = 0, outline = FALSE)\n#' )\n#' @export\ntype_boxplot = function(\n range = 1.5,\n width = NULL,\n varwidth = FALSE,\n notch = FALSE,\n outline = TRUE,\n boxwex = 0.8,\n staplewex = 0.5,\n outwex = 0.5) {\n out = list(\n draw = draw_boxplot(\n range = range,\n width = width,\n varwidth = varwidth,\n notch = notch,\n outline = outline,\n boxwex = boxwex,\n staplewex = staplewex,\n outwex = outwex),\n data = data_boxplot(),\n name = \"boxplot\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\n\ndraw_boxplot = function(range, width, varwidth, notch, outline, boxwex, staplewex, outwex) {\n fun = function(iby, ix, iy, ipch, ilty, icol, ibg, x_by = FALSE, facet_by = FALSE, ngrps = 1, flip, ...) {\n\n at_ix = unique(ix)\n if (isTRUE(x_by)) boxwex = boxwex * 2\n\n # Handle multiple groups\n if (ngrps > 1 && isFALSE(x_by) && isFALSE(facet_by)) {\n boxwex_orig = boxwex\n boxwex = boxwex / ngrps - 0.01\n at_ix = at_ix + seq(\n -((boxwex_orig - boxwex) / 2),\n ((boxwex_orig - boxwex) / 2),\n length.out = ngrps\n )[iby]\n }\n\n boxplot(\n formula = iy ~ ix,\n pch = ipch,\n lty = ilty,\n border = icol,\n col = ibg,\n horizontal = flip,\n add = TRUE, axes = FALSE,\n at = at_ix,\n range = range,\n width = width,\n varwidth = varwidth,\n notch = notch,\n outline = outline,\n boxwex = boxwex,\n staplewex = staplewex,\n outwex = outwex\n )\n }\n return(fun)\n}\n\n\n\ndata_boxplot = function() {\n fun = function(datapoints, bg, col, palette, null_by, null_facet, ...) {\n # Convert x to factor if it's not already\n datapoints$x = as.factor(datapoints$x)\n\n # Handle factor levels and maintain order\n xlvls = levels(datapoints$x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n datapoints$x = as.integer(datapoints$x)\n\n if (null_by && null_facet) {\n xord = order(datapoints$x)\n } else if (null_facet) {\n xord = order(datapoints$by, datapoints$x)\n } else if (null_by) {\n xord = order(datapoints$facet, datapoints$x)\n } else {\n xord = order(datapoints$by, datapoints$facet, datapoints$x)\n }\n\n if (length(unique(datapoints[[\"by\"]])) == 1 && is.null(palette)) {\n if (is.null(col)) col = par(\"fg\")\n if (is.null(bg)) bg = \"lightgray\"\n } else {\n bg = \"by\"\n }\n\n # Reorder x, y, ymin, and ymax based on the order determined\n datapoints = datapoints[xord,]\n\n # Return the result as a list called 'out'\n out = list(\n x = datapoints$x,\n y = datapoints$y,\n ymin = datapoints$ymin,\n ymax = datapoints$ymax,\n xlabs = xlabs,\n datapoints = datapoints,\n col = col,\n bg = bg)\n\n if (length(unique(datapoints$by)) > 1) out[[\"by\"]] = datapoints$by\n if (length(unique(datapoints$facet)) > 1) out[[\"facet\"]] = datapoints$facet\n\n return(out)\n }\n return(fun)\n}\n\n\n\n\n"], ["/tinyplot/R/utils.R", "rescale_num = function (x, from = NULL, to = NULL) {\n if (is.null(from)) from = range(x)\n if (is.null(to)) to = c(0, 1)\n (x - from[1])/diff(from) * diff(to) + to[1]\n}\n\n## Function for efficiently checking whether a vector has more than n unique\n## values (uses a hash set approach for large vectors to check sequentially)\nmore_than_n_unique = function(x, n, small_vec_len = 1e3L) {\n len_x = length(x)\n # For \"small\" vectors, just use direct length(unique(x)) approach\n if (len_x <= small_vec_len) {\n return(length(unique(x)) > n)\n } else {\n # For larger vectors, use the hash set approach\n env = new.env(hash = TRUE, size = n)\n count = 0\n for (val in x) {\n if (!exists(as.character(val), env)) {\n assign(as.character(val), TRUE, env)\n count = count + 1\n if (count > n) {\n return(TRUE)\n }\n }\n }\n return(FALSE)\n }\n}\n\n\n## Null coalescing operator\nif (getRversion() <= \"4.4.0\") {\n `%||%` = function(x, y) if (is.null(x)) y else x\n}\n\n\n## Function that computes an appropriate bandwidth kernel based on a string\n## input\nbw_fun = function(kernel, x) {\n kernel = tolower(kernel)\n switch(\n kernel,\n nrd0 = bw.nrd0(x),\n nrd = bw.nrd(x),\n ucv = bw.ucv(x),\n bcv = bw.bcv(x),\n sj = bw.SJ(x),\n stop(\"Invalid `bw` string. Choose from 'nrd0', 'nrd', 'ucv', 'bcv', or 'SJ'.\")\n )\n}\n"], ["/tinyplot/R/type_points.R", "#' Points plot type\n#'\n#' @description Type function for plotting points, i.e. a scatter plot.\n#' \n#' @examples\n#' # \"p\" type convenience character string\n#' tinyplot(Sepal.Length ~ Petal.Length, data = iris, type = \"p\")\n#' \n#' # Same result with type_points()\n#' tinyplot(Sepal.Length ~ Petal.Length, data = iris, type = type_points())\n#' \n#' # Note: Specifying the type here is redundant. Like base plot, tinyplot\n#' # automatically produces a scatter plot if x and y are numeric\n#' tinyplot(Sepal.Length ~ Petal.Length, data = iris)\n#' \n#' # Grouped scatter plot example\n#' tinyplot(Sepal.Length ~ Petal.Length | Species, data = iris)\n#' \n#' # Continuous grouping (with gradient legend)\n#' tinyplot(Sepal.Length ~ Petal.Length | Sepal.Width, data = iris, pch = 19)\n#' \n#' @export\ntype_points = function() {\n out = list(\n draw = draw_points(),\n data = data_points(),\n name = \"p\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\ndata_points = function() {\n fun = function(datapoints, ...) {\n # catch for factors (we should still be able to \"force\" plot these with points)\n if (is.factor(datapoints$x)) {\n xlvls = levels(datapoints$x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n datapoints$x = as.integer(datapoints$x)\n } else {\n xlabs = NULL\n }\n if (is.factor(datapoints$y)) {\n ylvls = levels(datapoints$y)\n ylabs = seq_along(ylvls)\n names(ylabs) = ylvls\n datapoints$y = as.integer(datapoints$y)\n } else {\n ylabs = NULL\n }\n \n out = list(\n datapoints = datapoints,\n xlabs = xlabs,\n ylabs = ylabs\n )\n return(out)\n }\n}\n\ndraw_points = function() {\n fun = function(ix, iy, icol, ibg, ipch, ilwd, cex, ...) {\n points(\n x = ix,\n y = iy,\n col = icol,\n bg = ibg,\n type = \"p\",\n pch = ipch,\n lwd = ilwd,\n cex = cex\n )\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_vline.R", "#' @param v x-value(s) for vertical line(s). Numeric of length 1, or equal to\n#' the number of groups or number of facets (or the product thereof).\n#' @rdname type_abline\n#' @export\ntype_vline = function(v = 0) {\n assert_numeric(v)\n data_vline = function(datapoints, lwd, lty, col, ...) {\n if (nrow(datapoints) == 0) {\n msg = \"`type_vline() only works on existing plots with x and y data points.\"\n stop(msg, call. = FALSE)\n }\n # keep track of unique lty and lwd (needed for group catch / escape hatch\n # later in draw_hline)\n ul_lwd = length(unique(lwd))\n ul_lty = length(unique(lty))\n ul_col = length(unique(col))\n return(list(type_info = list(ul_lty = ul_lty, ul_lwd = ul_lwd, ul_col = ul_col)))\n }\n draw_vline = function() {\n fun = function(\n ifacet, iby, data_facet, icol, ilty, ilwd,\n ngrps, nfacets, by_continuous, facet_by,\n type_info,\n ...\n ) {\n\n # flag for aesthetics by groups\n grp_aes = type_info[[\"ul_col\"]] == 1 || type_info[[\"ul_lty\"]] == ngrps || type_info[[\"ul_lwd\"]] == ngrps\n \n if (length(v) != 1) {\n if (!length(v) %in% c(ngrps, nfacets, ngrps*nfacets)) {\n msg = \"Length of 'v' must be 1, or equal to the number of facets or number of groups (or product thereof).\"\n stop(msg, call. = FALSE)\n }\n if (!facet_by && length(v) == nfacets) {\n v = v[ifacet]\n if (!grp_aes && type_info[[\"ul_col\"]]!=ngrps) {\n icol = 1\n } else if (by_continuous) {\n icol = 1\n }\n } else if (!by_continuous && length(v) == ngrps * nfacets) {\n v = v[ifacet * ngrps - c(ngrps - iby)]\n } else if (!by_continuous) {\n v = v[iby]\n }\n } else if (!grp_aes) {\n icol = 1\n }\n \n abline(v = v, col = icol, lty = ilty, lwd = ilwd)\n }\n return(fun)\n }\n out = list(\n draw = draw_vline(),\n data = data_vline,\n name = \"vline\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_glm.R", "#' Generalized linear model plot type\n#' \n#' @description Type function for plotting a generalized model fit.\n#' Arguments are passed to \\code{\\link[stats]{glm}}.\n#' \n#' @param se logical. If TRUE, confidence intervals are drawn.\n#' @inheritParams stats::glm\n#' @inheritParams stats::predict.glm\n#' @inheritParams stats::confint\n#' @importFrom stats glm predict\n#' @examples\n#' # \"glm\" type convenience string\n#' tinyplot(am ~ mpg, data = mtcars, type = \"glm\")\n#' \n#' # Use `type_glm()` to pass extra arguments for customization\n#' tinyplot(am ~ mpg, data = mtcars, type = type_glm(family = \"binomial\"))\n#' @export\ntype_glm = function(family = \"gaussian\", se = TRUE, level = 0.95, type = \"response\") {\n assert_flag(se)\n out = list(\n draw = draw_ribbon(),\n data = data_glm(family = family, se = se, level = level, type = type),\n name = if (isTRUE(se)) \"ribbon\" else \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_glm = function(family, se, level, type, ...) {\n fun = function(datapoints, ...) {\n dat = split(datapoints, list(datapoints$facet, datapoints$by))\n dat = lapply(dat, function(x) {\n if (nrow(x) == 0) return(x)\n if (nrow(x) < 3) {\n x$y = NA\n return(x)\n }\n fit = glm(y ~ x, data = x, family = family)\n nd = data.frame(x = seq(min(x$x, na.rm = TRUE), max(x$x, na.rm = TRUE), length.out = 100))\n nd$by = x$by[1]\n nd$facet = x$facet[1]\n if (se == TRUE) {\n if (identical(type, \"response\")) {\n p = predict(fit, newdata = nd, type = \"link\", se.fit = TRUE)\n p = ci(p$fit, p$se.fit, conf.level = level, fit$df.residual, backtransform = stats::family(fit)$linkinv)\n nd$y = p$estimate\n nd$ymax = p$conf.high\n nd$ymin = p$conf.low\n\n } else {\n nd$y = predict(fit, newdata = nd, type = type)\n nd = ci(nd$y, nd$se, level, fit$df.residual, backtransform = stats::family(fit)$linkinv)\n }\n } else {\n nd$y = predict(fit, nd, type = type)\n }\n nd\n })\n datapoints = do.call(rbind, dat)\n datapoints = datapoints[order(datapoints$facet, datapoints$by, datapoints$x), ]\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\n\n#' Calculate confidence intervals\n#' @importFrom stats qt\n#' @keywords internal\nci = function(estimate, std.error, conf.level, df, backtransform = identity) {\n crit = qt(1 - (1 - conf.level) / 2, df)\n out = list(\n estimate = backtransform(estimate),\n conf.low = backtransform(estimate - crit * std.error),\n conf.high = backtransform(estimate + crit * std.error)\n )\n return(out)\n}\n"], ["/tinyplot/R/type_rect.R", "#' Rectangle plot type\n#'\n#' @description Type function for plotting rectangles.\n#' \n#' @details Contrary to base \\code{\\link[graphics]{rect}}, rectangles in\n#' [tinyplot] must be specified using the `xmin`, `ymin`,`xmax`, and `ymax`\n#' arguments. \n#' \n#' @examples\n#' i = 4*(0:10)\n#' \n#' # \"rect\" type convenience character string\n#' tinyplot(\n#' xmin = 100+i, ymin = 300+i, xmax = 150+i, ymax = 380+i,\n#' by = i, fill = 0.2,\n#' type = \"rect\"\n#' )\n#' \n#' # Same result with type_rect()\n#' tinyplot(\n#' xmin = 100+i, ymin = 300+i, xmax = 150+i, ymax = 380+i,\n#' by = i, fill = 0.2,\n#' type = type_rect()\n#' )\n#' \n#' @export\ntype_rect = function() {\n out = list(\n draw = draw_rect(),\n data = NULL,\n name = \"rect\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_rect = function() {\n fun = function(ixmin, iymin, ixmax, iymax, ilty, ilwd, icol, ibg, ...) {\n rect(\n xleft = ixmin, ybottom = iymin, xright = ixmax, ytop = iymax,\n lty = ilty,\n lwd = ilwd,\n border = icol,\n col = ibg\n )\n }\n return(fun)\n}\n"], ["/tinyplot/R/setup_device.R", "setup_device = function(file, width, height) {\n # write to file\n if (!is.null(file)) {\n filepath = file\n filewidth = width\n fileheight = height\n if (is.null(filewidth)) filewidth = .tpar[[\"file.width\"]]\n if (is.null(fileheight)) fileheight = .tpar[[\"file.height\"]]\n fileres = .tpar[[\"file.res\"]]\n # catch to close interactive device if one isn't already open\n fkdev = is.null(dev.list())\n # grab existing device pars to pass on to next one\n dop = par(no.readonly = TRUE)\n # close interactive device if not already open\n if (isTRUE(fkdev)) dev.off()\n exttype = file_ext(filepath)\n if (exttype == \"pdf\" && .tpar[[\"cairo\"]]) {\n exttype = \"cairo\"\n } else if (exttype == \"jpg\") {\n exttype = \"jpeg\"\n }\n switch(exttype,\n png = png(filepath, width = filewidth, height = fileheight, units = \"in\", res = fileres),\n jpeg = jpeg(filepath, width = filewidth, height = fileheight, units = \"in\", res = fileres),\n pdf = pdf(filepath, width = filewidth, height = fileheight),\n cairo = cairo_pdf(filepath, width = filewidth, height = fileheight),\n svg = svg(filepath, width = filewidth, height = fileheight),\n stop(\"\\nUnsupported file extension. Only '.png', '.jpg', '.pdf', or '.svg' are allowed.\\n\")\n )\n dop$new = FALSE # catch for some interfaces\n par(dop)\n\n # interactive plot with user-specified width/height\n } else if (!is.null(width) || !is.null(height)) {\n devwidth = width\n devheight = height\n # if one of width or height is missing, set equal to the other\n if (is.null(devwidth)) devwidth = devheight\n if (is.null(devheight)) devheight = devwidth\n # catch to close interactive device if one isn't already open\n fkdev = is.null(dev.list())\n # grab existing device pars to pass on to next one\n dop = par(no.readonly = TRUE)\n # close interactive device if not already open\n if (isTRUE(fkdev)) dev.off()\n dev.new(width = devwidth, height = devheight)\n dop$new = FALSE # catch for some interfaces\n par(dop)\n }\n}\n"], ["/tinyplot/R/type_segments.R", "#' Line segments plot type\n#'\n#' @description Type function for plotting line segments.\n#' \n#' @details Contrary to base \\code{\\link[graphics]{segments}}, line segments in\n#' [tinyplot] must be specified using the `xmin`, `ymin`,`xmax`, and `ymax`\n#' arguments. \n#' \n#' @examples\n#' # \"segments\" type convenience character string\n#' tinyplot(\n#' xmin = c(0,.1), ymin = c(.2,1), xmax = c(1,.9), ymax = c(.75,0),\n#' type = \"segments\"\n#' )\n#' \n#' # Same result with type_segments()\n#' tinyplot(\n#' xmin = c(0,.1), ymin = c(.2,1), xmax = c(1,.9), ymax = c(.75,0),\n#' type = type_segments()\n#' )\n#' \n#' @export\ntype_segments = function() {\n out = list(\n draw = draw_segments(),\n data = NULL,\n name = \"segments\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_segments = function() {\n fun = function(ixmin, iymin, ixmax, iymax, ilty, ilwd, icol, ...) {\n segments(\n x0 = ixmin, y0 = iymin, x1 = ixmax, y1 = iymax,\n lty = ilty,\n lwd = ilwd,\n col = icol\n )\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_jitter.R", "#' Jittered points plot type\n#'\n#' @description Type function for plotting jittered points.\n#' Arguments are passed to \\code{\\link[base]{jitter}}.\n#'\n#' @inheritParams base::jitter\n#' @inherit base::jitter details\n#' @examples\n#' # \"jitter\" type convenience string\n#' tinyplot(Sepal.Length ~ Species, data = iris, type = \"jitter\")\n#' \n#' # Use `type_jitter()` to pass extra arguments for customization\n#' tinyplot(Sepal.Length ~ Species, data = iris, type = type_jitter(factor = 0.5))\n#' @export\ntype_jitter = function(factor = 1, amount = NULL) {\n out = list(\n draw = draw_points(),\n data = data_jitter(factor = factor, amount = amount),\n name = \"p\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_jitter = function(factor, amount) {\n fun = function(datapoints, ...) {\n x = datapoints$x\n y = datapoints$y\n if (is.factor(x)) {\n xlvls = levels(x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n x = as.integer(x)\n } else {\n xlabs = NULL\n }\n if (is.factor(y)) {\n ylvls = levels(y)\n ylabs = seq_along(ylvls)\n names(ylabs) = ylvls\n y = as.integer(y)\n } else {\n ylabs = NULL\n }\n x = jitter(x, factor = factor, amount = amount)\n y = jitter(y, factor = factor, amount = amount)\n\n datapoints$x = x\n datapoints$y = y\n\n out = list(\n datapoints = datapoints,\n x = x,\n y = y,\n xlabs = xlabs,\n ylabs = ylabs\n )\n return(out)\n }\n}\n\n"], ["/tinyplot/R/type_lm.R", "#' Linear model plot type\n#'\n#' @description Type function for plotting a linear model fit.\n#' Arguments are passed to \\code{\\link[stats]{lm}}.\n#' \n#' @inheritParams type_glm\n#' @importFrom stats lm predict\n#' @examples\n#' # \"lm\" type convenience string\n#' tinyplot(Sepal.Width ~ Petal.Width, data = iris, type = \"lm\")\n#' \n#' # Grouped model fits (here: illustrating an example of Simpson's paradox)\n#' tinyplot(Sepal.Width ~ Petal.Width | Species, data = iris, type = \"lm\")\n#' tinyplot_add(type = \"p\")\n#' \n#' # Use `type_lm()` to pass extra arguments for customization\n#' tinyplot(Sepal.Width ~ Petal.Width, data = iris, type = type_lm(level = 0.8))\n#' @export\ntype_lm = function(se = TRUE, level = 0.95) {\n assert_flag(se)\n out = list(\n draw = draw_ribbon(),\n data = data_lm(se = se, level = level),\n name = if (isTRUE(se)) \"ribbon\" else \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_lm = function(se, level, ...) {\n fun = function(datapoints, ...) {\n dat = split(datapoints, list(datapoints$facet, datapoints$by))\n dat = lapply(dat, function(x) {\n if (nrow(x) == 0) return(x)\n if (nrow(x) < 3) {\n x$y = NA\n return(x)\n }\n fit = lm(y ~ x, data = x)\n nd = data.frame(x = seq(min(x$x, na.rm = TRUE), max(x$x, na.rm = TRUE), length.out = 100))\n nd$by = x$by[1]\n nd$facet = x$facet[1]\n if (se == TRUE) {\n p = predict(fit, newdata = nd, se.fit = TRUE)\n p = ci(p$fit, p$se.fit, conf.level = level, fit$df.residual)\n nd$y = p$estimate\n nd$ymax = p$conf.high\n nd$ymin = p$conf.low\n } else {\n nd$y = predict(fit, newdata = nd)\n }\n nd\n })\n datapoints = do.call(rbind, dat)\n datapoints = datapoints[order(datapoints$facet, datapoints$by, datapoints$x), ]\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_loess.R", "#' Local polynomial regression plot type\n#' \n#' @description Type function for plotting a LOESS (LOcal regrESSion) fit.\n#' Arguments are passed to \\code{\\link[stats]{loess}}.\n#' \n#' @inheritParams stats::loess\n#' @param se logical. If `TRUE` (the default), confidence intervals are drawn.\n#' @param level the confidence level required if `se = TRUE`. Default is 0.95.\n#' @importFrom stats loess loess.control predict\n#' @examples\n#' # \"loess\" type convenience string\n#' tinyplot(dist ~ speed, data = cars, type = \"loess\")\n#' \n#' # Use `type_loess()` to pass extra arguments for customization\n#' tinyplot(dist ~ speed, data = cars, type = type_loess(span = 0.5, degree = 1))\n#' @export\ntype_loess = function(\n span = 0.75,\n degree = 2,\n family = \"gaussian\",\n control = loess.control(),\n se = TRUE,\n level = 0.95\n ) {\n out = list(\n draw = draw_ribbon(),\n data = data_loess(span = span, degree = degree, family = family, control = control, se = se, level = level),\n name = if (isTRUE(se)) \"ribbon\" else \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_loess = function(span, degree, family, control, se, level, ...) {\n fun = function(datapoints, ...) {\n datapoints = split(datapoints, list(datapoints$facet, datapoints$by))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n datapoints = lapply(datapoints, function(dat) {\n fit = loess(y ~ x, data = dat, span = span, degree = degree, family = family, control = control)\n if (se == TRUE) {\n p = predict(fit, newdata = dat, se = TRUE)\n p = ci(p$fit, p$se.fit, conf.level = level, p$df)\n dat$y = p$estimate\n dat$ymax = p$conf.high\n dat$ymin = p$conf.low\n } else {\n dat$y = predict(fit, dat)\n }\n dat\n })\n datapoints = do.call(rbind, datapoints)\n datapoints = datapoints[order(datapoints$facet, datapoints$by, datapoints$x), ]\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_spline.R", "#' Spline plot type\n#' \n#' @description Type function for plotting a cubic (or Hermite) spline interpolation.\n#' Arguments are passed to \\code{\\link[stats]{spline}}; see this latter function\n#' for default argument values.\n#' \n#' @inheritParams stats::spline\n#' @inherit stats::spline details\n#' @importFrom stats spline\n#' @examples\n#' # \"spline\" type convenience string\n#' tinyplot(dist ~ speed, data = cars, type = \"spline\")\n#' \n#' # Use `type_spline()` to pass extra arguments for customization\n#' tinyplot(dist ~ speed, data = cars, type = type_spline(method = \"natural\", n = 25),\n#' add = TRUE, lty = 2)\n#' @export\ntype_spline = function(\n n = NULL,\n method = \"fmm\",\n xmin = NULL,\n xmax = NULL,\n xout = NULL,\n ties = mean\n ) {\n out = list(\n draw = draw_lines(),\n data = data_spline(method = method, ties = ties, n = n, xmin = xmin, xmax = xmax, xout = xout),\n name = \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_spline = function(n, method, xmin, xmax, xout, ties, ...) {\n fun = function(datapoints, ...) {\n datapoints = split(datapoints, list(datapoints$facet, datapoints$by), drop = TRUE)\n datapoints = lapply(datapoints, function(dat) {\n if (is.null(n)) n = 3*length(dat$x)\n if (is.null(xmax)) xmax = max(dat$x)\n if (is.null(xmin)) xmin = min(dat$x)\n if (is.null(xout)) {\n fit = spline(x = dat$x, y = dat$y, n = n, method = method, xmin = xmin, xmax = xmax, ties = ties)\n } else {\n fit = spline(x = dat$x, y = dat$y, n = n, method = method, xmin = xmin, xmax = xmax, xout = xout, ties = ties)\n }\n fit = as.data.frame(fit)\n fit$facet = dat$facet[1]\n fit$by = dat$by[1]\n fit\n return(fit)\n })\n datapoints = do.call(rbind, datapoints)\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/sanitize.R", "sanitize_ribbon.alpha = function(ribbon.alpha) {\n assert_numeric(ribbon.alpha, len = 1, lower = 0, upper = 1, null.ok = TRUE)\n if (is.null(ribbon.alpha)) ribbon.alpha = .tpar[[\"ribbon.alpha\"]]\n return(ribbon.alpha)\n}\n\n\n\nsanitize_type = function(type, x, y, dots) {\n if (inherits(type, \"tinyplot_type\")) {\n return(type)\n }\n\n known_types = c(\n \"p\", \"l\", \"o\", \"b\", \"c\", \"h\", \"j\", \"s\", \"S\", \"n\", \n \"abline\",\n \"area\",\n \"bar\", \"barplot\",\n \"box\", \"boxplot\",\n \"density\",\n \"errorbar\",\n \"function\",\n \"glm\",\n \"hist\", \"histogram\",\n \"hline\",\n \"j\", \"jitter\",\n \"lines\",\n \"lm\",\n \"loess\",\n \"pointrange\",\n \"points\",\n \"polygon\", \"polypath\",\n \"qq\",\n \"rect\",\n \"ribbon\",\n \"ridge\",\n \"rug\",\n \"segments\",\n \"spine\", \"spineplot\",\n \"spline\",\n \"summary\",\n \"text\",\n \"violin\",\n \"vline\"\n )\n assert_choice(type, known_types, null.ok = TRUE)\n\n if (is.null(type)) {\n if (!is.null(x) && (is.factor(x) || is.character(x)) && !(is.factor(y) || is.character(y))) {\n # enforce boxplot type for y ~ factor(x)\n type = type_boxplot\n } else if (is.factor(y) || is.character(y)) {\n # enforce spineplot type for factor(y) ~ x\n type = type_spineplot\n } else {\n type = \"p\"\n }\n }\n\n if (is.character(type)) type = switch(type,\n \"abline\" = type_abline,\n \"area\" = type_area,\n \"bar\" = type_barplot,\n \"barplot\" = type_barplot,\n \"box\" = type_boxplot,\n \"boxplot\" = type_boxplot,\n \"density\" = type_density,\n \"errorbar\" = type_errorbar,\n \"function\" = type_function,\n \"glm\" = type_glm,\n \"hist\" = type_histogram,\n \"histogram\" = type_histogram,\n \"hline\" = type_hline,\n \"j\" = type_jitter,\n \"jitter\" = type_jitter,\n \"lines\" = type_lines,\n \"lm\" = type_lm,\n \"loess\" = type_loess,\n \"p\" = type_points,\n \"pointrange\" = type_pointrange,\n \"points\" = type_points,\n \"polygon\" = type_polygon,\n \"polypath\" = type_polypath,\n \"qq\" = type_qq,\n \"rect\" = type_rect,\n \"ribbon\" = type_ribbon,\n \"ridge\" = type_ridge,\n \"rug\" = type_rug,\n \"segments\" = type_segments,\n \"spine\" = type_spineplot,\n \"spineplot\" = type_spineplot,\n \"spline\" = type_spline,\n \"summary\" = type_summary,\n \"text\" = type_text,\n \"violin\" = type_violin,\n \"vline\" = type_vline,\n type # default case\n )\n \n if (is.function(type)) {\n args = intersect(names(formals(type)), names(dots))\n args = if (length(args) >= 1L) dots[args] else list()\n type = do.call(type, args)\n type$dots = dots[setdiff(names(dots), names(args))]\n }\n \n if (inherits(type, \"tinyplot_type\")) return(type)\n\n out = list(draw = NULL, data = NULL, name = type)\n return(out)\n}\n"], ["/tinyplot/R/type_polygon.R", "#' Polygon plot type\n#'\n#' @description Type function for plotting polygons.\n#' Arguments are passed to \\code{\\link[graphics]{polygon}}.\n#' \n#' @inheritParams graphics::polygon\n#' \n#' @examples\n#' # \"polygon\" type convenience character string\n#' tinyplot(1:9, c(2,1,2,1,NA,2,1,2,1), type = \"polygon\")\n#' \n#' # Use `type_polygon()` to pass extra arguments for customization\n#' tinyplot(1:9, c(2,1,2,1,NA,2,1,2,1), type = type_polygon(density = c(10, 20)))\n#' \n#' @export\ntype_polygon = function(density = NULL, angle = 45) {\n out = list(\n draw = draw_polygon(density = density, angle = angle),\n data = NULL,\n name = \"polygon\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_polygon = function(density = density, angle = 45) {\n fun = function(ix, iy, icol, ibg, ilty = par(\"lty\"), ilwd = par(\"lwd\"), ...) {\n polygon(\n x = ix,\n y = iy,\n border = icol,\n col = ibg,\n lty = ilty,\n lwd = ilwd,\n density = density,\n angle = angle\n )\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_lines.R", "#' Lines plot type\n#'\n#' @description Type function for plotting lines.\n#' \n#' @inheritParams graphics::plot.default\n#' \n#' @examples\n#' # \"l\" type convenience character string\n#' tinyplot(circumference ~ age | Tree, data = Orange, type = \"l\")\n#' \n#' # Use `type_lines()` to pass extra arguments for customization\n#' tinyplot(circumference ~ age | Tree, data = Orange, type = type_lines(type = \"s\"))\n#' \n#' @export\ntype_lines = function(type = \"l\") {\n out = list(\n draw = draw_lines(type = type),\n data = NULL,\n name = type\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_lines = function(type = \"l\") {\n fun = function(ix, iy, icol, ipch, ibg, ilty, ilwd, cex = 1, ...) {\n lines(\n x = ix,\n y = iy,\n col = icol,\n type = type,\n pch = ipch,\n bg = ibg,\n lty = ilty,\n lwd = ilwd,\n cex = cex\n )\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_pointrange.R", "#' @rdname type_errorbar\n#' @export\ntype_pointrange = function() {\n out = list(\n draw = draw_pointrange(),\n data = data_pointrange(),\n name = \"p\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\n\ndraw_pointrange = function() {\n fun = function(ix, iy, ixmin, iymin, ixmax, iymax, icol, ibg, ipch, ilwd, cex, ...) {\n segments(\n x0 = ixmin,\n y0 = iymin,\n x1 = ixmax,\n y1 = iymax,\n col = icol,\n lwd = ilwd\n )\n draw_points()(ix = ix, iy = iy, icol = icol, ibg = ibg, ipch = ipch, ilwd = ilwd, cex = cex)\n }\n return(fun)\n}\n\n\ndata_pointrange = function() {\n fun = function(datapoints, xlabs, ...) {\n if (is.character(datapoints$x)) datapoints$x = as.factor(datapoints$x)\n if (is.factor(datapoints$x)) {\n ## original data (i.e., no new sorting by factor)\n xlvls = unique(datapoints$x)\n datapoints$x = factor(datapoints$x, levels = xlvls)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n datapoints$x = as.integer(datapoints$x)\n }\n datapoints$xmin = datapoints$x\n datapoints$xmax = datapoints$x\n out = list(\n x = datapoints$x,\n xlabs = xlabs,\n datapoints = datapoints)\n\n return(out)\n }\n return(fun)\n}\n"], ["/tinyplot/R/lim.R", "# calculate limits of each plot\n\nlim_args = function(\n datapoints,\n xlim, ylim,\n xaxb = NULL, yaxb = NULL,\n xlim_user = FALSE, ylim_user = FALSE,\n type\n) {\n \n if (is.null(xlim)) {\n xlim = range(c(datapoints[[\"x\"]], datapoints[[\"xmin\"]],\n datapoints[[\"xmax\"]]), finite = TRUE)\n }\n if (is.null(ylim)) {\n ylim = range(c(datapoints[[\"y\"]], datapoints[[\"ymin\"]],\n datapoints[[\"ymax\"]]), finite = TRUE)\n }\n\n if (identical(type, \"boxplot\")) {\n xlim = xlim + c(-0.5, 0.5)\n }\n \n if (!xlim_user && !is.null(xaxb) && type != \"spineplot\") xlim = range(c(xlim, xaxb))\n if (!ylim_user && !is.null(yaxb) && type != \"spineplot\") ylim = range(c(ylim, yaxb))\n\n out = list(xlim = xlim, ylim = ylim)\n return(out)\n}\n\n"], ["/tinyplot/R/type_area.R", "#' @rdname type_ribbon\n#' @export\ntype_area = function(alpha = NULL) {\n out = list(\n draw = NULL,\n data = data_area(alpha = alpha),\n name = \"area\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_area = function(alpha = alpha) {\n ribbon.alpha = if (is.null(alpha)) .tpar[[\"ribbon.alpha\"]] else (alpha)\n fun = function(datapoints, ...) {\n datapoints$ymax = datapoints$y\n datapoints$ymin = rep.int(0, nrow(datapoints))\n out = list(\n datapoints = datapoints,\n ymax = datapoints$ymax,\n ymin = datapoints$ymin,\n type = \"ribbon\",\n ribbon.alpha = ribbon.alpha\n )\n return(out)\n }\n return(fun)\n}\n"], ["/tinyplot/R/environment.R", "init_environment = function() {\n tnypltptns = parent.env(environment())\n assign(\".tinyplot_env\", new.env(), envir = tnypltptns)\n .tpar = new.env()\n assign(\".tpar\", .tpar, envir = tnypltptns)\n}\n\nget_environment_variable = function(name) {\n get(name, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n}\n\nset_environment_variable = function(name, value) {\n assign(name, value, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n}\n"], ["/tinyplot/R/type_polypath.R", "#' Polypath polygon type\n#' \n#' @description Type function for plotting polygons.\n#' Arguments are passed to \\code{\\link[graphics]{polypath}}.\n#' \n#' @inheritParams graphics::polypath\n#' \n#' @examples\n#' # \"polypath\" type convenience character string\n#' tinyplot(\n#' c(.1, .1, .6, .6, NA, .4, .4, .9, .9),\n#' c(.1, .6, .6, .1, NA, .4, .9, .9, .4),\n#' type = \"polypath\", fill = \"grey\"\n#' )\n#' \n#' # Use `type_polypath()` to pass extra arguments for customization\n#' tinyplot(\n#' c(.1, .1, .6, .6, NA, .4, .4, .9, .9),\n#' c(.1, .6, .6, .1, NA, .4, .9, .9, .4),\n#' type = type_polypath(rule = \"evenodd\"), fill = \"grey\"\n#' )\n#' @export\ntype_polypath = function(rule = \"winding\") {\n draw_polypath = function() {\n fun = function(ix, iy, icol, ibg, ilty, ilwd, dots, ...) {\n polypath(\n x = ix,\n y = iy,\n border = icol,\n col = ibg,\n lty = ilty,\n lwd = ilwd,\n rule = rule\n )\n }\n return(fun)\n }\n\n out = list(\n draw = draw_polypath(),\n data = NULL,\n name = \"polypath\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n"], ["/tinyplot/R/tinyplot-package.R", "#' @keywords internal\n\"_PACKAGE\"\n\nNULL\n"], ["/tinyplot/R/type_errorbar.R", "#' Error bar and pointrange plot types\n#' \n#' @description Type function(s) for producing error bar and pointrange plots.\n#' \n#' @inheritParams graphics::arrows\n#' @examples\n#' mod = lm(mpg ~ wt * factor(am), mtcars)\n#' coefs = data.frame(names(coef(mod)), coef(mod), confint(mod))\n#' colnames(coefs) = c(\"term\", \"est\", \"lwr\", \"upr\")\n#' \n#' op = tpar(pch = 19)\n#' \n#' # \"errorbar\" and \"pointrange\" type convenience strings\n#' tinyplot(est ~ term, ymin = lwr, ymax = upr, data = coefs, type = \"errorbar\")\n#' tinyplot(est ~ term, ymin = lwr, ymax = upr, data = coefs, type = \"pointrange\")\n#' \n#' # Use `type_errorbar()` to pass extra arguments for customization\n#' tinyplot(est ~ term, ymin = lwr, ymax = upr, data = coefs, type = type_errorbar(length = 0.2))\n#' \n#' tpar(op)\n#' \n#' @export\ntype_errorbar = function(length = 0.05) {\n out = list(\n draw = draw_errorbar(length = length),\n data = data_pointrange(),\n name = \"p\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_errorbar = function(length = 0.05) {\n fun = function(ix, iy, ixmin, iymin, ixmax, iymax, icol, ibg, ipch, ilwd, cex, ...) {\n arrows(\n x0 = ixmin,\n y0 = iymin,\n x1 = ixmax,\n y1 = iymax,\n col = icol,\n lwd = ilwd,\n length = length,\n angle = 90,\n code = 3\n )\n draw_points()(ix = ix, iy = iy, icol = icol, ibg = ibg, ipch = ipch, ilwd = ilwd, cex = cex)\n }\n return(fun)\n}\n\n\n"]], "task_instance_info": {"created_time": "2025-08-21 01:20:28", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(hooks) {}", "code_description": "This code segment functions to: Reverse previously registered operations by selectively removing specified entries from a dynamically managed collection based on identity checks and updating the underlying storage mechanism accordingly."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nfunction(hooks) {\n for (hook_name in names(hooks)) {\n setHook(hook_name, hooks[[hook_name]], action = \"replace\")\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-20-50"}, "editdistance_info": {"edit_distance": 34.5238, "calculate_time": "2025-08-21 01:20:50", "true_code_clean": "function(hooks) {\n for (hook_name in names(hooks)) {\n hook <- getHook(hook_name)\n if (length(hook) > 0) {\n for (fun in unlist(hooks[hook_name])) {\n hook[sapply(hook, identical, fun)] <- NULL\n }\n }\n setHook(hook_name, hook, \"replace\")\n }\n}", "predict_code_clean": "function(hooks) {\n for (hook_name in names(hooks)) {\n setHook(hook_name, hooks[[hook_name]], action = \"replace\")\n }\n}"}} {"repo_name": "tinyplot", "file_name": "/tinyplot/R/type_lines.R", "inference_info": {"prefix_code": "#' Lines plot type\n#'\n#' @description Type function for plotting lines.\n#' \n#' @inheritParams graphics::plot.default\n#' \n#' @examples\n#' # \"l\" type convenience character string\n#' tinyplot(circumference ~ age | Tree, data = Orange, type = \"l\")\n#' \n#' # Use `type_lines()` to pass extra arguments for customization\n#' tinyplot(circumference ~ age | Tree, data = Orange, type = type_lines(type = \"s\"))\n#' \n#' @export\ntype_lines = function(type = \"l\") {\n out = list(\n draw = draw_lines(type = type),\n data = NULL,\n name = type\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_lines = ", "suffix_code": "\n", "middle_code": "function(type = \"l\") {\n fun = function(ix, iy, icol, ipch, ibg, ilty, ilwd, cex = 1, ...) {\n lines(\n x = ix,\n y = iy,\n col = icol,\n type = type,\n pch = ipch,\n bg = ibg,\n lty = ilty,\n lwd = ilwd,\n cex = cex\n )\n }\n return(fun)\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/tinyplot/R/type_errorbar.R", "#' Error bar and pointrange plot types\n#' \n#' @description Type function(s) for producing error bar and pointrange plots.\n#' \n#' @inheritParams graphics::arrows\n#' @examples\n#' mod = lm(mpg ~ wt * factor(am), mtcars)\n#' coefs = data.frame(names(coef(mod)), coef(mod), confint(mod))\n#' colnames(coefs) = c(\"term\", \"est\", \"lwr\", \"upr\")\n#' \n#' op = tpar(pch = 19)\n#' \n#' # \"errorbar\" and \"pointrange\" type convenience strings\n#' tinyplot(est ~ term, ymin = lwr, ymax = upr, data = coefs, type = \"errorbar\")\n#' tinyplot(est ~ term, ymin = lwr, ymax = upr, data = coefs, type = \"pointrange\")\n#' \n#' # Use `type_errorbar()` to pass extra arguments for customization\n#' tinyplot(est ~ term, ymin = lwr, ymax = upr, data = coefs, type = type_errorbar(length = 0.2))\n#' \n#' tpar(op)\n#' \n#' @export\ntype_errorbar = function(length = 0.05) {\n out = list(\n draw = draw_errorbar(length = length),\n data = data_pointrange(),\n name = \"p\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_errorbar = function(length = 0.05) {\n fun = function(ix, iy, ixmin, iymin, ixmax, iymax, icol, ibg, ipch, ilwd, cex, ...) {\n arrows(\n x0 = ixmin,\n y0 = iymin,\n x1 = ixmax,\n y1 = iymax,\n col = icol,\n lwd = ilwd,\n length = length,\n angle = 90,\n code = 3\n )\n draw_points()(ix = ix, iy = iy, icol = icol, ibg = ibg, ipch = ipch, ilwd = ilwd, cex = cex)\n }\n return(fun)\n}\n\n\n"], ["/tinyplot/R/type_ribbon.R", "#' Ribbon and area plot types\n#' \n#' @param alpha numeric value between 0 and 1 specifying the opacity of ribbon shading\n#' If no `alpha` value is provided, then will default to `tpar(\"ribbon.alpha\")` \n#' (i.e., probably `0.2` unless this has been overridden by the user in their global \n#' settings.)\n#'\n#' @description Type constructor functions for producing polygon ribbons, which \n#' define a `y` interval (usually spanning from `ymin` to `ymax`) for each\n#' `x` value. Area plots are a special case of ribbon plot where `ymin` is\n#' set to 0 and `ymax` is set to `y`.\n#' \n#' @examples\n#' x = 1:100/10\n#' y = sin(x)\n#' \n#' #\n#' ## Ribbon plots\n#' \n#' # \"ribbon\" convenience string\n#' tinyplot(x = x, ymin = y-1, ymax = y+1, type = \"ribbon\")\n\n#' # Same result with type_ribbon()\n#' tinyplot(x = x, ymin = y-1, ymax = y+1, type = type_ribbon())\n#' \n#' # y will be added as a line if it is specified\n#' tinyplot(x = x, y = y, ymin = y-1, ymax = y+1, type = \"ribbon\")\n#'\n#' #\n#' ## Area plots\n#' \n#' # \"area\" type convenience string\n#' tinyplot(x, y, type = \"area\")\n#' \n#' # Same result with type_area()\n#' tinyplot(x, y, type = type_area())\n#' \n#' # Area plots are often used for time series charts\n#' tinyplot(AirPassengers, type = \"area\")\n#' @export\ntype_ribbon = function(alpha = NULL) {\n out = list(\n draw = draw_ribbon(),\n data = data_ribbon(ribbon.alpha = alpha),\n name = \"ribbon\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_ribbon = function() {\n fun = function(ix, iy, ixmin, ixmax, iymin, iymax, ibg, ilty, ilwd, icol, ipch, i, flip = FALSE, ...) {\n polyg = type_polygon()$draw\n lin = type_lines()$draw\n if (isFALSE(flip)) {\n polyg(ix = c(ix, rev(ix)), iy = c(iymin, rev(iymax)), icol = NA, ibg = ibg)\n } else {\n polyg(c(ixmin, rev(ixmax)), iy = c(iy, rev(iy)), icol = NA, ibg = ibg)\n }\n lin(ix = ix, iy = iy, icol = icol, ipch = ipch, ibg = ibg, ilty = ilty, ilwd = ilwd, type = \"l\")\n }\n return(fun)\n}\n\n\ndata_ribbon = function(ribbon.alpha = NULL) {\n ribbon.alpha = sanitize_ribbon.alpha(ribbon.alpha)\n fun = function(datapoints, xlabs, null_by, null_facet, ...) {\n # Convert x to factor if it's not already\n if (is.character(datapoints$x)) {\n datapoints$x = as.factor(datapoints$x)\n }\n\n if (is.factor(datapoints$x)) {\n xlvls = levels(datapoints$x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n datapoints$x = as.integer(datapoints$x)\n } else {\n xlabs = NULL\n }\n\n if (null_by && null_facet) {\n xord = order(datapoints$x)\n } else if (null_facet) {\n xord = order(datapoints$by, datapoints$x)\n } else if (null_by) {\n xord = order(datapoints$facet, datapoints$x)\n } else {\n xord = order(datapoints$by, datapoints$facet, datapoints$x)\n }\n\n # Reorder x, y, ymin, and ymax based on the order determined\n datapoints = datapoints[xord,]\n\n # Catch for missing ymin and ymax \n if (is.null(datapoints$ymin)) datapoints$ymin = datapoints$y \n if (is.null(datapoints$ymax)) datapoints$ymax = datapoints$y\n\n out = list(\n x = datapoints$x,\n y = datapoints$y,\n ymin = datapoints$ymin,\n ymax = datapoints$ymax,\n xlabs = xlabs,\n datapoints = datapoints,\n ribbon.alpha = ribbon.alpha)\n\n if (length(unique(datapoints$by)) > 1) out[[\"by\"]] = datapoints$by\n if (length(unique(datapoints$facet)) > 1) out[[\"facet\"]] = datapoints$facet\n\n return(out)\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_boxplot.R", "#' Boxplot type\n#' \n#' @description Type function for producing box-and-whisker plots.\n#' Arguments are passed to \\code{\\link[graphics]{boxplot}}, although `tinyplot`\n#' scaffolding allows added functionality such as grouping and faceting.\n#' Box-and-whisker plots are the default plot type if `x` is a factor and `y` is\n#' numeric.\n#'\n#' @inheritParams graphics::boxplot\n#' @examples\n#' # \"boxplot\" type convenience string\n#' tinyplot(count ~ spray, data = InsectSprays, type = \"boxplot\")\n#' \n#' # Note: Specifying the type here is redundant. Like base plot, tinyplot\n#' # automatically produces a boxplot if x is a factor and y is numeric\n#' tinyplot(count ~ spray, data = InsectSprays)\n#' \n#' # Grouped boxplot example\n#' tinyplot(len ~ dose | supp, data = ToothGrowth, type = \"boxplot\")\n#' \n#' # Use `type_boxplot()` to pass extra arguments for customization\n#' tinyplot(\n#' len ~ dose | supp, data = ToothGrowth, lty = 1,\n#' type = type_boxplot(boxwex = 0.3, staplewex = 0, outline = FALSE)\n#' )\n#' @export\ntype_boxplot = function(\n range = 1.5,\n width = NULL,\n varwidth = FALSE,\n notch = FALSE,\n outline = TRUE,\n boxwex = 0.8,\n staplewex = 0.5,\n outwex = 0.5) {\n out = list(\n draw = draw_boxplot(\n range = range,\n width = width,\n varwidth = varwidth,\n notch = notch,\n outline = outline,\n boxwex = boxwex,\n staplewex = staplewex,\n outwex = outwex),\n data = data_boxplot(),\n name = \"boxplot\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\n\ndraw_boxplot = function(range, width, varwidth, notch, outline, boxwex, staplewex, outwex) {\n fun = function(iby, ix, iy, ipch, ilty, icol, ibg, x_by = FALSE, facet_by = FALSE, ngrps = 1, flip, ...) {\n\n at_ix = unique(ix)\n if (isTRUE(x_by)) boxwex = boxwex * 2\n\n # Handle multiple groups\n if (ngrps > 1 && isFALSE(x_by) && isFALSE(facet_by)) {\n boxwex_orig = boxwex\n boxwex = boxwex / ngrps - 0.01\n at_ix = at_ix + seq(\n -((boxwex_orig - boxwex) / 2),\n ((boxwex_orig - boxwex) / 2),\n length.out = ngrps\n )[iby]\n }\n\n boxplot(\n formula = iy ~ ix,\n pch = ipch,\n lty = ilty,\n border = icol,\n col = ibg,\n horizontal = flip,\n add = TRUE, axes = FALSE,\n at = at_ix,\n range = range,\n width = width,\n varwidth = varwidth,\n notch = notch,\n outline = outline,\n boxwex = boxwex,\n staplewex = staplewex,\n outwex = outwex\n )\n }\n return(fun)\n}\n\n\n\ndata_boxplot = function() {\n fun = function(datapoints, bg, col, palette, null_by, null_facet, ...) {\n # Convert x to factor if it's not already\n datapoints$x = as.factor(datapoints$x)\n\n # Handle factor levels and maintain order\n xlvls = levels(datapoints$x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n datapoints$x = as.integer(datapoints$x)\n\n if (null_by && null_facet) {\n xord = order(datapoints$x)\n } else if (null_facet) {\n xord = order(datapoints$by, datapoints$x)\n } else if (null_by) {\n xord = order(datapoints$facet, datapoints$x)\n } else {\n xord = order(datapoints$by, datapoints$facet, datapoints$x)\n }\n\n if (length(unique(datapoints[[\"by\"]])) == 1 && is.null(palette)) {\n if (is.null(col)) col = par(\"fg\")\n if (is.null(bg)) bg = \"lightgray\"\n } else {\n bg = \"by\"\n }\n\n # Reorder x, y, ymin, and ymax based on the order determined\n datapoints = datapoints[xord,]\n\n # Return the result as a list called 'out'\n out = list(\n x = datapoints$x,\n y = datapoints$y,\n ymin = datapoints$ymin,\n ymax = datapoints$ymax,\n xlabs = xlabs,\n datapoints = datapoints,\n col = col,\n bg = bg)\n\n if (length(unique(datapoints$by)) > 1) out[[\"by\"]] = datapoints$by\n if (length(unique(datapoints$facet)) > 1) out[[\"facet\"]] = datapoints$facet\n\n return(out)\n }\n return(fun)\n}\n\n\n\n\n"], ["/tinyplot/R/tinyplot.R", "#' @title Lightweight extension of the base R plotting function\n#'\n#' @description\n#' Enhances the base \\code{\\link[graphics]{plot}} function. Supported features\n#' include automatic legends and facets for grouped data, additional plot types,\n#' theme customization, and so on. Users can call either `tinyplot()`, or its\n#' shorthand alias `plt()`.\n#'\n#' @md\n#' @param x,y the x and y arguments provide the x and y coordinates for the\n#' plot. Any reasonable way of defining the coordinates is acceptable; most\n#' likely the names of existing vectors or columns of data frames. See the\n#' 'Examples' section below, or the function\n#' \\code{\\link[grDevices]{xy.coords}} for details. If supplied separately, `x`\n#' and `y` must be of the same length.\n#' @param xmin,xmax,ymin,ymax minimum and maximum coordinates of relevant area\n#' or interval plot types. Only used when the `type` argument is one of\n#' `\"rect\"` or `\"segments\"` (where all four min-max coordinates are required),\n#' or `\"pointrange\"`, `\"errorbar\"`, or `\"ribbon\"` (where only `ymin` and\n#' `ymax` required alongside `x`). In the formula method the arguments\n#' can be specified as `ymin = var` if `var` is a variable in `data`.\n#' @param by grouping variable(s). The default behaviour is for groups to be\n#' represented in the form of distinct colours, which will also trigger an\n#' automatic legend. (See `legend` below for customization options.) However,\n#' groups can also be presented through other plot parameters (e.g., `pch` or\n#' `lty`) by passing an appropriate \"by\" keyword; see Examples. Note that\n#' continuous (i.e., gradient) colour legends are also supported if the user\n#' passes a numeric or integer to `by`. To group by multiple variables, wrap\n#' them with \\code{\\link[base]{interaction}}.\n#' @param facet the faceting variable(s) that you want arrange separate plot\n#' windows by. Can be specified in various ways:\n#' - In \"atomic\" form, e.g. `facet = fvar`. To facet by multiple variables in\n#' atomic form, simply interact them, e.g.\n#' `interaction(fvar1, fvar2)` or `factor(fvar1):factor(fvar2)`.\n#' - As a one-sided formula, e.g. `facet = ~fvar`. Multiple variables can be\n#' specified in the formula RHS, e.g. `~fvar1 + fvar2` or `~fvar1:fvar2`. Note\n#' that these multi-variable cases are _all_ treated equivalently and\n#' converted to `interaction(fvar1, fvar2, ...)` internally. (No distinction\n#' is made between different types of binary operators, for example, and so\n#' `f1+f2` is treated the same as `f1:f2`, is treated the same as `f1*f2`,\n#' etc.)\n#' - As a two-side formula, e.g. `facet = fvar1 ~ fvar2`. In this case, the\n#' facet windows are arranged in a fixed grid layout, with the formula LHS\n#' defining the facet rows and the RHS defining the facet columns. At present\n#' only single variables on each side of the formula are well supported. (We\n#' don't recommend trying to use multiple variables on either the LHS or RHS\n#' of the two-sided formula case.)\n#' - As a special `\"by\"` convenience keyword, in which case facets will match\n#' the grouping variable(s) passed to `by` above.\n#' @param facet.args an optional list of arguments for controlling faceting\n#' behaviour. (Ignored if `facet` is NULL.) Supported arguments are as\n#' follows:\n#' - `nrow`, `ncol` for overriding the default \"square\" facet window\n#' arrangement. Only one of these should be specified, but `nrow` will take\n#' precedence if both are specified together. Ignored if a two-sided formula\n#' is passed to the main `facet` argument, since the layout is arranged in a\n#' fixed grid.\n#' - `free` a logical value indicating whether the axis limits (scales) for\n#' each individual facet should adjust independently to match the range of\n#' the data within that facet. Default is `FALSE`. Separate free scaling of\n#' the x- or y-axis (i.e., whilst holding the other axis fixed) is not\n#' currently supported.\n#' - `fmar` a vector of form `c(b,l,t,r)` for controlling the base margin\n#' between facets in terms of lines. Defaults to the value of `tpar(\"fmar\")`,\n#' which should be `c(1,1,1,1)`, i.e. a single line of padding around each\n#' individual facet, assuming it hasn't been overridden by the user as part\n#' their global \\code{\\link[tinyplot]{tpar}} settings. Note some automatic\n#' adjustments are made for certain layouts, and depending on whether the plot\n#' is framed or not, to reduce excess whitespace. See\n#' \\code{\\link[tinyplot]{tpar}} for more details.\n#' - `cex`, `font`, `col`, `bg`, `border` for adjusting the facet title text\n#' and background. Default values for these arguments are inherited from\n#' \\code{\\link[tinyplot]{tpar}} (where they take a \"facet.\" prefix, e.g.\n#' `tpar(\"facet.cex\")`). The latter function can also be used to set these\n#' features globally for all `tinyplot` plots.\n#' @param formula a \\code{\\link[stats]{formula}} that optionally includes\n#' grouping variable(s) after a vertical bar, e.g. `y ~ x | z`. One-sided\n#' formulae are also permitted, e.g. `~ y | z`. Only a single `y` and `x`\n#' variable (if any) must be specified but multiple grouping variables\n#' can be included in different ways, e.g. `y ~ x | z1:z2` or\n#' `y ~ x | z1 + z2`. (These two representations are treated as equivalent;\n#' both are parsed as `interaction(z1, z2)` internally.) If arithmetic\n#' operators are used for transforming variables, they should be wrapped in\n#' `I()`, e.g., `I(y1/y2) ~ x`. Note that the `formula` and `x` arguments\n#' should not be specified in the same call.\n#' @param data a data.frame (or list) from which the variables in formula\n#' should be taken. A matrix is converted to a data frame.\n#' @param type character string or call to a `type_*()` function giving the\n#' type of plot desired.\n#' - NULL (default): Choose a sensible type for the type of `x` and `y` inputs\n#' (i.e., usually `\"p\"`).\n#' - 1-character values supported by \\code{\\link[graphics]{plot}}:\n#' - `\"p\"` Points\n#' - `\"l\"` Lines\n#' - `\"b\"` Both points and lines\n#' - `\"c\"` Empty points joined by lines\n#' - `\"o\"` Overplotted points and lines\n#' - `\"s\"` Stair steps\n#' - `\"S\"` Stair steps\n#' - `\"h\"` Histogram-like vertical lines\n#' - `\"n\"` Empty plot over the extent of the data\n#' - `tinyplot`-specific types. These fall into several categories:\n#' - Shapes:\n#' - `\"area\"` / [`type_area()`]: Plots the area under the curve from `y` = 0 to `y` = f(`x`).\n#' - `\"errorbar\"` / [`type_errorbar()`]: Adds error bars to points; requires `ymin` and `ymax`.\n#' - `\"pointrange\"` / [`type_pointrange()`]: Combines points with error bars.\n#' - `\"polygon\"` / [`type_polygon()`]: Draws polygons.\n#' - `\"polypath\"` / [`type_polypath()`]: Draws a path whose vertices are given in `x` and `y`.\n#' - `\"rect\"` / [`type_rect()`]: Draws rectangles; requires `xmin`, `xmax`, `ymin`, and `ymax`.\n#' - `\"ribbon\"` / [`type_ribbon()`]: Creates a filled area between `ymin` and `ymax`.\n#' - `\"segments\"` / [`type_segments()`]: Draws line segments between pairs of points.\n#' - `\"text\"` / [`type_text()`]: Add text annotations.\n#' - Visualizations:\n#' - `\"barplot\"` / [`type_barplot()`]: Creates a bar plot.\n#' - `\"boxplot\"` / [`type_boxplot()`]: Creates a box-and-whisker plot.\n#' - `\"density\"` / [`type_density()`]: Plots the density estimate of a variable.\n#' - `\"histogram\"` / [`type_histogram()`]: Creates a histogram of a single variable.\n#' - `\"jitter\"` / [`type_jitter()`]: Jittered points.\n#' - `\"qq\"` / [`type_qq()`]: Creates a quantile-quantile plot.\n#' - `\"ridge\"` / [`type_ridge()`]: Creates a ridgeline (aka joy) plot.\n#' - `\"rug\"` / [`type_rug()`]: Adds a rug to an existing plot.\n#' - `\"spineplot\"` / [`type_spineplot()`]: Creates a spineplot or spinogram.\n#' - `\"violin\"` / [`type_violin()`]: Creates a violin plot.\n#' - Models:\n#' - `\"loess\"` / [`type_loess()`]: Local regression curve.\n#' - `\"lm\"` / [`type_lm()`]: Linear regression line.\n#' - `\"glm\"` / [`type_glm()`]: Generalized linear model fit.\n#' - `\"spline\"` / [`type_spline()`]: Cubic (or Hermite) spline interpolation.\n#' - Functions:\n#' - [`type_abline()`]: line(s) with intercept and slope.\n#' - [`type_hline()`]: horizontal line(s).\n#' - [`type_vline()`]: vertical line(s).\n#' - [`type_function()`]: arbitrary function.\n#' - [`type_summary()`]: summarize `y` by unique values of `x`.\n#' @param legend one of the following options:\n#' - NULL (default), in which case the legend will be determined by the\n#' grouping variable. If there is no group variable (i.e., `by` is NULL) then\n#' no legend is drawn. If a grouping variable is detected, then an automatic\n#' legend is drawn to the _outer_ right of the plotting area. Note that the\n#' legend title and categories will automatically be inferred from the `by`\n#' argument and underlying data.\n#' - A convenience string indicating the legend position. The string should\n#' correspond to one of the position keywords supported by the base `legend`\n#' function, e.g. \"right\", \"topleft\", \"bottom\", etc. In addition, `tinyplot`\n#' supports adding a trailing exclamation point to these keywords, e.g.\n#' \"right!\", \"topleft!\", or \"bottom!\". This will place the legend _outside_\n#' the plotting area and adjust the margins of the plot accordingly. Finally,\n#' users can also turn off any legend printing by specifying \"none\".\n#' - Logical value, where TRUE corresponds to the default case above (same\n#' effect as specifying NULL) and FALSE turns the legend off (same effect as\n#' specifying \"none\").\n#' - A list or, equivalently, a dedicated `legend()` function with supported\n#' legend arguments, e.g. \"bty\", \"horiz\", and so forth.\n#' @param main a main title for the plot, see also `title`.\n#' @param sub a subtitle for the plot.\n#' @param xlab a label for the x axis, defaults to a description of x.\n#' @param ylab a label for the y axis, defaults to a description of y.\n#' @param ann a logical value indicating whether the default annotation (title\n#' and x and y axis labels) should appear on the plot.\n#' @param xlim the x limits (x1, x2) of the plot. Note that x1 > x2 is allowed\n#' and leads to a ‘reversed axis’. The default value, NULL, indicates that\n#' the range of the `finite` values to be plotted should be used.\n#' @param ylim the y limits of the plot.\n#' @param axes logical or character. Should axes be drawn (`TRUE` or `FALSE`)?\n#' Or alternatively what type of axes should be drawn: `\"standard\"` (with\n#' axis, ticks, and labels; equivalent to `TRUE`), `\"none\"` (no axes;\n#' equivalent to `FALSE`), `\"ticks\"` (only ticks and labels without axis line),\n#' `\"labels\"` (only labels without ticks and axis line), `\"axis\"` (only axis\n#' line and labels but no ticks). To control this separately for the two\n#' axes, use the character specifications for `xaxt` and/or `yaxt`.\n#' @param xaxt,yaxt character specifying the type of x-axis and y-axis,\n#' respectively. See `axes` for the possible values.\n#' @param xaxs,yaxs character specifying the style of the interval calculation\n#' used for the x-axis and y-axis, respectively. See\n#' \\code{\\link[graphics]{par}} for the possible values.\n#' @param xaxb,yaxb numeric vector (or character vector, if appropriate) giving\n#' the break points at which the axis tick-marks are to be drawn. Break points\n#' outside the range of the data will be ignored if the associated axis\n#' variable is categorical, or an explicit `x/ylim` range is given.\n#' @param xaxl,yaxl a function or a character keyword specifying the format of\n#' the x- or y-axis tick labels. Note that this is a post-processing step that\n#' affects the _appearance_ of the tick labels only; use in conjunction with\n#' `x/yaxb` if you would like to adjust the position of the tick marks too. In\n#' addition to user-supplied formatting functions (e.g., [`format`],\n#' [`toupper`], [`abs`], or other custom function), several convenience\n#' keywords (or their symbol equivalents) are available for common formatting\n#' transformations: `\"percent\"` (`\"%\"`), `\"comma\"` (`\",\"`), `\"log\"` (`\"l\"`),\n#' `\"dollar\"` (`\"$\"`), `\"euro\"` (`\"€\"`), or `\"sterling\"` (`\"£\"`). See the\n#' [`tinylabel`] documentation for examples.\n#' @param log a character string which contains `\"x\"` if the x axis is to be\n#' logarithmic, `\"y\"` if the y axis is to be logarithmic and `\"xy\"` or `\"yx\"`\n#' if both axes are to be logarithmic.\n#' @param flip logical. Should the plot orientation be flipped, so that the\n#' y-axis is on the horizontal plane and the x-axis is on the vertical plane?\n#' Default is FALSE.\n#' @param frame.plot a logical indicating whether a box should be drawn around\n#' the plot. Can also use `frame` as an acceptable argument alias.\n#' The default is to draw a frame if both axis types (set via `axes`, `xaxt`,\n#' or `yaxt`) include axis lines.\n#' @param grid argument for plotting a background panel grid, one of either:\n#' - a logical (i.e., `TRUE` to draw the grid), or\n#' - a panel grid plotting function like `grid()`.\n#' Note that this argument replaces the `panel.first` and `panel.last`\n#' arguments from base `plot()` and tries to make the process more seamless\n#' with better default behaviour. The default behaviour is determined by (and\n#' can be set globally through) the value of `tpar(\"grid\")`.\n#' @param palette one of the following options:\n#' - NULL (default), in which case the palette will be chosen according to\n#' the class and cardinality of the \"by\" grouping variable. For non-ordered\n#' factors or strings with a reasonable number of groups, this will inherit\n#' directly from the user's default \\code{\\link[grDevices]{palette}} (e.g.,\n#' \"R4\"). In other cases, including ordered factors and high cardinality, the\n#' \"Viridis\" palette will be used instead. Note that a slightly restricted\n#' version of the \"Viridis\" palette---where extreme color values have been\n#' trimmed to improve visual perception---will be used for ordered factors\n#' and continuous variables. In the latter case of a continuous grouping\n#' variable, we also generate a gradient legend swatch.\n#' - A convenience string corresponding to one of the many palettes listed by\n#' either `palette.pals()` or `hcl.pals()`. Note that the string can be\n#' case-insensitive (e.g., \"Okabe-Ito\" and \"okabe-ito\" are both valid).\n#' - A palette-generating function. This can be \"bare\" (e.g.,\n#' `palette.colors`) or \"closed\" with a set of named arguments (e.g.,\n#' `palette.colors(palette = \"Okabe-Ito\", alpha = 0.5)`). Note that any\n#' unnamed arguments will be ignored and the key `n` argument, denoting the\n#' number of colours, will automatically be spliced in as the number of\n#' groups.\n#' - A vector or list of colours, e.g. `c(\"darkorange\", \"purple\", \"cyan4\")`.\n#' If too few colours are provided for a discrete (qualitative) set of\n#' groups, then the colours will be recycled with a warning. For continuous\n#' (sequential) groups, a gradient palette will be interpolated. \n#' @param col plotting color. Character, integer, or vector of length equal to\n#' the number of categories in the `by` variable. See `col`. Note that the\n#' default behaviour in `tinyplot` is to vary group colors along any variables\n#' declared in the `by` argument. Thus, specifying colors manually should not\n#' be necessary unless users wish to override the automatic colors produced by\n#' this grouping process. Typically, this would only be done if grouping\n#' features are deferred to some other graphical parameter (i.e., passing the\n#' \"by\" keyword to one of `pch`, `lty`, `lwd`, or `bg`; see below.)\n#' @param pch plotting \"character\", i.e., symbol to use. Character, integer, or\n#' vector of length equal to the number of categories in the `by` variable.\n#' See `pch`. In addition, users can supply a special `pch = \"by\"` convenience\n#' argument, in which case the characters will automatically loop over the\n#' number groups. This automatic looping will begin at the global character\n#' value (i.e., `par(\"pch\")`) and recycle as necessary.\n#' @param lty line type. Character, integer, or vector of length equal to the\n#' number of categories in the `by` variable. See `lty`. In addition, users\n#' can supply a special `lty = \"by\"` convenience argument, in which case the\n#' line type will automatically loop over the number groups. This automatic\n#' looping will begin at the global line type value (i.e., `par(\"lty\")`) and\n#' recycle as necessary.\n#' @param lwd line width. Numeric scalar or vector of length equal to the\n#' number of categories in the `by` variable. See `lwd`. In addition, users\n#' can supply a special `lwd = \"by\"` convenience argument, in which case the\n#' line width will automatically loop over the number of groups. This\n#' automatic looping will be centered at the global line width value (i.e.,\n# ` par(\"lwd\")`) and pad on either side of that.\n#' @param bg background fill color for the open plot symbols 21:25 (see\n#' `points.default`), as well as ribbon and area plot types.\n#' Users can also supply either one of two special convenience arguments that\n#' will cause the background fill to inherit the automatic grouped coloring\n#' behaviour of `col`:\n#'\n#' - `bg = \"by\"` will insert a background fill that inherits the main color\n#' mappings from `col`.\n#' - `by = ` (i.e., a numeric in the range `[0,1]`) will insert\n#' a background fill that inherits the main color mapping(s) from `col`, but\n#' with added alpha-transparency.\n#'\n#' For both of these convenience arguments, note that the (grouped) `bg`\n#' mappings will persist even if the (grouped) `col` defaults are themselves\n#' overridden. This can be useful if you want to preserve the grouped palette\n#' mappings by background fill but not boundary color, e.g. filled points. See\n#' examples.\n#' @param fill alias for `bg`. If non-NULL values for both `bg` and `fill` are\n#' provided, then the latter will be ignored in favour of the former.\n#' @param alpha a numeric in the range `[0,1]` for adjusting the alpha channel\n#' of the color palette, where 0 means transparent and 1 means opaque. Use\n#' fractional values, e.g. `0.5` for semi-transparency.\n#' @param cex character expansion. A numerical vector (can be a single value)\n#' giving the amount by which plotting characters and symbols should be scaled\n#' relative to the default. Note that NULL is equivalent to 1.0, while NA\n#' renders the characters invisible.\n#' @param subset,na.action,drop.unused.levels arguments passed to `model.frame`\n#' when extracting the data from `formula` and `data`.\n#' @param add logical. If TRUE, then elements are added to the current plot rather\n#' than drawing a new plot window. Note that the automatic legend for the\n#' added elements will be turned off. See also [tinyplot_add], which provides\n#' a convenient wrapper around this functionality for layering on top of an\n#' existing plot without having to repeat arguments.\n#' @param draw a function that draws directly on the plot canvas (before `x` and\n#' `y` are plotted). The `draw` argument is primarily useful for adding common\n#' elements to each facet of a faceted plot, e.g.\n#' \\code{\\link[graphics]{abline}} or \\code{\\link[graphics]{text}}. Note that\n#' this argument is somewhat experimental and that _no_ internal checking is\n#' done for correctness; the provided argument is simply captured and\n#' evaluated as-is. See Examples.\n#' @param restore.par a logical value indicating whether the\n#' \\code{\\link[graphics]{par}} settings prior to calling `tinyplot` should be\n#' restored on exit. Defaults to FALSE, which makes it possible to add\n#' elements to the plot after it has been drawn. However, note the the outer\n#' margins of the graphics device may have been altered to make space for the\n#' `tinyplot` legend. Users can opt out of this persistent behaviour by\n#' setting to TRUE instead. See also [get_saved_par] for another option to\n#' recover the original \\code{\\link[graphics]{par}} settings, as well as\n#' longer discussion about the trade-offs involved.\n#' @param empty logical indicating whether the interior plot region should be\n#' left empty. The default is `FALSE`. Setting to `TRUE` has a similar effect\n#' to invoking `type = \"n\"` above, except that any legend artifacts owing to a\n#' particular plot type (e.g., lines for `type = \"l\"` or squares for\n#' `type = \"area\"`) will still be drawn correctly alongside the empty plot. In\n#' contrast,`type = \"n\"` implicitly assumes a scatterplot and so any legend\n#' will only depict points.\n#' @param file character string giving the file path for writing a plot to disk.\n#' If specified, the plot will not be displayed interactively, but rather sent\n#' to the appropriate external graphics device (i.e.,\n#' \\code{\\link[grDevices]{png}}, \\code{\\link[grDevices]{jpeg}},\n#' \\code{\\link[grDevices]{pdf}}, or \\code{\\link[grDevices]{svg}}). As a point\n#' of convenience, note that any global parameters held in `(t)par` are\n#' automatically carried over to the external device and don't need to be\n#' reset (in contrast to the conventional base R approach that requires\n#' manually opening and closing the device). The device type is determined by\n#' the file extension at the end of the provided path, and must be one of\n#' \".png\", \".jpg\" (\".jpeg\"), \".pdf\", or \".svg\". (Other file types may be\n#' supported in the future.) The file dimensions can be controlled by the\n#' corresponding `width` and `height` arguments below, otherwise will fall\n#' back to the `\"file.width\"` and `\"file.height\"` values held in\n#' \\code{\\link[tinyplot]{tpar}} (i.e., both defaulting to 7 inches, and where\n#' the default resolution for bitmap files is also specified as 300\n#' DPI).\n#' @param width numeric giving the plot width in inches. Together with `height`,\n#' typically used in conjunction with the `file` argument above, overriding the\n#' default values held in `tpar(\"file.width\", \"file.height\")`. If either `width`\n#' or `height` is specified, but a corresponding `file` argument is not\n#' provided as well, then a new interactive graphics device dimensions will be\n#' opened along the given dimensions. Note that this interactive resizing may\n#' not work consistently from within an IDE like RStudio that has an integrated\n#' graphics windows.\n#' @param height numeric giving the plot height in inches. Same considerations as\n#' `width` (above) apply, e.g. will default to `tpar(\"file.height\")` if not\n#' specified.\n#' @param asp the y/xy/x aspect ratio, see `plot.window`.\n#' @param ... other graphical parameters. If `type` is a character specification\n#' (such as `\"hist\"`) then any argument names that match those from the corresponding\n#' `type_*()` function (such as \\code{\\link{type_hist}}) are passed on to that.\n#' All remaining arguments from `...` can be further graphical parameters, see\n#' \\code{\\link[graphics]{par}}).\n#'\n#' @returns No return value, called for side effect of producing a plot.\n#'\n#' @details\n#' Disregarding the enhancements that it supports, `tinyplot` tries as far as\n#' possible to mimic the behaviour and syntax logic of the original base\n#' \\code{\\link[graphics]{plot}} function. Users should therefore be able to swap\n#' out existing `plot` calls for `tinyplot` (or its shorthand alias `plt`),\n#' without causing unexpected changes to the output.\n#'\n#' @importFrom grDevices axisTicks adjustcolor cairo_pdf colorRampPalette extendrange palette palette.colors palette.pals hcl.colors hcl.pals xy.coords png jpeg pdf svg dev.off dev.new dev.list\n#' @importFrom graphics abline arrows axis Axis axTicks box boxplot grconvertX grconvertY hist lines mtext par plot.default plot.new plot.window points polygon polypath segments rect text title\n#' @importFrom utils modifyList head tail\n#' @importFrom stats na.omit\n#' @importFrom tools file_ext\n#'\n#' @examples\n#' aq = transform(\n#' airquality,\n#' Month = factor(Month, labels = month.abb[unique(Month)])\n#' )\n#'\n#' # In most cases, `tinyplot` should be a drop-in replacement for regular\n#' # `plot` calls. For example:\n#'\n#' op = tpar(mfrow = c(1, 2))\n#' plot(0:10, main = \"plot\")\n#' tinyplot(0:10, main = \"tinyplot\")\n#' tpar(op) # restore original layout\n#'\n#' # Aside: `tinyplot::tpar()` is a (near) drop-in replacement for `par()`\n#'\n#' # Unlike vanilla plot, however, tinyplot allows you to characterize groups\n#' # using either the `by` argument or equivalent `|` formula syntax.\n#'\n#' with(aq, tinyplot(Day, Temp, by = Month)) ## atomic method\n#' tinyplot(Temp ~ Day | Month, data = aq) ## formula method\n#'\n#' # (Notice that we also get an automatic legend.)\n#'\n#' # You can also use the equivalent shorthand `plt()` alias if you'd like to\n#' # save on a few keystrokes\n#'\n#' plt(Temp ~ Day | Month, data = aq) ## shorthand alias\n#'\n#' # Use standard base plotting arguments to adjust features of your plot.\n#' # For example, change `pch` (plot character) to get filled points and `cex`\n#' # (character expansion) to increase their size.\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' pch = 16,\n#' cex = 2\n#' )\n#'\n#' # We can add alpha transparency for overlapping points\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' pch = 16,\n#' cex = 2,\n#' alpha = 0.3\n#' )\n#'\n#' # To get filled points with a common solid background color, use an\n#' # appropriate plotting character (21:25) and combine with one of the special\n#' # `bg` convenience arguments.\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' pch = 21, # use filled circles\n#' cex = 2,\n#' bg = 0.3, # numeric in [0,1] adds a grouped background fill with transparency\n#' col = \"black\" # override default color mapping; give all points a black border\n#' )\n#'\n#' # Converting to a grouped line plot is a simple matter of adjusting the\n#' # `type` argument.\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' type = \"l\"\n#' )\n#'\n#' # Similarly for other plot types, including some additional ones provided\n#' # directly by tinyplot, e.g. density plots or internal plots (ribbons,\n#' # pointranges, etc.)\n#'\n#' tinyplot(\n#' ~ Temp | Month,\n#' data = aq,\n#' type = \"density\",\n#' fill = \"by\"\n#' )\n#'\n#' # Facet plots are supported too. Facets can be drawn on their own...\n#'\n#' tinyplot(\n#' Temp ~ Day,\n#' facet = ~Month,\n#' data = aq,\n#' type = \"area\",\n#' main = \"Temperatures by month\"\n#' )\n#'\n#' # ... or combined/contrasted with the by (colour) grouping.\n#'\n#' aq = transform(aq, Summer = Month %in% c(\"Jun\", \"Jul\", \"Aug\"))\n#' tinyplot(\n#' Temp ~ Day | Summer,\n#' facet = ~Month,\n#' data = aq,\n#' type = \"area\",\n#' palette = \"dark2\",\n#' main = \"Temperatures by month and season\"\n#' )\n#'\n#' # Users can override the default square window arrangement by passing `nrow`\n#' # or `ncol` to the helper facet.args argument. Note that we can also reduce\n#' # axis label repetition across facets by turning the plot frame off.\n#'\n#' tinyplot(\n#' Temp ~ Day | Summer,\n#' facet = ~Month, facet.args = list(nrow = 1),\n#' data = aq,\n#' type = \"area\",\n#' palette = \"dark2\",\n#' frame = FALSE,\n#' main = \"Temperatures by month and season\"\n#' )\n#'\n#' # Use a two-sided formula to arrange the facet windows in a fixed grid.\n#' # LHS -> facet rows; RHS -> facet columns\n#'\n#' aq$hot = ifelse(aq$Temp >= 75, \"hot\", \"cold\")\n#' aq$windy = ifelse(aq$Wind >= 15, \"windy\", \"calm\")\n#' tinyplot(\n#' Temp ~ Day,\n#' facet = windy ~ hot,\n#' data = aq\n#' )\n#'\n#' # To add common elements to each facet, use the `draw` argument\n#'\n#' tinyplot(\n#' Temp ~ Day,\n#' facet = windy ~ hot,\n#' data = aq,\n#' draw = abline(h = 75, lty = 2, col = \"hotpink\")\n#' )\n#'\n#' # The (automatic) legend position and look can be customized using\n#' # appropriate arguments. Note the trailing \"!\" in the `legend` position\n#' # argument below. This tells `tinyplot` to place the legend _outside_ the plot\n#' # area.\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' type = \"l\",\n#' legend = legend(\"bottom!\", title = \"Month of the year\", bty = \"o\")\n#' )\n#'\n#' # The default group colours are inherited from either the \"R4\" or \"Viridis\"\n#' # palettes, depending on the number of groups. However, all palettes listed\n#' # by `palette.pals()` and `hcl.pals()` are supported as convenience strings,\n#' # or users can supply a valid palette-generating function for finer control\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' type = \"l\",\n#' palette = \"tableau\"\n#' )\n#'\n#' # It's possible to customize the look of your plots by setting graphical\n#' # parameters (e.g., via `(t)par`)... But a more convenient way is to just use\n#' # built-in themes (see `?tinytheme`).\n#'\n#' tinytheme(\"clean2\")\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' type = \"b\",\n#' alpha = 0.5,\n#' main = \"Daily temperatures by month\",\n#' sub = \"Brought to you by tinyplot\"\n#' )\n#' # reset the theme\n#' tinytheme()\n#'\n#' # For more examples and a detailed walkthrough, please see the introductory\n#' # tinyplot tutorial available online:\n#' # https://grantmcdermott.com/tinyplot/vignettes/introduction.html\n#'\n#' @rdname tinyplot\n#' @export\ntinyplot =\n function(x, ...) {\n UseMethod(\"tinyplot\")\n }\n\n#' @rdname tinyplot\n#' @export\ntinyplot.default = function(\n x = NULL,\n y = NULL,\n xmin = NULL,\n xmax = NULL,\n ymin = NULL,\n ymax = NULL,\n by = NULL,\n facet = NULL,\n facet.args = NULL,\n data = NULL,\n type = NULL,\n legend = NULL,\n main = NULL,\n sub = NULL,\n xlab = NULL,\n ylab = NULL,\n ann = par(\"ann\"),\n xlim = NULL,\n ylim = NULL,\n axes = TRUE,\n xaxt = NULL,\n yaxt = NULL,\n xaxs = NULL,\n yaxs = NULL,\n xaxb = NULL,\n yaxb = NULL,\n xaxl = NULL,\n yaxl = NULL,\n log = \"\",\n flip = FALSE,\n frame.plot = NULL,\n grid = NULL,\n palette = NULL,\n pch = NULL,\n lty = NULL,\n lwd = NULL,\n col = NULL,\n bg = NULL,\n fill = NULL,\n alpha = NULL,\n cex = 1,\n add = FALSE,\n draw = NULL,\n empty = FALSE,\n restore.par = FALSE,\n file = NULL,\n width = NULL,\n height = NULL,\n asp = NA,\n ...) {\n\n par_first = get_saved_par(\"first\")\n if (is.null(par_first)) set_saved_par(\"first\", par())\n\n assert_logical(add)\n \n # save for tinyplot_add()\n if (!add) {\n calls = sys.calls()\n idx = grep(\"^tinyplot\", sapply(calls, function(k) k[[1]]))\n if (length(idx) > 0) {\n options(tinyplot_last_call = calls[[idx[1]]])\n }\n ## TODO: remove the global option above and move to this when density is refactored\n # cal = match.call(call = sys.call(sys.parent()), expand.dots = TRUE)\n # assign(\".last_call\", cal, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n }\n\n dots = list(...)\n\n if (add) legend = FALSE\n draw = substitute(draw)\n\n\n # sanitize arguments\n\n # type factories vs. strings\n type = sanitize_type(type, x, y, dots)\n if (\"dots\" %in% names(type)) dots = type$dots\n \n # retrieve type-specific data and drawing functions\n type_data = type$data\n type_draw = type$draw\n type = type$name\n \n # area flag (mostly for legend)\n was_area_type = identical(type, \"area\")\n # check flip flag is logical \n assert_flag(flip)\n\n palette = substitute(palette)\n\n # themes\n if (is.null(palette)) palette = get_tpar(\"palette\", default = NULL)\n if (is.null(pch)) pch = get_tpar(\"pch\", default = NULL)\n\n xlabs = ylabs = NULL\n\n # type_ridge()\n ygroup = NULL\n\n # will be overwritten by some type_data() functions and ignored by others\n ribbon.alpha = sanitize_ribbon.alpha(NULL)\n\n ## handle defaults of axes, xaxt, yaxt, frame.plot\n ## - convert axes to character if necessary\n ## - set defaults of xaxt/yaxt (if these are NULL) based on axes\n ## - set logical axes based on xaxt/yaxt\n ## - set frame.plot default based on xaxt/yaxt\n if (isFALSE(axes)) {\n axes = xaxt = yaxt = \"none\"\n } else if (isTRUE(axes)) {\n axes = \"standard\"\n if (is.null(xaxt)) xaxt = get_tpar(\"xaxt\", default = \"standard\")\n if (is.null(yaxt)) yaxt = get_tpar(\"yaxt\", default = \"standard\")\n } else {\n xaxt = yaxt = axes\n }\n axis_types = c(\"standard\", \"none\", \"labels\", \"ticks\", \"axis\")\n axes = match.arg(axes, axis_types)\n xaxt = match.arg(xaxt, axis_types)\n yaxt = match.arg(yaxt, axis_types)\n xaxt = substr(match.arg(xaxt, axis_types), 1L, 1L)\n yaxt = substr(match.arg(yaxt, axis_types), 1L, 1L)\n axes = any(c(xaxt, yaxt) != \"n\")\n if (is.null(frame.plot) || !is.logical(frame.plot)) frame.plot = all(c(xaxt, yaxt) %in% c(\"s\", \"a\"))\n\n # Write plot to output file or window with fixed dimensions\n setup_device(file = file, width = width, height = height)\n if (!is.null(file)) on.exit(dev.off(), add = TRUE)\n\n # Save current graphical parameters\n opar = par(no.readonly = TRUE)\n if (restore.par || !is.null(facet)) {\n if (!is.null(file) || !is.null(width) || !is.null(height)) {\n opar$new = FALSE # catch for some interfaces\n }\n on.exit(par(opar), add = TRUE)\n }\n # set_orig_par(opar)\n set_saved_par(when = \"before\", opar)\n\n # catch for adding to existing facet plot\n if (!is.null(facet) && add) {\n recordGraphics(\n par(get_saved_par(when = \"after\")),\n list = list(),\n env = getNamespace('tinyplot')\n )\n }\n\n # Capture deparsed expressions early, before x, y and by are evaluated\n x_dep = if (!is.null(x)) {\n deparse1(substitute(x))\n } else if (type %in% c(\"rect\", \"segments\")) {\n x = NULL\n NULL\n }\n y_dep = if (is.null(y)) {\n deparse1(substitute(x))\n } else {\n deparse1(substitute(y))\n }\n by_dep = deparse1(substitute(by))\n null_by = is.null(by)\n\n ## coerce character variables to factors\n if (!is.null(x) && is.character(x)) x = factor(x)\n if (!is.null(y) && is.character(y)) y = factor(y)\n if (!null_by && is.character(by)) by = factor(by)\n\n # flag if x==by (currently only used for \"boxplot\", \"spineplot\" and \"ridges\" types)\n x_by = identical(x, by)\n\n facet_dep = deparse1(substitute(facet))\n # flag if facet==by\n facet_by = FALSE\n if (!is.null(facet) && length(facet) == 1 && facet == \"by\") {\n by = as.factor(by) ## if by==facet, then both need to be factors\n facet = by\n facet_by = TRUE\n } else if (!is.null(facet) && inherits(facet, \"formula\")) {\n facet = get_facet_fml(facet, data = data)\n if (isTRUE(attr(facet, \"facet_grid\"))) {\n facet.args[[\"nrow\"]] = attr(facet, \"facet_nrow\")\n }\n }\n facet_attr = attributes(facet) ## TODO: better solution for restoring facet attributes?\n null_facet = is.null(facet)\n\n if (is.null(x)) {\n ## Special catch for rect and segment plots without a specified y-var\n if (type %in% c(\"rect\", \"segments\")) {\n xmin_dep = deparse(substitute(xmin))\n xmax_dep = deparse(substitute(xmax))\n x_dep = paste0(\"[\", xmin_dep, \", \", xmax_dep, \"]\")\n x = rep(NA, length(x))\n }\n }\n if (is.null(y)) {\n ## Special catch for area and interval plots without a specified y-var\n if (type %in% c(\"rect\", \"segments\", \"pointrange\", \"errorbar\", \"ribbon\")) {\n ymin_dep = deparse(substitute(ymin))\n ymax_dep = deparse(substitute(ymax))\n y_dep = paste0(\"[\", ymin_dep, \", \", ymax_dep, \"]\")\n y = rep(NA, length(x))\n } else if (type == \"density\") {\n if (is.null(ylab)) ylab = \"Density\"\n } else if (type == \"function\") {\n if (is.null(ylab)) ylab = \"Frequency\"\n } else if (!(type %in% c(\"histogram\", \"barplot\"))) {\n y = x\n x = seq_along(x)\n if (is.null(xlab)) xlab = \"Index\"\n }\n }\n\n if (is.null(xlab)) xlab = x_dep\n if (is.null(ylab) && type != \"histogram\") ylab = y_dep\n \n # flag(s) indicating whether x/ylim was set by the user (needed later for\n # special case where facets are free but still want to set x/ylim manually)\n xlim_user = !is.null(xlim)\n ylim_user = !is.null(ylim)\n\n # alias\n if (is.null(bg) && !is.null(fill)) bg = fill\n\n datapoints = list(x = x, y = y, xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, ygroup = ygroup)\n datapoints = Filter(function(z) length(z) > 0, datapoints)\n datapoints = data.frame(datapoints)\n if (nrow(datapoints) > 0) {\n datapoints[[\"rowid\"]] = seq_len(nrow(datapoints))\n datapoints[[\"facet\"]] = if (!is.null(facet)) facet else \"\"\n datapoints[[\"by\"]] = if (!null_by) by else \"\"\n }\n\n ## initialize empty list with information that type_data\n ## can overwrite in order to pass on to type_draw\n type_info = list()\n\n if (!is.null(type_data)) {\n fargs = list(\n datapoints = datapoints,\n bg = bg,\n by = by,\n col = col,\n log = log,\n lty = lty,\n lwd = lwd,\n facet = facet,\n facet_by = facet_by,\n facet.args = facet.args,\n null_by = null_by,\n null_facet = null_facet,\n palette = palette,\n ribbon.alpha = ribbon.alpha,\n xaxt = xaxt,\n xaxb = xaxb,\n xaxl = xaxl,\n xlab = xlab,\n xlabs = xlabs,\n xlim = xlim,\n yaxt = yaxt,\n yaxb = yaxb,\n yaxl = yaxl,\n ylab = ylab,\n ylim = ylim\n )\n fargs = c(fargs, dots)\n list2env(do.call(type_data, fargs), environment())\n }\n\n\n # swap x and y values if flip is TRUE\n assert_flag(flip)\n # extra catch for boxplots\n # now swap the values\n if (isTRUE(flip)) {\n if (type != \"boxplot\") {\n # limits, labs, etc.\n xlim_cp = xlim\n xlim = ylim\n ylim = xlim_cp\n xlab_cp = xlab\n xlab = ylab\n ylab = xlab_cp\n xlabs_cp = xlabs\n xlabs = ylabs\n ylabs = xlabs_cp\n xaxt_cp = xaxt\n xaxt = yaxt\n yaxt = xaxt_cp\n xaxs_cp = xaxs\n xaxs = yaxs\n yaxs = xaxs_cp\n xaxb_cp = xaxb\n xaxb = yaxb\n yaxb = xaxb_cp\n xaxl_cp = xaxl\n xaxl = yaxl\n yaxl = xaxl_cp\n if (!is.null(log)) {\n log = if (log == \"x\") \"y\" else if (log == \"y\") \"x\" else log\n }\n # x/y vars\n x_cp = datapoints[[\"x\"]]\n datapoints[[\"x\"]] = datapoints[[\"y\"]]\n datapoints[[\"y\"]] = x_cp\n # x/y min and max vars\n xmin_cp = if (!is.null(datapoints[[\"xmin\"]])) datapoints[[\"xmin\"]] else NULL\n datapoints[[\"xmin\"]] = if (!is.null(datapoints[[\"ymin\"]])) datapoints[[\"ymin\"]] else NULL\n datapoints[[\"ymin\"]] = if (!is.null(xmin_cp)) xmin_cp else NULL\n xmax_cp = if (!is.null(datapoints[[\"xmax\"]])) datapoints[[\"xmax\"]] else NULL\n datapoints[[\"xmax\"]] = if (!is.null(datapoints[[\"ymax\"]])) datapoints[[\"ymax\"]] else NULL\n datapoints[[\"ymax\"]] = if (!is.null(xmax_cp)) xmax_cp else NULL\n # clean up\n rm(xlim_cp, xlab_cp, xlabs_cp, xaxt_cp, xaxs_cp, xaxb_cp, xaxl_cp, x_cp, xmin_cp, xmax_cp)\n } else {\n # We'll let boxplot(..., horizontal = TRUE) handle most of the adjustments\n # and just catch a few elements that we draw beforehand.\n xlab_cp = xlab\n xlab = ylab\n ylab = xlab_cp\n rm(xlab_cp)\n }\n }\n \n # For cases where x/yaxb is provided and corresponding x/ylabs is not null...\n # We can subset these here to provide breaks\n if (!is.null(xaxb) && !is.null(xlabs)) {\n xlabs = xlabs[names(xlabs) %in% xaxb]\n xaxb = NULL # don't need this any more\n }\n if (!is.null(yaxb) && !is.null(ylabs)) {\n ylabs = ylabs[names(ylabs) %in% yaxb]\n yaxb = NULL # don't need this any more\n }\n \n # plot limits\n fargs = lim_args(\n datapoints = datapoints,\n xlim = xlim, ylim = ylim,\n xaxb = xaxb, yaxb = yaxb,\n xlim_user = xlim_user, ylim_user = ylim_user,\n type = type\n )\n list2env(fargs, environment())\n\n\n # split data\n by_ordered = FALSE\n by_continuous = !null_by && inherits(datapoints$by, c(\"numeric\", \"integer\"))\n if (isTRUE(by_continuous) && type %in% c(\"l\", \"b\", \"o\", \"ribbon\", \"polygon\", \"polypath\", \"boxplot\")) {\n warning(\"\\nContinuous legends not supported for this plot type. Reverting to discrete legend.\")\n by_continuous = FALSE\n } else if (!null_by) {\n by_ordered = is.ordered(by)\n }\n\n if (length(unique(datapoints$facet)) == 1) {\n datapoints[[\"facet\"]] = NULL\n }\n if (!is.null(datapoints$facet)) {\n split_data = split(datapoints, datapoints$facet)\n split_data = lapply(split_data, as.list)\n } else {\n split_data = list(as.list(datapoints))\n }\n\n # aesthetics by group: col, bg, etc.\n ngrps = if (null_by) 1L else if (is.factor(by)) length(levels(by)) else if (by_continuous) 100L else length(unique(by))\n pch = by_pch(ngrps = ngrps, type = type, pch = pch)\n lty = by_lty(ngrps = ngrps, type = type, lty = lty)\n lwd = by_lwd(ngrps = ngrps, type = type, lwd = lwd)\n col = by_col(\n ngrps = ngrps, col = col, palette = palette,\n gradient = by_continuous, ordered = by_ordered, alpha = alpha)\n bg = by_bg(\n adjustcolor = adjustcolor, alpha = alpha, bg = bg, by = by, by_continuous = by_continuous,\n by_ordered = by_ordered, col = col, fill = fill, palette = substitute(palette),\n ribbon.alpha = ribbon.alpha, ngrps = ngrps, type = type)\n \n ncolors = length(col)\n lgnd_labs = rep(NA, times = ncolors)\n if (isTRUE(by_continuous)) {\n ## Identify the pretty break points for our labels\n nlabs = 5\n ncolors = length(col)\n ubyvar = unique(by)\n byvar_range = range(ubyvar)\n pbyvar = pretty(byvar_range, n = nlabs)\n pbyvar = pbyvar[pbyvar >= byvar_range[1] & pbyvar <= byvar_range[2]]\n # optional thinning\n if (length(ubyvar) == 2 && all(ubyvar %in% pbyvar)) {\n pbyvar = ubyvar\n } else if (length(pbyvar) > nlabs) {\n pbyvar = pbyvar[seq_along(pbyvar) %% 2 == 0]\n }\n ## Find the (approximate) location of our pretty labels\n pidx = rescale_num(c(byvar_range, pbyvar), to = c(1, ncolors))[-c(1:2)]\n pidx = round(pidx)\n lgnd_labs[pidx] = pbyvar\n }\n\n # Determine the number and arrangement of facets.\n # Note: We're do this up front, so we can make some adjustments to legend cex\n # next (if there are facets). But the actual drawing of the facets will only\n # come later.\n attributes(datapoints$facet) = facet_attr ## TODO: better solution for restoring facet attributes?\n fargs = facet_layout(facet = datapoints$facet, facet.args = facet.args, add = add)\n list2env(fargs, environment())\n\n #\n ## Global plot elements (legend and titles)\n #\n\n # place and draw the legend\n has_legend = FALSE # simple indicator variable for later use\n\n if (!exists(\"legend_args\")) {\n legend_args = dots[[\"legend_args\"]]\n }\n if (is.null(legend_args)) legend_args = list(x = NULL)\n legend = substitute(legend)\n\n if (isFALSE(legend)) {\n legend = \"none\"\n } else if (isTRUE(legend)) {\n legend = NULL\n }\n if (!is.null(legend) && legend == \"none\") {\n legend_args[[\"x\"]] = \"none\"\n }\n\n if (null_by) {\n if (is.null(legend)) {\n legend = \"none\"\n legend_args[[\"x\"]] = \"none\"\n }\n }\n\n if ((is.null(legend) || legend != \"none\") && !add) {\n if (isFALSE(by_continuous)) {\n if (ngrps > 1) {\n lgnd_labs = if (is.factor(datapoints$by)) levels(datapoints$by) else unique(datapoints$by)\n } else {\n lgnd_labs = ylab\n }\n }\n\n has_sub = !is.null(sub)\n\n if (isTRUE(was_area_type) || isTRUE(type %in% c(\"area\", \"rect\", \"hist\", \"histogram\"))) {\n legend_args[[\"pt.lwd\"]] = par(\"lwd\")\n legend_args[[\"lty\"]] = 0\n }\n\n draw_legend(\n legend = legend,\n legend_args = legend_args,\n by_dep = by_dep,\n lgnd_labs = lgnd_labs,\n type = type,\n pch = pch,\n lty = lty,\n lwd = lwd,\n col = col,\n bg = bg,\n gradient = by_continuous,\n cex = cex * cex_fct_adj,\n has_sub = has_sub\n )\n\n has_legend = TRUE\n } else if (legend_args[[\"x\"]] == \"none\" && !add) {\n omar = par(\"mar\")\n ooma = par(\"oma\")\n topmar_epsilon = 0.1\n\n # Catch to avoid recursive offsets, e.g. repeated tinyplot calls with\n # \"bottom!\" legend position.\n\n ## restore inner margin defaults\n ## (in case the plot region/margins were affected by the preceding tinyplot call)\n if (any(ooma != 0)) {\n if (ooma[1] != 0 && omar[1] == par(\"mgp\")[1] + 1 * par(\"cex.lab\")) omar[1] = 5.1\n if (ooma[2] != 0 && omar[2] == par(\"mgp\")[1] + 1 * par(\"cex.lab\")) omar[2] = 4.1\n if (ooma[3] == topmar_epsilon && omar[3] != 4.1) omar[3] = 4.1\n if (ooma[4] != 0 && omar[4] == 0) omar[4] = 2.1\n par(mar = omar)\n }\n ## restore outer margin defaults (with a catch for custom mfrow plots)\n if (all(par(\"mfrow\") == c(1, 1))) {\n par(omd = c(0, 1, 0, 1))\n }\n\n # clean up for now\n rm(omar, ooma, topmar_epsilon)\n\n # Draw new plot\n plot.new()\n }\n\n # Titles. Only draw these if add = FALSE\n if (!add) {\n # main title\n # Note that we include a special catch for the main title if legend is\n # \"top!\" (and main is specified in the first place).\n legend_eval = tryCatch(eval(legend), error = function(e) NULL)\n # Extra bit of footwork if user passed legend = legend(...) instead of\n # legend = list(...), since the call environment is tricky\n if (is.null(legend_eval)) {\n legend_eval = tryCatch(paste0(legend)[[2]], error = function(e) NULL)\n }\n\n adj_title = !is.null(legend) && (legend == \"top!\" || (!is.null(legend_args[[\"x\"]]) && legend_args[[\"x\"]] == \"top!\") || (is.list(legend_eval) && legend_eval[[1]] == \"top!\"))\n\n # For the \"top!\" legend case, bump main title up to make space for the\n # legend beneath it: Take the normal main title line gap (i.e., 1.7 lines)\n # and add the difference between original top margin and new one (i.e.,\n # which should equal the height of the new legend). Note that we also\n # include a 0.1 epsilon bump, which we're using to reset the tinyplot\n # window in case of recursive \"top!\" calls. (See draw_legend code.)\n\n if (isTRUE(adj_title)) {\n line_main = par(\"mar\")[3] - opar[[\"mar\"]][3] + 1.7 + 0.1\n } else {\n line_main = NULL\n }\n\n if (!is.null(sub)) {\n if (isTRUE(get_tpar(\"side.sub\", 1) == 3)) {\n if (is.null(line_main)) line_main = par(\"mgp\")[3] + 1.7 - .1\n line_main = line_main + 1.2\n }\n if (isTRUE(get_tpar(\"side.sub\", 1) == 3)) {\n line_sub = get_tpar(\"line.sub\", 1.7)\n } else {\n line_sub = get_tpar(\"line.sub\", 4)\n }\n args = list(\n text = sub,\n line = line_sub,\n cex = get_tpar(\"cex.sub\", 1.2),\n col = get_tpar(\"col.sub\", \"black\"),\n adj = get_tpar(c(\"adj.sub\", \"adj\")),\n font = get_tpar(\"font.sub\", 1),\n side = get_tpar(\"side.sub\", 1),\n las = 1\n )\n args = Filter(function(x) !is.null(x), args)\n do.call(mtext, args)\n }\n\n if (!is.null(main)) {\n args = list(\n main = main,\n line = line_main,\n cex.main = get_tpar(\"cex.main\", 1.4),\n col.main = get_tpar(\"col.main\", \"black\"),\n font.main = get_tpar(\"font.main\", 2),\n adj = get_tpar(c(\"adj.main\", \"adj\"), 3))\n args = Filter(function(x) !is.null(x), args)\n do.call(title, args)\n }\n\n\n # Axis titles\n args = list(xlab = xlab)\n args[[\"adj\"]] = get_tpar(c(\"adj.xlab\", \"adj\"))\n do.call(title, args)\n args = list(ylab = ylab)\n args[[\"adj\"]] = get_tpar(c(\"adj.ylab\", \"adj\"))\n do.call(title, args)\n }\n\n #\n ## Exterior plot elements (plot and facet windows, axes, etc.)\n #\n\n omar = NULL # Placeholder variable for now, which we re-assign as part of facet margins\n\n # placeholders for facet_window_args() call\n facet_newlines = facet_text = facet_rect = facet_font = facet_col = facet_bg = facet_border = NULL\n\n if (!is.null(facet) && !add) {\n if (is.null(omar)) omar = par(\"mar\")\n\n # Grab some of the customizable facet args that we'll be using later\n facet_rect = FALSE\n facet_text = .tpar[[\"facet.cex\"]]\n facet_font = .tpar[[\"facet.font\"]]\n facet_col = .tpar[[\"facet.col\"]]\n facet_bg = .tpar[[\"facet.bg\"]]\n facet_border = .tpar[[\"facet.border\"]]\n if (!is.null(facet.args)) {\n if (!is.null(facet.args[[\"cex\"]])) facet_text = facet.args[[\"cex\"]]\n if (!is.null(facet.args[[\"col\"]])) facet_col = facet.args[[\"col\"]]\n if (!is.null(facet.args[[\"font\"]])) facet_font = facet.args[[\"font\"]]\n if (!is.null(facet.args[[\"bg\"]])) facet_bg = facet.args[[\"bg\"]]\n if (!is.null(facet.args[[\"border\"]])) facet_border = facet.args[[\"border\"]]\n }\n if (!is.null(facet_bg) || !is.null(facet_border)) facet_rect = TRUE\n\n # Need extra adjustment to top margin if facet titles have \"\\n\" newline\n # separator. (Note that we'll also need to take account for this in the\n # individual facet margins / gaps further below.)\n facet_newlines = lengths(gregexpr(\"\\n\", grep(\"\\\\n\", facets, value = TRUE)))\n # if (length(facet_newlines)==0) facet_newlines = 0\n # omar[3] = omar[3] + max(facet_newlines)\n facet_newlines = ifelse(length(facet_newlines) == 0, 0, max(facet_newlines))\n omar[3] = omar[3] + facet_newlines * facet_text / cex_fct_adj\n # apply the changes\n par(mar = omar)\n }\n\n # Now draw the individual facet windows (incl. axes, grid lines, and facet titles)\n # Will be skipped if adding to an existing plot; see ?facet\n\n facet_window_args = recordGraphics(\n draw_facet_window(\n add = add,\n # facet-specific args\n cex_fct_adj = cex_fct_adj,\n facet.args = facet.args,\n facet_newlines = facet_newlines, facet_font = facet_font,\n facet_rect = facet_rect, facet_text = facet_text,\n facet_col = facet_col, facet_bg = facet_bg, facet_border = facet_border,\n facet = facet,\n facets = facets, ifacet = ifacet,\n nfacets = nfacets, nfacet_cols = nfacet_cols, nfacet_rows = nfacet_rows,\n # axes args\n axes = axes, flip = flip, frame.plot = frame.plot,\n oxaxis = oxaxis, oyaxis = oyaxis,\n xlabs = xlabs, xlim = xlim, xlim_user = xlim_user, xaxt = xaxt, xaxs = xaxs, xaxb = xaxb, xaxl = xaxl,\n ylabs = ylabs, ylim = ylim, ylim_user = ylim_user, yaxt = yaxt, yaxs = yaxs, yaxb = yaxb, yaxl = yaxl,\n asp = asp, log = log,\n # other args (in approx. alphabetical + group ordering)\n dots = dots,\n draw = draw,\n grid = grid,\n has_legend = has_legend,\n type = type,\n x = x, xmax = xmax, xmin = xmin,\n y = y, ymax = ymax, ymin = ymin\n ),\n list = list(\n add = add,\n cex_fct_adj = cex_fct_adj,\n facet.args = facet.args,\n facet_newlines = facet_newlines, facet_font = facet_font,\n facet_rect = facet_rect, facet_text = facet_text,\n facet_col = facet_col, facet_bg = facet_bg, facet_border = facet_border,\n facet = datapoints$facet,\n facets = facets, ifacet = ifacet,\n nfacets = nfacets, nfacet_cols = nfacet_cols, nfacet_rows = nfacet_rows,\n axes = axes, flip = flip, frame.plot = frame.plot,\n oxaxis = oxaxis, oyaxis = oyaxis,\n xlabs = xlabs, xlim = xlim, xlim_user = xlim_user, xaxt = xaxt, xaxs = xaxs, xaxb = xaxb, xaxl = xaxl,\n ylabs = ylabs, ylim = ylim, ylim_user = ylim_user, yaxt = yaxt, yaxs = yaxs, yaxb = yaxb, yaxl = yaxl,\n asp = asp, log = log,\n dots = dots,\n draw = draw,\n grid = grid,\n has_legend = has_legend,\n type = type,\n x = datapoints$x, xmax = datapoints$xmax, xmin = datapoints$xmin,\n y = datapoints$y, ymax = datapoints$ymax, ymin = datapoints$ymin\n ),\n getNamespace(\"tinyplot\")\n )\n list2env(facet_window_args, environment())\n\n\n #\n ## Interior plot elements\n #\n\n # Finally, we can draw all of the plot elements (points, lines, etc.)\n # We'll do this via a nested loops:\n # 1) Outer loop over facets\n # 2) Inner loop over groups\n\n ## Outer loop over the facets\n for (i in seq_along(split_data)) {\n # Split group-level data again to grab any \"by\" groups\n idata = split_data[[i]]\n iby = idata[[\"by\"]]\n if (!null_by) { ## maybe all(iby==\"\")\n if (isTRUE(by_continuous)) {\n idata[[\"col\"]] = col[round(rescale_num(idata$by, from = range(datapoints$by), to = c(1, 100)))]\n idata[[\"bg\"]] = bg[round(rescale_num(idata$by, from = range(datapoints$by), to = c(1, 100)))]\n idata = list(idata)\n } else {\n idata = lapply(idata, split, iby)\n idata = do.call(function(...) Map(\"list\", ...), idata)\n }\n } else {\n idata = list(idata)\n if (isTRUE(by_continuous)) {\n if (length(col) != 1) {\n idata[[1]][[\"col\"]] = col[round(rescale_num(by, to = c(1, 100)))]\n } else {\n idata[[1]][[\"col\"]] = col\n }\n if (length(bg) != 1) {\n idata[[1]][[\"bg\"]] = bg[round(rescale_num(by, to = c(1, 100)))]\n } else {\n idata[[1]][[\"bg\"]] = bg\n }\n }\n }\n \n # Set the facet \"window\" manually\n # See: https://github.com/grantmcdermott/tinyplot/issues/65\n if (nfacets > 1) {\n mfgi = ceiling(i / nfacet_cols)\n mfgj = i %% nfacet_cols\n if (mfgj == 0) mfgj = nfacet_cols\n par(mfg = c(mfgi, mfgj))\n\n # For free facets, we need to reset par(usr) based extent of that\n # particular facet... which we calculated and saved to the .fusr env var\n # (list) back in draw_facet_window()\n if (isTRUE(facet.args[[\"free\"]])) {\n fusr = get(\".fusr\", envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n par(usr = fusr[[i]])\n }\n }\n\n\n ## Inner loop over the \"by\" groupings\n for (ii in seq_along(idata)) {\n icol = col[ii]\n ibg = bg[ii]\n ipch = pch[ii]\n ilty = lty[ii]\n ilwd = lwd[ii]\n \n ix = idata[[ii]][[\"x\"]]\n iy = idata[[ii]][[\"y\"]]\n iz = idata[[ii]][[\"z\"]]\n ixmin = idata[[ii]]$xmin\n ixmax = idata[[ii]]$xmax\n iymin = idata[[ii]]$ymin\n iymax = idata[[ii]]$ymax\n ilabels = idata[[ii]][[\"labels\"]]\n\n if (isTRUE(by_continuous)) {\n icol = idata[[ii]]$col\n ibg = idata[[ii]]$bg\n }\n\n # empty plot flag\n empty_plot = FALSE\n if (isTRUE(empty) || isTRUE(type == \"n\") || ((length(ix) == 0) && !(type %in% c(\"histogram\", \"hist\", \"rect\", \"segments\", \"spineplot\")))) {\n empty_plot = TRUE\n }\n\n # Draw the individual plot elements...\n if (!isTRUE(empty_plot)) {\n if (is.null(type_draw)) {\n type_draw = switch(type,\n \"ribbon\" = type_ribbon()$draw,\n \"polygon\" = type_polygon()$draw,\n \"rect\" = type_rect()$draw,\n \"p\" = ,\n \"points\" = type_points()$draw,\n \"l\" = ,\n \"o\" = ,\n \"b\" = ,\n \"c\" = ,\n \"h\" = ,\n \"s\" = ,\n \"S\" = type_lines(type = type)$draw\n )\n }\n type_draw(\n ibg = ibg,\n icol = icol,\n ilty = ilty,\n ilwd = ilwd,\n ipch = ipch,\n ix = ix,\n ixmax = ixmax,\n ixmin = ixmin,\n iy = iy,\n iymax = iymax,\n iymin = iymin,\n ilabels = ilabels,\n iz = iz,\n cex = cex,\n dots = dots,\n type = type,\n x_by = x_by,\n by_continuous = by_continuous,\n iby = ii,\n ifacet = i,\n facet_by = facet_by,\n data_facet = idata,\n ngrps = ngrps,\n nfacets = nfacets,\n flip = flip,\n type_info = type_info,\n facet_window_args = facet_window_args\n )\n }\n }\n }\n \n if (!add) {\n # save end pars for possible recall later\n recordGraphics(\n {\n apar = par(no.readonly = TRUE)\n set_saved_par(when = \"after\", apar)\n },\n list = list(), \n env = getNamespace('tinyplot')\n )\n }\n\n}\n\n\n\n\n#' @rdname tinyplot\n#' @importFrom stats as.formula model.frame terms\n#' @export\ntinyplot.formula = function(\n x = NULL,\n data = parent.frame(),\n facet = NULL,\n facet.args = NULL,\n type = NULL,\n xmin = NULL,\n xmax = NULL,\n ymin = NULL,\n ymax = NULL,\n xlim = NULL,\n ylim = NULL,\n # log = \"\",\n main = NULL,\n sub = NULL,\n xlab = NULL,\n ylab = NULL,\n ann = par(\"ann\"),\n axes = TRUE,\n frame.plot = NULL,\n asp = NA,\n grid = NULL,\n pch = NULL,\n col = NULL,\n lty = NULL,\n lwd = NULL,\n restore.par = FALSE,\n formula = NULL,\n subset = NULL,\n na.action = NULL,\n drop.unused.levels = TRUE,\n ...) {\n ## formula for variables must be specified through 'x' or 'formula' but not both\n if (is.null(x)) {\n if (missing(formula)) {\n stop(\"plot formula must be specified by either 'x' or 'formula' argument\")\n }\n } else {\n if (missing(formula)) {\n formula = x\n } else {\n warning(\"only one of the arguments 'x' and 'formula' should be specified, defaulting to the 'formula' argument\")\n }\n }\n\n ## placeholder for legend title\n legend_args = list(x = NULL)\n\n ## turn facet into a formula if it does not evaluate successfully\n if (inherits(try(facet, silent = TRUE), \"try-error\")) {\n facet = as.formula(paste(\"~\", deparse(substitute(facet))))\n environment(facet) = environment(formula)\n }\n\n ## process all formulas\n tf = tinyformula(formula, facet)\n\n ## set up model frame\n m = match.call(expand.dots = FALSE)\n m = m[c(1L, match(c(\"formula\", \"data\", \"subset\", \"na.action\", \"drop.unused.levels\", \"xmin\", \"xmax\", \"ymin\", \"ymax\"), names(m), 0L))]\n m$formula = tf$full\n ## need stats:: for non-standard evaluation\n m[[1L]] = quote(stats::model.frame)\n mf = eval.parent(m)\n\n ## extract x\n x = tinyframe(tf$x, mf)\n xnam = names(x)[[1L]]\n if (length(names(x)) != 1L) warning(\n paste(\"formula should specify exactly one x-variable, using:\", xnam),\n \"\\nif you want to use arithmetic operators, make sure to wrap them inside I()\")\n x = x[[xnam]]\n\n ## extract y (if any)\n y = tinyframe(tf$y, mf)\n if (!is.null(y)) {\n ynam = names(y)[[1L]]\n if (length(names(y)) > 1L) warning(paste(\"formula should specify at most one y-variable, using:\", ynam),\n \"\\nif you want to use arithmetic operators, make sure to wrap them inside I()\")\n y = y[[ynam]]\n }\n\n ## extract by (if any)\n by = tinyframe(tf$by, mf)\n if (!is.null(by)) {\n bynam = names(by)\n by = if (length(bynam) == 1L) by[[bynam]] else interaction(by, sep = \":\")\n }\n\n ## extract x/y facet (if formula)\n if (!is.null(tf$xfacet) || !is.null(tf$yfacet)) {\n xfacet = tinyframe(tf$xfacet, mf)\n yfacet = tinyframe(tf$yfacet, mf)\n if (!is.null(xfacet)) xfacet = if (ncol(xfacet) == 1L) xfacet[[1L]] else interaction(xfacet, sep = \":\")\n if (!is.null(yfacet)) yfacet = if (ncol(yfacet) == 1L) yfacet[[1L]] else interaction(yfacet, sep = \":\")\n if (is.null(yfacet)) {\n facet = xfacet\n } else {\n facet = interaction(xfacet, yfacet, sep = \"~\")\n attr(facet, \"facet_grid\") = TRUE\n attr(facet, \"facet_nrow\") = length(unique(yfacet))\n }\n }\n\n ## nice axis and legend labels\n dens_type = (is.atomic(type) && identical(type, \"density\")) || (!is.atomic(type) && identical(type$name, \"density\"))\n hist_type = (is.atomic(type) && type %in% c(\"hist\", \"histogram\")) || (!is.atomic(type) && identical(type$name, \"histogram\"))\n if (!is.null(type) && dens_type) {\n # if (is.null(ylab)) ylab = \"Density\" ## rather assign ylab as part of internal type_density() logic\n if (is.null(xlab)) xlab = xnam\n } else if (!is.null(type) && hist_type) {\n # if (is.null(ylab)) ylab = \"Frequency\" ## rather assign ylab as part of internal type_histogram() logic\n if (is.null(xlab)) xlab = xnam\n } else if (is.null(y)) {\n if (is.null(ylab)) ylab = xnam\n if (is.null(xlab)) xlab = \"Index\"\n } else {\n if (is.null(ylab)) ylab = ynam\n if (is.null(xlab)) xlab = xnam\n }\n if (!is.null(by)) {\n legend_args[[\"title\"]] = if (length(bynam) == 1L) bynam else sprintf(\"interaction(%s)\", paste(bynam, collapse = \", \"))\n }\n\n tinyplot.default(\n x = x, y = y, by = by,\n facet = facet, facet.args = facet.args,\n data = data,\n type = type,\n xmin = mf[[\"(xmin)\"]],\n xmax = mf[[\"(xmax)\"]],\n ymin = mf[[\"(ymin)\"]],\n ymax = mf[[\"(ymax)\"]],\n xlim = xlim,\n ylim = ylim,\n # log = \"\",\n main = main,\n sub = sub,\n xlab = xlab,\n ylab = ylab,\n ann = ann,\n axes = axes,\n frame.plot = frame.plot,\n asp = asp,\n grid = grid,\n legend_args = legend_args,\n pch = pch,\n col = col,\n lty = lty,\n lwd = lwd,\n restore.par = restore.par,\n ...\n )\n}\n\n#' @rdname tinyplot\n#' @export\ntinyplot.density = function(\n x = NULL,\n type = c(\"l\", \"area\"),\n ...) {\n \n dots = list(...)\n \n if (!is.null(dots[[\"by\"]]) || !is.null(dots[[\"facet\"]])) {\n stop(\n '\\nGrouped and/or faceted plots are no longer supported with the tinyplot.density() method. ',\n '\\nPlease use the dedicated type argument instead, e.g. `tinyplot(..., type = \"density\")`. See `?type_density` for details.',\n '\\n\\nThis breaking change was introduced in tinyplot v0.3.0.'\n )\n }\n \n type = match.arg(type)\n \n ## override if bg = \"by\"\n if (!is.null(dots[[\"bg\"]]) || !is.null(dots[[\"fill\"]])) type = \"area\"\n \n if (inherits(x, \"density\")) {\n object = x\n # legend_args = list(x = NULL)\n # # Grab by label to pass on legend title to tinyplot.default\n # legend_args[[\"title\"]] = deparse(substitute(by))\n } else {\n ## An internal catch for non-density objects that were forcibly\n ## passed to tinyplot.density (e.g., via a one-side formula)\n if (anyNA(x)) {\n x = na.omit(x)\n x = as.numeric(x)\n }\n object = density(x)\n }\n \n x = object$x\n y = object$y\n \n if (type == \"area\") {\n ymin = rep(0, length(y))\n ymax = y\n # # set extra legend params to get bordered boxes with fill\n # legend_args[[\"x.intersp\"]] = 1.25\n # legend_args[[\"lty\"]] = 0\n # legend_args[[\"pt.lwd\"]] = 1\n }\n \n # splice in change arguments\n dots[[\"x\"]] = x\n dots[[\"y\"]] = y\n dots[[\"type\"]] = type\n \n ## axes range\n if (is.null(dots[[\"xlim\"]])) dots[[\"xlim\"]] = range(x)\n if (is.null(dots[[\"ylim\"]])) dots[[\"ylim\"]] = range(y)\n \n ## nice labels and titles\n if (is.null(dots[[\"ylab\"]])) dots[[\"ylab\"]] = \"Density\"\n if (is.null(dots[[\"xlab\"]])) dots[[\"xlab\"]] = paste0(\"N = \", object$n, \" Bandwidth = \", sprintf(\"%.4g\", object$bw))\n if (is.null(dots[[\"main\"]])) dots[[\"main\"]] = paste0(paste(object$call, collapse = \"(x = \"), \")\")\n \n do.call(tinyplot.default, args = dots)\n \n}\n\n\n#' @export\n#' @name plt\n#' @rdname tinyplot\nplt = tinyplot\n"], ["/tinyplot/R/type_polygon.R", "#' Polygon plot type\n#'\n#' @description Type function for plotting polygons.\n#' Arguments are passed to \\code{\\link[graphics]{polygon}}.\n#' \n#' @inheritParams graphics::polygon\n#' \n#' @examples\n#' # \"polygon\" type convenience character string\n#' tinyplot(1:9, c(2,1,2,1,NA,2,1,2,1), type = \"polygon\")\n#' \n#' # Use `type_polygon()` to pass extra arguments for customization\n#' tinyplot(1:9, c(2,1,2,1,NA,2,1,2,1), type = type_polygon(density = c(10, 20)))\n#' \n#' @export\ntype_polygon = function(density = NULL, angle = 45) {\n out = list(\n draw = draw_polygon(density = density, angle = angle),\n data = NULL,\n name = \"polygon\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_polygon = function(density = density, angle = 45) {\n fun = function(ix, iy, icol, ibg, ilty = par(\"lty\"), ilwd = par(\"lwd\"), ...) {\n polygon(\n x = ix,\n y = iy,\n border = icol,\n col = ibg,\n lty = ilty,\n lwd = ilwd,\n density = density,\n angle = angle\n )\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_points.R", "#' Points plot type\n#'\n#' @description Type function for plotting points, i.e. a scatter plot.\n#' \n#' @examples\n#' # \"p\" type convenience character string\n#' tinyplot(Sepal.Length ~ Petal.Length, data = iris, type = \"p\")\n#' \n#' # Same result with type_points()\n#' tinyplot(Sepal.Length ~ Petal.Length, data = iris, type = type_points())\n#' \n#' # Note: Specifying the type here is redundant. Like base plot, tinyplot\n#' # automatically produces a scatter plot if x and y are numeric\n#' tinyplot(Sepal.Length ~ Petal.Length, data = iris)\n#' \n#' # Grouped scatter plot example\n#' tinyplot(Sepal.Length ~ Petal.Length | Species, data = iris)\n#' \n#' # Continuous grouping (with gradient legend)\n#' tinyplot(Sepal.Length ~ Petal.Length | Sepal.Width, data = iris, pch = 19)\n#' \n#' @export\ntype_points = function() {\n out = list(\n draw = draw_points(),\n data = data_points(),\n name = \"p\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\ndata_points = function() {\n fun = function(datapoints, ...) {\n # catch for factors (we should still be able to \"force\" plot these with points)\n if (is.factor(datapoints$x)) {\n xlvls = levels(datapoints$x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n datapoints$x = as.integer(datapoints$x)\n } else {\n xlabs = NULL\n }\n if (is.factor(datapoints$y)) {\n ylvls = levels(datapoints$y)\n ylabs = seq_along(ylvls)\n names(ylabs) = ylvls\n datapoints$y = as.integer(datapoints$y)\n } else {\n ylabs = NULL\n }\n \n out = list(\n datapoints = datapoints,\n xlabs = xlabs,\n ylabs = ylabs\n )\n return(out)\n }\n}\n\ndraw_points = function() {\n fun = function(ix, iy, icol, ibg, ipch, ilwd, cex, ...) {\n points(\n x = ix,\n y = iy,\n col = icol,\n bg = ibg,\n type = \"p\",\n pch = ipch,\n lwd = ilwd,\n cex = cex\n )\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_polypath.R", "#' Polypath polygon type\n#' \n#' @description Type function for plotting polygons.\n#' Arguments are passed to \\code{\\link[graphics]{polypath}}.\n#' \n#' @inheritParams graphics::polypath\n#' \n#' @examples\n#' # \"polypath\" type convenience character string\n#' tinyplot(\n#' c(.1, .1, .6, .6, NA, .4, .4, .9, .9),\n#' c(.1, .6, .6, .1, NA, .4, .9, .9, .4),\n#' type = \"polypath\", fill = \"grey\"\n#' )\n#' \n#' # Use `type_polypath()` to pass extra arguments for customization\n#' tinyplot(\n#' c(.1, .1, .6, .6, NA, .4, .4, .9, .9),\n#' c(.1, .6, .6, .1, NA, .4, .9, .9, .4),\n#' type = type_polypath(rule = \"evenodd\"), fill = \"grey\"\n#' )\n#' @export\ntype_polypath = function(rule = \"winding\") {\n draw_polypath = function() {\n fun = function(ix, iy, icol, ibg, ilty, ilwd, dots, ...) {\n polypath(\n x = ix,\n y = iy,\n border = icol,\n col = ibg,\n lty = ilty,\n lwd = ilwd,\n rule = rule\n )\n }\n return(fun)\n }\n\n out = list(\n draw = draw_polypath(),\n data = NULL,\n name = \"polypath\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n"], ["/tinyplot/R/type_spineplot.R", "#' Spineplot and spinogram types\n#'\n#' @description Type function(s) for producing spineplots and spinograms, which\n#' are modified versions of histograms or mosaic plots, and particularly\n#' useful for visualizing factor variables. Note that [`tinyplot`] defaults\n#' to `type_spineplot()` if `y` is a factor variable.\n#' @param xlevels,ylevels a character or numeric vector specifying the ordering of the\n#' levels of the `x` and `y` variables (if character) or the corresponding indexes\n#' (if numeric) for the plot.\n#' @inheritParams graphics::spineplot\n#' @examples\n#' # \"spineplot\" type convenience string\n#' tinyplot(Species ~ Sepal.Width, data = iris, type = \"spineplot\")\n#' \n#' # Aside: specifying the type is redundant for this example, since tinyplot()\n#' # defaults to \"spineplot\" if y is a factor (just like base plot).\n#' tinyplot(Species ~ Sepal.Width, data = iris)\n#' \n#' # Use `type_spineplot()` to pass extra arguments for customization\n#' tinyplot(Species ~ Sepal.Width, data = iris, type = type_spineplot(breaks = 4))\n#' \n#' p = palette.colors(3, \"Pastel 1\")\n#' tinyplot(Species ~ Sepal.Width, data = iris, type = type_spineplot(breaks = 4, col = p))\n#' rm(p)\n#' \n#' # More idiomatic tinyplot way of drawing the previous plot: use y == by\n#' tinyplot(\n#' Species ~ Sepal.Width | Species, data = iris, type = type_spineplot(breaks = 4),\n#' palette = \"Pastel 1\", legend = FALSE\n#' )\n#' \n#' # Grouped and faceted spineplots\n#' \n#' ttnc = as.data.frame(Titanic)\n#' \n#' tinyplot(\n#' Survived ~ Sex, facet = ~ Class, data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq)\n#' )\n#' \n#' # For grouped \"by\" spineplots, it's better visually to facet as well\n#' tinyplot(\n#' Survived ~ Sex | Class, facet = \"by\", data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq)\n#' )\n#' \n#' # Fancier version. Note the smart inheritance of spacing etc.\n#' tinyplot(\n#' Survived ~ Sex | Class, facet = \"by\", data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq),\n#' palette = \"Dark 2\", facet.args = list(nrow = 1), axes = \"t\"\n#' )\n#'\n#' # Reorder x and y variable categories either by their character levels or numeric indexes\n#' tinyplot(\n#' Survived ~ Sex, facet = ~ Class, data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq, xlevels = c(\"Female\", \"Male\"), ylevels = 2:1)\n#' )\n#'\n#' # Note: It's possible to use \"by\" on its own (without faceting), but the\n#' # overlaid result isn't great. We will likely overhaul this behaviour in a\n#' # future version of tinyplot...\n#' tinyplot(Survived ~ Sex | Class, data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq), alpha = 0.3\n#' )\n#' \n#' @export\ntype_spineplot = function(breaks = NULL, tol.ylab = 0.05, off = NULL, xlevels = NULL, ylevels = NULL, col = NULL, xaxlabels = NULL, yaxlabels = NULL, weights = NULL) {\n col = col\n out = list(\n data = data_spineplot(off = off, breaks = breaks, xlevels = xlevels, ylevels = ylevels, xaxlabels = xaxlabels, yaxlabels = yaxlabels, weights = weights),\n draw = draw_spineplot(tol.ylab = tol.ylab, off = off, col = col, xaxlabels = xaxlabels, yaxlabels = yaxlabels),\n name = \"spineplot\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n#' @importFrom grDevices nclass.Sturges\ndata_spineplot = function(off = NULL, breaks = NULL, xlevels = xlevels, ylevels = ylevels, xaxlabels = NULL, yaxlabels = NULL, weights = NULL) {\n fun = function(\n datapoints,\n by = NULL, col = NULL, bg = NULL, palette = NULL,\n facet = NULL, facet.args = NULL,\n xlim = NULL, ylim = NULL,\n axes = TRUE, xaxt = NULL, yaxt = NULL, xaxb = NULL, yaxb = NULL,\n null_by, null_facet, \n ...\n ) {\n \n ## process weights\n if (!is.null(weights)) {\n ny = length(datapoints$y)\n if (length(weights) != ny && length(weights) != 1L) {\n stop(sprintf(\"'weights' must have either length 1 or %s\", ny))\n }\n }\n datapoints$weights = weights\n \n ## process x variable\n if (is.factor(datapoints$x)) {\n breaks = NULL\n off = if(is.null(off)) 0.02 else off/100\n if (is.null(xlim)) xlim = c(0, 1 + (nlevels(datapoints$x) - 1L) * off)\n } else {\n off = 0\n if (is.null(xlim)) xlim = c(0, 1)\n \t x = as.numeric(datapoints$x)\n if (is.null(breaks)) {\n breaks = if (!is.null(xaxb)) xaxb else if (is.null(weights)) nclass.Sturges(x) else ceiling(log2(sum(weights)) + 1)\n\t }\n breaks = as.numeric(breaks)\n if (length(breaks) == 1L) {\n if (!is.numeric(breaks) || !is.finite(breaks) || breaks < 1L) stop(\"invalid number of 'breaks'\")\n if (breaks > 1e6) {\n warning(gettextf(\"'breaks = %g' is too large and set to 1e6\", breaks))\n breaks = 1000000L\n }\n rg = if (is.null(weights)) range(x, na.rm = TRUE) else range(x[weights > 0], na.rm = TRUE)\n breaks = pretty(rg, n = breaks, min.n = 1L) \n }\n }\n\n ## process y variable\n if (!is.factor(datapoints$y)) datapoints$y = factor(datapoints$y)\n if (is.null(ylim)) ylim = c(0, 1)\n\n ## adjust facet margins\n if (!is.null(facet) && is.null(facet.args[[\"fmar\"]])) {\n facet.args[[\"fmar\"]] = c(2, 2, 2, 2)\n }\n \n x_by = identical(datapoints$x, datapoints$by)\n y_by = identical(datapoints$y, datapoints$by)\n \n x.categorical = is.factor(datapoints$x)\n if (!is.null(xlevels) && x.categorical) {\n xlevels = if(is.numeric(xlevels)) levels(datapoints$x)[xlevels] else xlevels\n if (any(is.na(xlevels)) || !all(xlevels %in% levels(datapoints$x))) warning(\"not all 'xlevels' correspond to levels of 'x'\")\n datapoints$x = factor(datapoints$x, levels = xlevels)\n if (x_by) datapoints$by = datapoints$x\n }\n if (!is.null(ylevels)) {\n ylevels = if(is.numeric(ylevels)) levels(datapoints$y)[ylevels] else ylevels\n if (any(is.na(ylevels)) || !all(ylevels %in% levels(datapoints$y))) warning(\"not all 'ylevels' correspond to levels of 'y'\")\n datapoints$y = factor(datapoints$y, levels = ylevels)\n if (y_by) datapoints$by = datapoints$y\n }\n \n x = datapoints$x\n y = datapoints$y\n \n # if either x_by or y_by are TRUE, we'll only split by facets and then\n # use some simple logic to assign colouring on the backend\n if (isTRUE(x_by) || isTRUE(y_by)) {\n datapoints = split(datapoints, list(datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n } else {\n datapoints = split(datapoints, list(datapoints$by, datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n }\n \n # construct spineplot rectangles and breaks points for each by-facet combo\n datapoints = Map(function(dat, x.categorical, off) {\n ## set up frequency table\n x = dat$x\n if(!x.categorical) {\n x = cut(as.numeric(x), breaks = breaks, include.lowest = TRUE)\n }\n ## TODO: process by grouping via: interaction + spacing + labeling\n ## (for now just do interaction)\n ## FIXME: data_facet only contains the first by group?\n ## if (any(dat$by != \"\")) x = interaction(dat$by, x)\n if(is.null(dat$weights)) {\n tab = table(x, dat$y)\n } else {\n tab = as.table(tapply(dat$weights, list(x, dat$y), FUN = sum, na.rm = TRUE))\n tab[is.na(tab)] = 0\n }\n nx = nrow(tab)\n ny = ncol(tab)\n \n ## compute coordinates\n ## cumulative proportions of x (plus off) vs. conditional cumulative proportions of y\n yat = rbind(0, apply(proportions(tab[, ny:1L, drop = FALSE], 1L), 1L, cumsum))\n yat[is.na(yat)] = 1\n xat = c(0, cumsum(proportions(marginSums(tab, 1L)) + off))\n \n ybottom = as.vector(yat[-(ny + 1L),])\n ytop = as.vector(yat[-1L,])\n xleft = rep(xat[1L:nx], rep(ny, nx))\n xright = rep(xat[2L:(nx+1L)] - off, rep(ny, nx))\n \n out = data.frame(\n by = dat$by[1], # already split\n facet = dat$facet[1], # already split\n ymin = ybottom,\n ymax = ytop,\n xmin = xleft,\n xmax = xright\n )\n \n attr(out, \"nx\") = nx\n attr(out, \"ny\") = ny\n attr(out, \"xat\") = xat\n attr(out, \"yat\") = yat\n return(out)\n }, \n dat = datapoints,\n x.categorical = x.categorical,\n off = off\n )\n \n nx = attr(datapoints[[1]], \"nx\") ## should be the same for all by/facet groups\n ny = attr(datapoints[[1]], \"ny\") ## ditto\n xat = lapply(datapoints, attr, \"xat\")\n yat = lapply(datapoints, attr, \"yat\")\n datapoints = do.call(rbind, datapoints)\n \n if (is.null(yaxlabels)) yaxlabels = rev(levels(y))\n \n ## axis labels\n yaxlabels = if(is.null(yaxlabels)) levels(y) else rep_len(yaxlabels, ny)\n if (!is.null(yaxb)) {\n # yaxlabels = yaxlabels[yaxlabels %in% yaxb]\n ## rather use the \"\" assignment workaround below, since otherwise we \n ## get a mismatch between the label names and ticks \n yaxlabels[!(yaxlabels %in% yaxb)] = \"\"\n }\n if(x.categorical) {\n xaxlabels = if(is.null(xaxlabels)) {\n levels(x)\n } else {\n rep_len(xaxlabels, nx)\n }\n } else {\n xaxlabels = if(is.null(xaxlabels)) {\n if(is.numeric(x)) breaks else c(x[1L], x[c(diff(as.numeric(x)) > 0, TRUE)])\n } else {\n rep_len(xaxlabels, nx + 1L)\n }\n }\n \n # catch for x_by / y/by\n if (isTRUE(x_by)) datapoints$by = factor(rep(xaxlabels, each = ny)) # each x label extends over ny rows\n if (isTRUE(y_by)) datapoints$by = factor(rep(yaxlabels, length.out = nrow(datapoints)))\n \n ## grayscale flag\n grayscale = null_by && is.null(palette) && is.null(.tpar[[\"palette.qualitative\"]])\n \n out = list(\n x = c(datapoints$xmin, datapoints$xmax), \n y = c(datapoints$ymin, datapoints$ymax),\n ymin = datapoints$ymin, \n ymax = datapoints$ymax, \n xmin = datapoints$xmin, \n xmax = datapoints$xmax, \n col = col,\n bg = bg,\n datapoints = datapoints,\n by = if (null_by) by else datapoints$by, \n facet = if (null_facet) facet else datapoints$facet,\n axes = FALSE,\n frame.plot = FALSE,\n xaxt = \"n\",\n yaxt = \"n\",\n xaxs = \"i\",\n yaxs = \"i\",\n ylabs = yaxlabels,\n type_info = list(\n off = off,\n x.categorical = x.categorical,\n nx = nx,\n ny = ny,\n xat = xat,\n yat = yat,\n xaxlabels = xaxlabels,\n yaxlabels = yaxlabels,\n breaks = breaks,\n axes = axes,\n xaxt = xaxt, \n yaxt = yaxt,\n grayscale = grayscale,\n x_by = x_by,\n y_by = y_by\n ),\n facet.args = facet.args\n )\n \n return(out)\n \n }\n return(fun)\n}\n\n#' @importFrom grDevices gray.colors\ndraw_spineplot = function(tol.ylab = 0.05, off = NULL, col = NULL, xaxlabels = NULL, yaxlabels = NULL) {\n fun = function(ixmin, iymin, ixmax, iymax, ilty, ilwd, icol, ibg, \n flip,\n facet_window_args,\n type_info,\n ifacet,\n ...) {\n \n if (is.null(off)) off = type_info[[\"off\"]]\n if (is.null(xaxlabels)) xaxlabels = type_info[[\"xaxlabels\"]]\n if (is.null(yaxlabels)) yaxlabels = type_info[[\"yaxlabels\"]]\n xat = type_info[[\"xat\"]][[ifacet]]\n yat = type_info[[\"yat\"]][[ifacet]]\n nx = type_info[[\"nx\"]]\n ny = type_info[[\"ny\"]]\n x.categorical = type_info[[\"x.categorical\"]]\n grayscale = type_info[[\"grayscale\"]]\n x_by = type_info[[\"x_by\"]]\n y_by = type_info[[\"y_by\"]]\n \n ## graphical parameters\n if (is.null(col)) {\n if (is.null(ibg)) ibg = icol\n if (isFALSE(y_by)) {\n ibg = if (isTRUE(grayscale)) gray.colors(ny) else seq_palette(ibg, ny)\n }\n ibg = rep_len(ibg, ny)\n } else {\n ibg = col\n }\n \n if (type_info[[\"xaxt\"]] %in% c(\"l\", \"t\", \"n\") &&\n type_info[[\"yaxt\"]] %in% c(\"l\", \"t\", \"n\") &&\n !all(c(type_info[[\"xaxt\"]], type_info[[\"yaxt\"]]) == \"n\")) ilwd = 0\n \n rect(\n xleft = ixmin, ybottom = iymin, xright = ixmax, ytop = iymax,\n lty = ilty,\n lwd = ilwd,\n border = par(\"fg\"), #icol,\n col = ibg\n )\n \n ## axes\n ## - standard categorical axes (xaxt/yaxt == \"s\") _without_ ticks\n ## - never draw additional axis lines, box always for spinogram\n if(type_info[[\"axes\"]]) {\n if (x.categorical) {\n spine_axis(if (flip) 2 else 1, at = (xat[1L:nx] + xat[2L:(nx+1L)] - off)/2, labels = xaxlabels,\n type = type_info[[\"xaxt\"]], categorical = TRUE)\n } else {\n spine_axis(if (flip) 2 else 1, at = xat, labels = xaxlabels,\n type = type_info[[\"xaxt\"]], categorical = FALSE)\n }\n yat = yat[, if(flip) ncol(yat) else 1L]\n equidist = any(diff(yat) < tol.ylab)\n yat = if(equidist) seq.int(1/(2*ny), 1-1/(2*ny), by = 1/ny) else (yat[-1L] + yat[-length(yat)])/2\n spine_axis(if (flip) 3 else 2, at = yat, labels = yaxlabels,\n type = type_info[[\"yaxt\"]], categorical = TRUE)\n if (is_facet_position(if(flip) \"bottom\" else \"right\", ifacet, facet_window_args)) spine_axis(if (flip) 1 else 4,\n type = type_info[[\"yaxt\"]], categorical = FALSE)\n }\n if(!x.categorical && (is.null(ilwd) || ilwd > 0)) box()\n \n }\n return(fun)\n}\n\n\n\n\nspine_axis = function(side, ..., type = \"standard\", categorical = TRUE) {\n type = match.arg(type, c(\"standard\", \"none\", \"labels\", \"ticks\", \"axis\"))\n ## standard: with axis, ticks (unless categorical), and labels\n ## none: no axes\n ## labels: only labels without ticks and axis line\n ## ticks: only ticks and labels without axis line\n ## axis: only axis line and labels but no ticks\n\n if (type == \"none\") {\n invisible(numeric(0L))\n } else {\n args = list(side = side, ...)\n if (type == \"labels\") {\n args$tick = FALSE\n } else if (type == \"ticks\") {\n args$lwd = 0\n if (!(\"lwd.ticks\" %in% names(args))) args$lwd.ticks = if (categorical) 0 else 1\n } else if (type == \"axis\") {\n if (categorical) {\n args$tick = FALSE\n } else {\n args$lwd.ticks = 0\n }\n } else {\n args$tick = !categorical\n }\n do.call(\"axis\", args)\n }\n}\n\n#' @importFrom grDevices col2rgb convertColor hcl\nto_hcl = function(x) {\n x = t(col2rgb(x, alpha = TRUE)/255)\n alpha = x[, 4]\n x = x[, 1:3]\n x = convertColor(x, from = \"sRGB\", to = \"Luv\")\n x = cbind(H = atan2(x[, 3L], x[, 2L]) * 180/pi, C = sqrt(x[, 2L]^2 + x[, 3L]^2), L = x[, 1L])\n x[is.na(x[, 1L]), 1L] = 0\n x[x[, 1L] < 0, 1L] = x[x[, 1L] < 0, 1L] + 360\n attr(x, \"alpha\") = alpha\n return(x)\n}\n\nseq_palette = function(x, n, power = 1.5) {\n x = drop(to_hcl(x[1L]))\n alpha = attr(x, \"alpha\")\n hcl(\n h = x[1L],\n c = seq.int(from = x[2L]^(1/power), to = 0, length.out = n + 1)[1L:n]^power,\n l = 100 - seq.int(from = (100 - x[3L])^(1/power), to = pmin(8, (100 - x[3L])/2)^(1/power), length.out = n)^power,\n alpha = alpha\n )[1L:n]\n}\n"], ["/tinyplot/R/type_qq.R", "#' Quantile-Quantile plot (QQ)\n#'\n#' @description Plots the theoretical quantiles of `x` on the horizontal axis\n#' against observed values of `x` on the vertical axis.\n#'\n#' @param distribution Distribution function to use.\n#' @examples\n#' tinyplot(~mpg, data = mtcars, type = type_qq())\n#'\n#' # suppress the line\n#' tinyplot(~mpg, data = mtcars, lty = 0, type = type_qq())\n#' @importFrom stats qnorm ppoints quantile\n#' @export\ntype_qq = function(distribution = qnorm) {\n data_qq = function(distribution) {\n fun = function(datapoints, ...) {\n y = sort(datapoints$y)\n x = datapoints$x\n x = distribution(ppoints(x))\n datapoints$x = x\n datapoints$y = y\n out = list(datapoints = datapoints)\n return(out)\n }\n }\n\n draw_qq = function() {\n fun = function(ix, iy, icol, ibg, ipch, ilwd, ilty, cex, xlab, ...) {\n points(\n x = ix,\n y = iy,\n col = icol,\n bg = ibg,\n type = \"p\",\n pch = ipch,\n lwd = ilwd,\n cex = cex\n )\n\n if (!is.null(ilty)) {\n iy <- quantile(iy, c(0.25, 0.75))\n ix <- quantile(ix, c(0.25, 0.75))\n slope <- diff(iy) / diff(ix)\n intercept <- iy[1] - slope * ix[1]\n abline(a = intercept, b = slope, lty = ilty, col = icol, lwd = ilwd)\n }\n }\n return(fun)\n }\n\n out = list(\n draw = draw_qq(),\n data = data_qq(distribution = distribution),\n name = \"qq\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_abline.R", "#' Add straight lines to a plot\n#' @description\n#' These functions add straight line(s) through the current plot.\n#' @details\n#' While `type_abline`, `type_hline`, and `type_vline` can be called in a base\n#' plot layer, we expect that they will typically be called as subsequent\n#' layers via [`tinyplot_add`].\n#' @section Recycling logic: \n#' The recycling behaviour of the line parameters (i.e., `a`, `b`, `h`, or `v`)\n#' is adaptive, depending on whether `by` or `facet` grouping is detected. While\n#' this leads to different recycling scenarios, the underlying code logic\n#' follows sensible heuristics designed to match user expectations.\n#' \n#' Parameter lengths must equal one of four options:\n#' \n#' 1. Single value (i.e., length = 1), i.e. simplest case where the same line is\n#' applied uniformly across all groups and facets. Uses the default user colour\n#' (e.g. `\"black\"`, or `tpar(\"palette.qualitative\")[1]` if a theme is set).\n#' 2. Number of `by` groups, i.e. one parameter per group. For example,\n#' `tinyplot(mpg ~ wt | factor(cyl), data = mtcars, type = type_hline(h = 21:23))`\n#' will give three horizontal lines, with colours matching the user's qualitative\n#' palette.\n#' 3. Number of `facet` groups, i.e. one parameter per facet panel. For example:\n#' `tinyplot(mpg ~ wt, facet = ~am, data = mtcars, type = type_hline(h = c(20,30)))`\n#' would give separate horizontal lines per facet, but both using the same\n#' default color.\n#' 4. Product of `by` and `facet` groups, i.e. one parameter for each unique\n#' by-facet combination. Orders over facets first and then, within that, by\n#' group. For example:\n#' `tinyplot(mpg ~ wt | factor(cyl), facet = ~am, data = mtcars, type = type_hline(h = 21:26))`\n#' will give six separate lines, with the first three (`21:23`) coloured by\n#' group in the first facet, and second three (`24:26`) coloured by by group\n#' in the second facet.\n#' \n#' Alongside these general rules, we also try to accomodate special cases when\n#' other aesthetic parameters like `lwd` or `lty` are invoked by the user. See\n#' Examples.\n#' \n#' @param a,b the intercept (default: `a` = 0) and slope (default: `b` = 1)\n#' terms. Numerics of length 1, or equal to the number of groups or number of\n#' facets (or the product thereof).\n#' @examples\n#' #\n#' ## abline\n#' \n#' tinyplot(x = -10:10, y = rnorm(21) + -10:10, grid = TRUE)\n#' tinyplot_add(type = \"abline\")\n#' # same as...\n#' # tinyplot_add(type = type_abline(a = 0, b = 1))\n#' \n#' # customize by passing bespoke intercept and slope values\n#' tinyplot_add(type = type_abline(a = -1, b = -0.5))\n#' \n#' # note that calling as abline & co. as a base plot layer will still lead to\n#' # axes limits that respect the range of the data\n#' tinyplot(x = -10:10, y = -10:10, grid = TRUE, type = \"abline\")\n#' \n#' #\n#' ## hline and vline\n#'\n#' # Base plot layer\n#' tinyplot(mpg ~ hp | cyl, facet = \"by\", data = mtcars, ylim = c(0, 40))\n#' \n#' # Add horizontal lines at the (default) 0 y-intercept\n#' tinyplot_add(type = \"hline\", col = \"grey\")\n#' \n#' # Note that group+facet aesthetics will be inherited. We can use this to\n#' # add customized lines (here: the mean `mpg` for each `cyl` group) \n#' tinyplot_add(type = type_hline(with(mtcars, tapply(mpg, cyl, mean))), lty = 2)\n#' \n#' # Similar idea for vline\n#' tinyplot_add(type = type_vline(with(mtcars, tapply(hp, cyl, mean))), lty = 2)\n#' \n#' #\n#' ## Recycling logic\n#' \n#' # length(h) == no. of groups\n#' tinyplot(mpg ~ wt | factor(cyl), data = mtcars, type = type_hline(h = 21:23))\n#' \n#' # length(h) == no. of facets\n#' tinyplot(mpg ~ wt, facet = ~am, data = mtcars, type = type_hline(h = c(20, 30)))\n#' \n#' # length(h) == no. of groups x no. of facets\n#' tinyplot(mpg ~ wt | factor(cyl), facet = ~am, data = mtcars,\n#' type = type_hline(h = 21:26))\n#' \n#' # special adjustment case (here: lwd by group)\n#' tinyplot(mpg ~ wt | factor(cyl), facet = ~am, data = mtcars,\n#' type = type_hline(c(20, 30)), lwd = c(21, 14, 7))\n#' \n#' @export\ntype_abline = function(a = 0, b = 1) {\n data_abline = function(datapoints, lwd, lty, col, ...) {\n if (nrow(datapoints) == 0) {\n msg = \"`type_abline() only works on existing plots with x and y data points.\"\n stop(msg, call. = FALSE)\n }\n # keep track of unique lty and lwd (needed for group catch / escape hatch\n # later in draw_hline)\n ul_lwd = length(unique(lwd))\n ul_lty = length(unique(lty))\n ul_col = length(unique(col))\n return(list(type_info = list(ul_lty = ul_lty, ul_lwd = ul_lwd, ul_col = ul_col)))\n }\n draw_abline = function() {\n fun = function(\n ifacet, iby, data_facet, icol, ilty, ilwd,\n ngrps, nfacets, by_continuous, facet_by,\n type_info,\n ...\n ) {\n \n # flag for aesthetics by groups\n grp_aes = type_info[[\"ul_col\"]] == 1 || type_info[[\"ul_lty\"]] == ngrps || type_info[[\"ul_lwd\"]] == ngrps\n \n if (length(a) != 1) {\n if (!length(a) %in% c(ngrps, nfacets, ngrps*nfacets)) {\n msg = \"Length of 'a' must be 1, or equal to the number of facets or number of groups (or product thereof).\"\n stop(msg, call. = FALSE)\n }\n if (!facet_by && length(a) == nfacets) {\n a = a[ifacet]\n if (!grp_aes && type_info[[\"ul_col\"]]!=ngrps) {\n icol = 1\n } else if (by_continuous) {\n icol = 1\n }\n } else if (!by_continuous && length(a) == ngrps * nfacets) {\n a = a[ifacet * ngrps - c(ngrps - iby)]\n } else if (!by_continuous) {\n a = a[iby]\n }\n } else if (!grp_aes) {\n icol = 1\n }\n \n if (length(b) != 1) {\n if (!length(b) %in% c(ngrps, nfacets, ngrps*nfacets)) {\n msg = \"Length of 'b' must be 1, or equal to the number of facets or number of groups (or product thereof).\"\n stop(msg, call. = FALSE)\n }\n if (!facet_by && length(b) == nfacets) {\n b = b[ifacet]\n if (!grp_aes && type_info[[\"ul_col\"]]!=ngrps) {\n icol = 1\n } else if (by_continuous) {\n icol = 1\n }\n } else if (!by_continuous && length(b) == ngrps * nfacets) {\n b = b[ifacet * ngrps - c(ngrps - iby)]\n } else if (!by_continuous) {\n b = b[iby]\n }\n } else if (!grp_aes) {\n icol = 1\n }\n \n if (type_info[[\"ul_col\"]]!=1 && !(type_info[[\"ul_lty\"]]==ngrps || type_info[[\"ul_lwd\"]]==ngrps)) {\n icol = 1\n }\n\n abline(a = a, b = b, col = icol, lty = ilty, lwd = ilwd)\n }\n return(fun)\n }\n out = list(\n draw = draw_abline(),\n data = data_abline,\n name = \"abline\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_pointrange.R", "#' @rdname type_errorbar\n#' @export\ntype_pointrange = function() {\n out = list(\n draw = draw_pointrange(),\n data = data_pointrange(),\n name = \"p\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\n\ndraw_pointrange = function() {\n fun = function(ix, iy, ixmin, iymin, ixmax, iymax, icol, ibg, ipch, ilwd, cex, ...) {\n segments(\n x0 = ixmin,\n y0 = iymin,\n x1 = ixmax,\n y1 = iymax,\n col = icol,\n lwd = ilwd\n )\n draw_points()(ix = ix, iy = iy, icol = icol, ibg = ibg, ipch = ipch, ilwd = ilwd, cex = cex)\n }\n return(fun)\n}\n\n\ndata_pointrange = function() {\n fun = function(datapoints, xlabs, ...) {\n if (is.character(datapoints$x)) datapoints$x = as.factor(datapoints$x)\n if (is.factor(datapoints$x)) {\n ## original data (i.e., no new sorting by factor)\n xlvls = unique(datapoints$x)\n datapoints$x = factor(datapoints$x, levels = xlvls)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n datapoints$x = as.integer(datapoints$x)\n }\n datapoints$xmin = datapoints$x\n datapoints$xmax = datapoints$x\n out = list(\n x = datapoints$x,\n xlabs = xlabs,\n datapoints = datapoints)\n\n return(out)\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_rect.R", "#' Rectangle plot type\n#'\n#' @description Type function for plotting rectangles.\n#' \n#' @details Contrary to base \\code{\\link[graphics]{rect}}, rectangles in\n#' [tinyplot] must be specified using the `xmin`, `ymin`,`xmax`, and `ymax`\n#' arguments. \n#' \n#' @examples\n#' i = 4*(0:10)\n#' \n#' # \"rect\" type convenience character string\n#' tinyplot(\n#' xmin = 100+i, ymin = 300+i, xmax = 150+i, ymax = 380+i,\n#' by = i, fill = 0.2,\n#' type = \"rect\"\n#' )\n#' \n#' # Same result with type_rect()\n#' tinyplot(\n#' xmin = 100+i, ymin = 300+i, xmax = 150+i, ymax = 380+i,\n#' by = i, fill = 0.2,\n#' type = type_rect()\n#' )\n#' \n#' @export\ntype_rect = function() {\n out = list(\n draw = draw_rect(),\n data = NULL,\n name = \"rect\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_rect = function() {\n fun = function(ixmin, iymin, ixmax, iymax, ilty, ilwd, icol, ibg, ...) {\n rect(\n xleft = ixmin, ybottom = iymin, xright = ixmax, ytop = iymax,\n lty = ilty,\n lwd = ilwd,\n border = icol,\n col = ibg\n )\n }\n return(fun)\n}\n"], ["/tinyplot/R/facet.R", "#' Draw facet windows\n#' \n#' @description Internal functions called from `tinyplot` in order to draw the\n#' plot window with different facets, grids, axes, etc. \n#' \n#' `facet_layout` determines the layout of the facets, based on a set of inputs.\n#' \n#' `draw_facet_window` is the main workhorse function for setting the exterior\n#' plot elements as part of a `tinyplot` call, including adjustment of margins\n#' for dynamic themes, etc.\n#' \n#' @keywords internal\n#' @rdname facet\ndraw_facet_window = function(\n # add arg first, since that determines what happens (if at all)\n add,\n # facet-specific args\n cex_fct_adj,\n facet.args,\n facet_newlines, facet_font, facet_rect, facet_text,\n facet_col, facet_bg, facet_border,\n facet, facets, ifacet,\n nfacets, nfacet_cols, nfacet_rows,\n # axes args\n axes, flip, frame.plot, oxaxis, oyaxis,\n xlabs, xlim, xlim_user, xaxt, xaxs, xaxb, xaxl,\n ylabs, ylim, ylim_user, yaxt, yaxs, yaxb, yaxl,\n asp, log,\n # other args (in approx. alphabetical + group ordering)\n dots,\n draw,\n grid,\n has_legend,\n type,\n x, xmax, xmin,\n y, ymax, ymin\n ) {\n \n # if add is TRUE, just return inputs without any calculations\n if (isTRUE(add)) {\n return(as.list(environment()))\n }\n \n # if breaks are provided use these (but only if x/ylabs are null)\n if (!is.null(xaxb) && !is.null(xlabs)) xlabs = xaxb\n if (!is.null(yaxb) && !is.null(ylabs)) ylabs = yaxb\n \n # draw background color only in the grid rectangle\n grid.bg = get_tpar(\"grid.bg\")\n if (!is.null(grid.bg)) {\n corners = par(\"usr\")\n rect(corners[1], corners[3], corners[2], corners[4], col = grid.bg, border = NA)\n }\n\n ## dynamic margins flag\n dynmar = isTRUE(.tpar[[\"dynmar\"]])\n \n ## optionally allow to modify the style of axis interval calculation\n if (!is.null(xaxs)) par(xaxs = xaxs)\n if (!is.null(yaxs)) par(yaxs = yaxs)\n\n if (nfacets > 1) {\n # Set facet margins (i.e., gaps between facets)\n if (is.null(facet.args[[\"fmar\"]])) {\n fmar = tpar(\"fmar\")\n } else {\n if (length(facet.args[[\"fmar\"]]) != 4) {\n warning(\n \"`fmar` has to be a vector of length four, e.g.\",\n \"`facet.args = list(fmar = c(b,l,t,r))`.\",\n \"\\n\",\n \"Resetting to fmar = c(1,1,1,1) default.\",\n \"\\n\"\n )\n fmar = tpar(\"fmar\")\n } else {\n fmar = facet.args[[\"fmar\"]]\n }\n }\n # We need to adjust for n>=3 facet cases for correct spacing...\n if (nfacets >= 3) {\n ## ... exception for 2x2 cases\n if (!(nfacet_rows == 2 && nfacet_cols == 2)) fmar = fmar * .75\n }\n # Extra reduction if no plot frame to reduce whitespace\n if (isFALSE(frame.plot) && !isTRUE(facet.args[[\"free\"]])) {\n fmar = fmar - 0.5\n }\n\n ooma = par(\"oma\")\n\n # Bump top margin down for facet titles\n fmar[3] = fmar[3] + 1\n if (isTRUE(attr(facet, \"facet_grid\"))) {\n fmar[3] = max(0, fmar[3] - 1)\n # Indent for RHS facet_grid title strip if \"right!\" legend\n if (has_legend && ooma[4] > 0) ooma[4] = ooma[4] + 1\n }\n fmar[3] = fmar[3] + facet_newlines * facet_text / cex_fct_adj\n\n omar = par(\"mar\")\n \n ## Dynamic plot margin adjustments\n if (dynmar) {\n if (par(\"las\") %in% 1:2) {\n # extra whitespace bump on the y axis\n ## overrides for ridge and some types that use integer spacing with (named) axis labels ## FXIME\n if (type == \"ridge\") {\n yaxlabs = levels(y)\n } else if (!is.null(ylabs)) {\n yaxlabs = if (!is.null(names(ylabs))) names(ylabs) else ylabs \n } else if (type == \"boxplot\" && isTRUE(flip) && !is.null(xlabs)) {\n yaxlabs = if (!is.null(names(xlabs))) names(xlabs) else xlabs \n } else {\n # yaxl = axTicks(2)\n yaxlabs = axisTicks(usr = extendrange(ylim, f = 0.04), log = par(\"ylog\"))\n }\n if (!is.null(yaxl)) yaxlabs = tinylabel(yaxlabs, yaxl)\n # whtsbp = grconvertX(max(strwidth(yaxl, \"figure\")), from = \"nfc\", to = \"lines\") - 1\n whtsbp = grconvertX(max(strwidth(yaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - grconvertX(0, from = \"nfc\", to = \"lines\") - 1\n if (whtsbp > 0) {\n omar = omar + c(0, whtsbp, 0, 0) * cex_fct_adj\n fmar[2] = fmar[2] + whtsbp * cex_fct_adj\n }\n # Extra reduction if no plot frame to reduce whitespace\n if (isFALSE(frame.plot) && !isTRUE(facet.args[[\"free\"]])) {\n fmar[2] = fmar[2] - (whtsbp * cex_fct_adj)\n }\n }\n if (par(\"las\") %in% 2:3) {\n # extra whitespace bump on the x axis\n # xaxlabs = axTicks(1)\n xaxlabs = if (is.null(xlabs)) axisTicks(usr = extendrange(xlim, f = 0.04), log = par(\"xlog\")) else \n if (!is.null(names(xlabs))) names(xlabs) else xlabs\n if (!is.null(xaxl)) xaxlabs = tinylabel(xaxlabs, xaxl)\n whtsbp = grconvertX(max(strwidth(xaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - 1\n if (whtsbp > 0) {\n omar = omar + c(whtsbp, 0, 0, 0) * cex_fct_adj\n fmar[1] = fmar[1] + whtsbp * cex_fct_adj\n }\n # Extra reduction if no plot frame to reduce whitespace\n if (isFALSE(frame.plot) && !isTRUE(facet.args[[\"free\"]])) {\n fmar[1] = fmar[1] - (whtsbp * cex_fct_adj)\n }\n }\n # FIXME: Is this causing issues for lhs legends with facet_grid?\n # catch for missing rhs legend\n if (isTRUE(attr(facet, \"facet_grid\")) && !has_legend) {\n omar[4] = omar[4] + 1\n }\n }\n\n # Now we set the margins. The trick here is that we simultaneously adjust\n # inner (mar) and outer (oma) margins by the same amount, but in opposite\n # directions, to preserve the overall facet and plot centroids.\n nmar = (fmar + .1) / cex_fct_adj\n noma = (ooma + omar - fmar - .1) / cex_fct_adj\n # Catch in case of negative oma values. (Probably only occurs with some\n # user-supplied tpar(lmar) values and a \"left!\" positioned legend.)\n if (any(noma < 0)) {\n noma_orig = noma\n noma[noma < 0] = 0\n # noma_diff = noma-noma_orig\n # nmar = nmar + noma_diff\n }\n # apply changes\n par(oma = noma)\n par(mar = nmar)\n\n # Now that the margins have been set, arrange facet rows and columns based\n # on our earlier calculations.\n par(mfrow = c(nfacet_rows, nfacet_cols))\n } else if (dynmar) {\n # Dynamic plot margin adjustments\n omar = par(\"mar\")\n omar = omar - c(0, 0, 1, 0) # reduce top whitespace since no facet (title)\n if (type == \"spineplot\") omar[4] = 2.1 # FIXME catch for spineplot RHS axis labs\n if (par(\"las\") %in% 1:2) {\n # extra whitespace bump on the y axis\n ## overrides for ridge and some types that use integer spacing with (named) axis labels ## FXIME\n if (type == \"ridge\") {\n yaxlabs = levels(y)\n } else if (!is.null(ylabs)) {\n yaxlabs = if (!is.null(names(ylabs))) names(ylabs) else ylabs \n } else if (type == \"boxplot\" && isTRUE(flip) && !is.null(xlabs)) {\n yaxlabs = if (!is.null(names(xlabs))) names(xlabs) else xlabs \n } else {\n # yaxl = axTicks(2)\n yaxlabs = axisTicks(usr = extendrange(ylim, f = 0.04), log = par(\"ylog\"))\n }\n if (!is.null(yaxl)) yaxlabs = tinylabel(yaxlabs, yaxl)\n # whtsbp = grconvertX(max(strwidth(yaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - 1\n whtsbp = grconvertX(max(strwidth(yaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - grconvertX(0, from = \"nfc\", to = \"lines\") - 1\n if (whtsbp > 0) {\n omar[2] = omar[2] + whtsbp\n }\n }\n if (par(\"las\") %in% 2:3) {\n # extra whitespace bump on the x axis\n # xaxl = axTicks(1)\n xaxlabs = if (is.null(xlabs)) axisTicks(usr = extendrange(xlim, f = 0.04), log = par(\"xlog\")) else \n if (!is.null(names(xlabs))) names(xlabs) else xlabs\n if (!is.null(xaxl)) xaxlabs = tinylabel(xaxlabs, xaxl)\n whtsbp = grconvertX(max(strwidth(xaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - 1\n if (whtsbp > 0) {\n omar[1] = omar[1] + whtsbp\n }\n }\n par(mar = omar)\n }\n\n ## Loop over the individual facet windows and draw the plot region\n ## components (axes, titles, box, grid, etc.)\n for (ii in ifacet) {\n # See: https://github.com/grantmcdermott/tinyplot/issues/65\n if (nfacets > 1) {\n mfgi = ceiling(ii / nfacet_cols)\n mfgj = ii %% nfacet_cols\n if (mfgj == 0) mfgj = nfacet_cols\n par(mfg = c(mfgi, mfgj))\n }\n\n ## Set the plot window\n ## Problem: Passing extra args through ... (e.g., legend_args) to plot.window\n ## triggers an annoying warning about unrecognized graphical params.\n # plot.window(\n # xlim = xlim, ylim = ylim,\n # asp = asp, log = log,\n # # ...\n # )\n ## Solution: Only pass on relevant args using name checking and do.call.\n ## Idea borrowed from here: https://stackoverflow.com/a/4128401/4115816\n pdots = dots[names(dots) %in% names(formals(plot.default))]\n ## catch for flipped boxplots...\n if (type == \"boxplot\" && isTRUE(flip)) {\n log_flip = log\n if (!is.null(log)) {\n if (log == \"x\") log_flip = \"y\"\n if (log == \"y\") log_flip = \"x\"\n }\n do.call(\n \"plot.window\",\n c(list(xlim = ylim, ylim = xlim, asp = asp, log = log_flip), pdots)\n )\n xside = 2\n yside = 1\n } else {\n ## ... standard plot window for all other cases\n do.call(\n \"plot.window\",\n c(list(xlim = xlim, ylim = ylim, asp = asp, log = log), pdots)\n )\n xside = 1\n yside = 2\n }\n\n\n # axes, frame.plot and grid\n if (isTRUE(axes) || isTRUE(facet.args[[\"free\"]])) {\n args_x = list(x,\n side = xside,\n type = xaxt,\n labeller = xaxl,\n cex = get_tpar(c(\"cex.xaxs\", \"cex.axis\"), 0.8),\n lwd = get_tpar(c(\"lwd.xaxs\", \"lwd.axis\"), 1),\n lty = get_tpar(c(\"lty.xaxs\", \"lty.axis\"), 1)\n )\n args_y = list(y,\n side = yside,\n type = yaxt,\n labeller = yaxl,\n cex = get_tpar(c(\"cex.yaxs\", \"cex.axis\"), 0.8),\n lwd = get_tpar(c(\"lwd.yaxs\", \"lwd.axis\"), 1),\n lty = get_tpar(c(\"lty.yaxs\", \"lty.axis\"), 1)\n )\n if (!is.null(xaxb)) args_x$at = xaxb\n if (!is.null(yaxb)) args_y$at = yaxb\n type_range_x = type %in% c(\"barplot\", \"pointrange\", \"errorbar\", \"ribbon\", \"boxplot\", \"p\", \"violin\") && !is.null(xlabs)\n type_range_y = !is.null(ylabs) && (type == \"p\" || (isTRUE(flip) && type %in% c(\"barplot\", \"pointrange\", \"errorbar\", \"ribbon\", \"boxplot\", \"violin\")))\n if (type_range_x) {\n args_x = modifyList(args_x, list(at = xlabs, labels = names(xlabs)))\n }\n if (type_range_y) {\n args_y = modifyList(args_y, list(at = ylabs, labels = names(ylabs)))\n }\n\n if (isTRUE(facet.args[[\"free\"]]) && (par(\"xlog\") || par(\"ylog\"))) {\n warning(\n \"\\nFree scale axes for faceted plots are currently not supported if the axes are logged. Reverting back to fixed scales.\",\n \"\\nIf support for this feature is important to you, please raise an issue on our GitHub repo:\",\n \"\\nhttps://github.com/grantmcdermott/tinyplot/issues\\n\"\n )\n facet.args[[\"free\"]] = FALSE\n }\n\n # Special logic if facets are free...\n if (isTRUE(facet.args[[\"free\"]])) {\n # First, we need to calculate the plot extent and axes range of each\n # individual facet.\n xfree = split(c(x, xmin, xmax), facet)[[ii]]\n yfree = split(c(y, ymin, ymax), facet)[[ii]]\n if (!xlim_user) xlim = range(xfree, na.rm = TRUE)\n if (!ylim_user) ylim = range(yfree, na.rm = TRUE)\n xext = extendrange(xlim, f = 0.04)\n yext = extendrange(ylim, f = 0.04)\n # We'll save this in a special .fusr env var (list) that we'll re-use\n # when it comes to plotting the actual elements later\n if (ii == 1) {\n fusr = replicate(4, vector(\"double\", length = nfacets), simplify = FALSE)\n assign(\".fusr\", fusr, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n }\n fusr = get(\".fusr\", envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n fusr[[ii]] = c(xext, yext)\n assign(\".fusr\", fusr, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n # Explicitly set (override) the current facet extent\n par(usr = fusr[[ii]])\n # if plot frame is true then print axes per normal...\n if (type %in% c(\"barplot\", \"pointrange\", \"errorbar\", \"ribbon\", \"boxplot\", \"p\", \"violin\") && !is.null(xlabs)) {\n tinyAxis(xfree, side = xside, at = xlabs, labels = names(xlabs), type = xaxt, labeller = xaxl)\n } else {\n tinyAxis(xfree, side = xside, type = xaxt, labeller = xaxl)\n }\n if (isTRUE(flip) && type %in% c(\"barplot\", \"pointrange\", \"errorbar\", \"ribbon\", \"boxplot\", \"p\", \"violin\") && !is.null(ylabs)) {\n tinyAxis(yfree, side = yside, at = ylabs, labels = names(ylabs), type = yaxt, labeller = yaxl)\n } else {\n tinyAxis(yfree, side = yside, type = yaxt, labeller = yaxl)\n }\n\n # For fixed facets we can just reuse the same plot extent and axes limits\n } else if (isTRUE(frame.plot)) {\n # if plot frame is true then print axes per normal...\n do.call(tinyAxis, args_x)\n do.call(tinyAxis, args_y)\n } else {\n # ... else only print the \"outside\" axes.\n if (ii %in% oxaxis) do.call(tinyAxis, args_x)\n if (ii %in% oyaxis) do.call(tinyAxis, args_y)\n }\n }\n\n # facet titles\n ## Note: facet titles could be done more simply with mtext... but then we\n ## couldn't adjust background features (e.g., fill), or rotate the rhs\n ## facet grid text. So we're rolling our own \"manual\" versions with text\n ## and rect.\n if (!is.null(facet)) {\n # Get the four corners of plot area (x1, x2, y1, y2)\n corners = par(\"usr\")\n # catch for logged axes\n xlog = isTRUE(par(\"xlog\"))\n ylog = isTRUE(par(\"ylog\"))\n if (xlog) corners[1:2] = 10^(corners[1:2])\n if (ylog) corners[3:4] = 10^(corners[3:4])\n # special logic for facet grids\n if (is.null(facet_newlines) || facet_newlines == 0) {\n facet_title_lines = 1\n } else {\n facet_title_lines = 1 + facet_newlines\n }\n # different logic for facet grids versus regular facets\n if (isTRUE(attr(facet, \"facet_grid\"))) {\n ## top facet strips\n if (ii %in% 1:nfacet_cols) {\n if (isTRUE(facet_rect)) {\n line_height = (facet_title_lines + .1) * facet_text / cex_fct_adj\n if (ylog) {\n line_height = grconvertY(line_height, from = \"lines\", to = \"user\") / grconvertY(0, from = \"lines\", to = \"user\")\n rect_height = corners[4] * line_height\n } else {\n line_height = grconvertY(line_height, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\")\n rect_height = corners[4] + line_height\n }\n rect(\n corners[1], corners[4], corners[2], rect_height,\n col = facet_bg, border = facet_border,\n xpd = NA\n )\n }\n xpos = if (xlog) 10^(mean(log10(corners[1:2]))) else mean(corners[1:2])\n if (ylog) {\n ypos = grconvertY(0.4, from = \"lines\", to = \"user\") / grconvertY(0, from = \"lines\", to = \"user\")\n ypos = corners[4] * ypos\n } else {\n ypos = grconvertY(0.4, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\")\n ypos = corners[4] + ypos\n }\n text(\n x = xpos,\n y = ypos,\n labels = sub(\"^(.*?)~.*\", \"\\\\1\", facets[[ii]]),\n adj = c(0.5, 0),\n cex = facet_text / cex_fct_adj,\n col = facet_col,\n font = facet_font,\n xpd = NA,\n )\n }\n ## right facet strips\n if (ii %% nfacet_cols == 0 || ii == nfacets) {\n if (isTRUE(facet_rect)) {\n line_height = (facet_title_lines + .1) * facet_text / cex_fct_adj\n if (xlog) {\n line_height = grconvertX(line_height, from = \"lines\", to = \"user\") / grconvertX(0, from = \"lines\", to = \"user\")\n rect_width = corners[2] * line_height\n } else {\n line_height = grconvertX(line_height, from = \"lines\", to = \"user\") - grconvertX(0, from = \"lines\", to = \"user\")\n rect_width = corners[2] + line_height\n }\n rect(\n corners[2], corners[3], rect_width, corners[4],\n col = facet_bg, border = facet_border,\n xpd = NA\n )\n }\n if (xlog) {\n xpos = grconvertX(0.4, from = \"lines\", to = \"user\") / grconvertX(0, from = \"lines\", to = \"user\")\n xpos = corners[2] * xpos\n } else {\n xpos = grconvertX(0.4, from = \"lines\", to = \"user\") - grconvertX(0, from = \"lines\", to = \"user\")\n xpos = corners[2] + xpos\n }\n ypos = if (ylog) 10^(mean(log10(corners[3:4]))) else mean(corners[3:4])\n text(\n x = xpos,\n y = ypos,\n labels = sub(\"^.*?~(.*)\", \"\\\\1\", facets[[ii]]),\n srt = 270,\n adj = c(0.5, 0),\n cex = facet_text / cex_fct_adj,\n col = facet_col,\n font = facet_font,\n xpd = NA\n )\n }\n } else {\n if (isTRUE(facet_rect)) {\n line_height = (facet_title_lines + .1) * facet_text / cex_fct_adj\n if (ylog) {\n line_height = grconvertY(line_height, from = \"lines\", to = \"user\") / grconvertY(0, from = \"lines\", to = \"user\")\n rect_height = corners[4] * line_height\n } else {\n line_height = grconvertY(line_height, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\")\n rect_height = corners[4] + line_height\n }\n rect(\n corners[1], corners[4], corners[2], rect_height,\n col = facet_bg, border = facet_border,\n xpd = NA\n )\n }\n xpos = if (xlog) 10^(mean(log10(corners[1:2]))) else mean(corners[1:2])\n if (ylog) {\n ypos = grconvertY(0.4, from = \"lines\", to = \"user\") / grconvertY(0, from = \"lines\", to = \"user\")\n ypos = corners[4] * ypos\n } else {\n ypos = grconvertY(0.4, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\")\n ypos = corners[4] + ypos\n }\n text(\n x = xpos,\n y = ypos,\n labels = paste(facets[[ii]]),\n adj = c(0.5, 0),\n cex = facet_text / cex_fct_adj,\n col = facet_col,\n font = facet_font,\n xpd = NA\n )\n }\n }\n\n # plot frame\n if (frame.plot) box()\n\n # panel grid lines\n if (is.null(grid)) grid = .tpar[[\"grid\"]]\n if (!is.null(grid)) {\n if (is.logical(grid)) {\n ## If grid is TRUE create a default grid. Rather than just calling the default grid()\n ## abline(... = pretty(extendrange(...)), ...) is used. Reason: pretty() is generic\n ## and works better for axes based on date/time classes. Exception: For axes in logs,\n ## resort to using grid() which is likely better handled there.\n if (isTRUE(grid)) {\n gnx = gny = NULL\n if (!is.null(xaxb)) {\n abline(v = xaxb, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n gnx = NA\n } else if (!any(c(par(\"xlog\"), type == \"boxplot\"))) {\n xg = if (!inherits(x, c(\"POSIXt\", \"Date\"))) axTicks(side = 1) else axTicksDateTime(side = 1, x = x)\n abline(v = xg, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n gnx = NA\n }\n if (!is.null(yaxb)) {\n abline(h = yaxb, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n gny = NA\n } else if (!any(c(par(\"ylog\"), type == \"boxplot\"))) {\n yg = if (!inherits(y, c(\"POSIXt\", \"Date\"))) axTicks(side = 2) else axTicksDateTime(side = 2, x = x)\n abline(h = yg, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n gny = NA\n }\n grid(nx = gnx, ny = gny, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n }\n } else {\n grid\n }\n }\n\n # add any drawn elements\n if (!is.null(draw)) eval(draw)\n } # end of ii facet loop\n\n return(as.list(environment()))\n}\n\n\n#' @rdname facet\n#' @keywords internal\nfacet_layout = function(facet, add = FALSE, facet.args = list()) {\n nfacet_rows = 1\n nfacet_cols = 1\n if (!is.null(facet)) {\n facets = if (is.factor(facet)) levels(facet) else sort(unique(facet))\n ifacet = seq_along(facets)\n nfacets = length(facets)\n if (isTRUE(add)) {\n omfrow = par(\"mfrow\")\n nfacet_rows = omfrow[1]\n nfacet_cols = omfrow[2]\n } else {\n if (isTRUE(attr(facet, \"facet_grid\"))) {\n facet.args[[\"nrow\"]] = attr(facet, \"facet_nrow\")\n }\n if (!is.null(facet.args[[\"nrow\"]])) {\n nfacet_rows = facet.args[[\"nrow\"]]\n nfacet_cols = ceiling(nfacets / nfacet_rows)\n } else if (!is.null(facet.args[[\"ncol\"]])) {\n nfacet_cols = facet.args[[\"ncol\"]]\n nfacet_rows = ceiling(nfacets / nfacet_cols)\n } else {\n if (nfacets > 3) {\n nfacet_cols = ceiling(sqrt(nfacets))\n nfacet_rows = ceiling(nfacets / nfacet_cols)\n } else {\n nfacet_rows = 1L\n nfacet_cols = nfacets\n }\n }\n }\n\n oxaxis = tail(ifacet, nfacet_cols)\n oyaxis = seq(1, nfacets, by = nfacet_cols)\n\n if (nfacet_rows >= 3 || nfacet_cols >= 3) {\n cex_fct_adj = 0.66\n } else if (nfacet_rows == 2 && nfacet_cols == 2) {\n cex_fct_adj = 0.83\n } else {\n cex_fct_adj = 1\n }\n } else {\n facets = ifacet = nfacets = oxaxis = oyaxis = 1\n cex_fct_adj = 1\n }\n\n list(\n facets = facets,\n ifacet = ifacet,\n nfacets = nfacets,\n nfacet_rows = nfacet_rows,\n nfacet_cols = nfacet_cols,\n oxaxis = oxaxis,\n oyaxis = oyaxis,\n cex_fct_adj = cex_fct_adj\n )\n}\n\n\n\n#\n# helper functions\n#\n\n\n# utility function for converting facet formulas into variables\nget_facet_fml = function(formula, data = NULL) {\n xfacet = yfacet = NULL\n\n ## catch one-sided formula ~ x or ~ x | z with no \"y\" variable\n if (!inherits(formula, \"formula\")) formula = as.formula(formula)\n no_yfacet = length(formula) == 2L\n fml_rhs = if (no_yfacet) 2L else 3L\n\n ## set up model frame\n m = match.call(expand.dots = FALSE)\n\n if (!is.null(data)) {\n m = m[c(1L, match(c(\"formula\", \"data\", \"subset\", \"na.action\", \"drop.unused.levels\"), names(m), 0L))]\n }\n\n m$formula = formula\n ## need stats:: for non-standard evaluation\n m[[1L]] = quote(stats::model.frame)\n mf = eval.parent(m)\n\n ## extract variables: x, y (if any)\n if (no_yfacet) {\n yfacet_loc = NULL\n xfacet_loc = 1L\n } else {\n yfacet_loc = 1L\n xfacet_loc = 2L\n }\n if (NCOL(mf) < xfacet_loc) stop(\"formula should specify at least one variable on the right-hand side\")\n yfacet = if (no_yfacet) NULL else mf[, yfacet_loc]\n xfacet = mf[, xfacet_loc:NCOL(mf)]\n\n ## return object\n xfacet = interaction(xfacet, sep = \":\")\n if (no_yfacet) {\n ret = xfacet\n } else {\n # yfacet = interaction(yfacet, sep = \":\")\n ## NOTE: We \"swap\" the formula LHS and RHS since mfrow plots rowwise\n ret = interaction(xfacet, yfacet, sep = \"~\")\n attr(ret, \"facet_grid\") = TRUE\n attr(ret, \"facet_nrow\") = length(unique(yfacet))\n }\n\n return(ret)\n}\n\n\n## internal convenience function to determine whether the current facet panel\n## has the position \"left\", \"right\", \"top\", or \"bottom\" in the facet grid\nis_facet_position = function(position, ifacet, facet_window_args) {\n id = facet_window_args$ifacet\n nc = facet_window_args$nfacet_cols\n ni = tail(id, 1L)\n switch(position,\n \"left\" = ifacet %in% seq(1L, ni, by = nc),\n \"right\" = ifacet %in% pmin(ni, seq(1L, ni, by = nc) + nc - 1L),\n \"top\" = ifacet %in% head(id, nc),\n \"bottom\" = ifacet %in% tail(id, nc),\n NA\n )\n}\n"], ["/tinyplot/R/type_segments.R", "#' Line segments plot type\n#'\n#' @description Type function for plotting line segments.\n#' \n#' @details Contrary to base \\code{\\link[graphics]{segments}}, line segments in\n#' [tinyplot] must be specified using the `xmin`, `ymin`,`xmax`, and `ymax`\n#' arguments. \n#' \n#' @examples\n#' # \"segments\" type convenience character string\n#' tinyplot(\n#' xmin = c(0,.1), ymin = c(.2,1), xmax = c(1,.9), ymax = c(.75,0),\n#' type = \"segments\"\n#' )\n#' \n#' # Same result with type_segments()\n#' tinyplot(\n#' xmin = c(0,.1), ymin = c(.2,1), xmax = c(1,.9), ymax = c(.75,0),\n#' type = type_segments()\n#' )\n#' \n#' @export\ntype_segments = function() {\n out = list(\n draw = draw_segments(),\n data = NULL,\n name = \"segments\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_segments = function() {\n fun = function(ixmin, iymin, ixmax, iymax, ilty, ilwd, icol, ...) {\n segments(\n x0 = ixmin, y0 = iymin, x1 = ixmax, y1 = iymax,\n lty = ilty,\n lwd = ilwd,\n col = icol\n )\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_ridge.R", "#' Ridge plot type\n#'\n#' @description Type function for producing ridge plots (also known as joy plots),\n#' which display density distributions for multiple groups with vertical offsets.\n#' This function uses `tinyplot` scaffolding, which enables added functionality\n#' such as grouping and faceting.\n#'\n#' The line color is controlled by the `col` argument in the `tinyplot()` call.\n#' The fill color is controlled by the `bg` argument in the `tinyplot()` call.\n#'\n#' @param scale Numeric. Controls the scaling factor of each plot.\n#' Values greater than 1 means that plots overlap.\n#' @param joint.max character indicating how to scale the maximum of the densities:\n#' The default `\"all\"` indicates that all densities are scaled jointly relative to\n#' the same maximum so that the areas of all densities are comparable.\n#' Alternatively, `\"facet\"` indicates that the maximum is computed within\n#' each facet so that the areas of the densities are comparable within each\n#' facet but not necessarily across facets. Finally, `\"by\"` indicates that\n#' each row (in each facet) is scaled separately, so that the areas of the\n#' densities for `by` groups in the same row are comparable but not necessarily\n#' across rows.\n#' @param breaks Numeric. If a color gradient is used for shading, the\n#' breaks between the colors can be modified. The default is to use\n#' equidistant breaks spanning the range of the `x` variable.\n#' @param probs Numeric. Instead of specifying the same `breaks` on the\n#' x-axis for all groups, it is possible to specify group-specific quantiles\n#' at the specified `probs`. The quantiles are computed based on the density\n#' (rather than the raw original variable). Only one of `breaks` or\n#' `probs` must be specified.\n#' @param ylevels a character or numeric vector specifying in which order\n#' the levels of the y-variable should be plotted.\n#' @inheritParams stats::density\n#' @param kernel a character string giving the smoothing kernel to be used. This\n#' must partially match one of `\"gaussian\"`, `\"rectangular\"`, `\"triangular\"`,\n#' `\"epanechnikov\"`, `\"biweight\"`, `\"cosine\"` or `\"optcosine\"`, with default\n#' `\"gaussian\"`, and may be abbreviated to a unique prefix (single letter).\n#'\n#' `\"cosine\"` is smoother than `\"optcosine\"`, which is the usual 'cosine'\n#' kernel in the literature and almost MSE-efficient. However, `\"cosine\"` is\n#' the version used by S.\n#' @param joint.bw character string indicating whether (and how) the smoothing\n#' bandwidth should be computed from the joint data distribution. The default\n#' of `\"mean\"` will compute the joint bandwidth as the mean of the individual\n#' subgroup bandwidths (weighted by their number of observations). Choosing\n#' `\"full\"` will result in a joint bandwidth computed from the full\n#' distribution (merging all subgroups). For `\"none\"` the individual bandwidth\n#' will be computed independently for each subgroup. Also accepts a logical\n#' argument, where `TRUE` maps to `\"mean\"` and `FALSE` maps to `\"none\"`. See\n#' \\code{\\link{type_density}} for some discussion of practical considerations.\n#' @param gradient Logical or character. Should a gradient fill be used to\n#' shade the area under the density? If a character specification is used,\n#' then it can either be of length 1 and specify the palette to be used with\n#' `gradient = TRUE` corresponding to `gradient = \"viridis\"`. If a character\n#' vector of length greater than 1 is used, then it should specify the\n#' colors in the palette, e.g., `gradient = hcl.colors(512)`.\n#' @param raster Logical. Should the `gradient` fill be drawn using\n#' \\code{\\link[graphics]{rasterImage}}? Defaults to `FALSE`, in which case the\n#' `gradient` fill will instead be drawn using\n#' \\code{\\link[graphics]{polygon}}. See the `Technical note on gradient fills`\n#' section below.\n#' @param col Character string denoting the outline (border) color for all\n#' of the ridge densities. Note that a singular value is expected; if multiple\n#' colors are provided then only the first will be used. This argument is mostly\n#' useful for the aesthetic effect of drawing a common outline color in\n#' combination with gradient fills. See Examples.\n#' @param alpha Numeric in the range `[0,1]` for adjusting the alpha\n#' transparency of the density fills. In most cases, will default to a value of\n#' 1, i.e. fully opaque. But for some `by` grouped plots (excepting the special\n#' cases where `by==y` or `by==x`), will default to 0.6.\n#' \n#' @section Technical note on gradient fills:\n#' \n#' `tinyplot` uses two basic approaches for drawing gradient fills in ridge line\n#' plots, e.g., if `type_ridge(gradient = TRUE)`.\n#' \n#' The first (and default) polygon-based approach involves dividing up the main\n#' density region into many smaller polygons along the x-axis. Each of these\n#' smaller polygons inherits a different color \"segment\" from the underlying\n#' palette swatch, which in turn creates the effect of a continuous gradient\n#' when they are all plotted together. Internally, this polygon-based approach\n#' is vectorized (i.e., all of the sub-polygons are plotted simultaneously). It\n#' is thus efficient from a plotting perspective and generally also performs\n#' well from an aesthetic perspective. However, it can occasionally produce\n#' undesirable plotting artifacts on some graphics devices---e.g., thin but\n#' visible vertical lines---if alpha transparency is being used at the same \n#' time.\n#' \n#' For this reason, we also offer an alternative raster-based approach for\n#' gradient fills that users can invoke via\n#' `type_ridge(gradient = TRUE, raster = TRUE)`. The essential idea is that we\n#' coerce the density polygon into a raster representation (using\n#' \\code{\\link[graphics]{rasterImage}}) and achieve the gradient effect via\n#' color interpolation. The trade-off this time is potential smoothness\n#' artifacts around the top of the ridge densities at high resolutions, since we\n#' have converted a vector object into a raster object.\n#' \n#' Again, we expect that the choice between these two approaches will only\n#' matter for ridge plots that combine gradient fills with alpha transparency\n#' (and on certain graphics devices). We recommend that users experiment to\n#' determine which approach is optimal for their device.\n#'\n#' @examples\n#' aq = transform(\n#' airquality,\n#' Month = factor(month.abb[Month], levels = month.abb[5:9]),\n#' Month2 = factor(month.name[Month], levels = month.name[5:9]),\n#' Late = ifelse(Day > 15, \"Late\", \"Early\")\n#' )\n#' \n#' # default ridge plot (using the \"ridge\" convenience string)\n#' tinyplot(Month ~ Temp, data = aq, type = \"ridge\")\n#' \n#' # for ridge plots, we recommend pairing with the dedicated theme(s), which\n#' # facilitate nicer y-axis labels, grid lines, etc.\n#' \n#' tinytheme(\"ridge\")\n#' tinyplot(Month ~ Temp, data = aq, type = \"ridge\")\n#' \n#' tinytheme(\"ridge2\") # removes the plot frame (but keeps x-axis line)\n#' tinyplot(Month ~ Temp, data = aq, type = \"ridge\")\n#' \n#' # the \"ridge(2)\" themes are especially helpful for long y labels, due to\n#' # dyanmic plot adjustment\n#' tinyplot(Month2 ~ Temp, data = aq, type = \"ridge\")\n#' \n#' # pass customization arguments through type_ridge()... for example, use\n#' # the scale argument to change/avoid overlap of densities (more on scaling\n#' # further below)\n#' \n#' tinyplot(Month ~ Temp, data = aq, type = type_ridge(scale = 1))\n#' \n#' ## by grouping is also supported. two special cases of interest:\n#'\n#' # 1) by == y (color by y groups)\n#' tinyplot(Month ~ Temp | Month, data = aq, type = \"ridge\")\n#'\n#' # 2) by == x (gradient coloring along x)\n#' tinyplot(Month ~ Temp | Temp, data = aq, type = \"ridge\")\n#'\n#' # aside: pass explicit `type_ridge(col = )` arg to set a different\n#' # border color\n#' tinyplot(Month ~ Temp | Temp, data = aq, type = type_ridge(col = \"white\"))\n#'\n#' # gradient coloring along the x-axis can also be invoked manually without\n#' # a legend (the next two tinyplot calls are equivalent)\n#' \n#' # tinyplot(Month ~ Temp, data = aq, type = type_ridge(gradient = \"agsunset\"))\n#' tinyplot(Month ~ Temp, data = aq, type = type_ridge(gradient = TRUE))\n#' \n#' # aside: when combining gradient fill with alpha transparency, it may be\n#' # better to use the raster-based approach (test on your graphics device)\n#' \n#' tinyplot(Month ~ Temp, data = aq,\n#' type = type_ridge(gradient = TRUE, alpha = 0.5),\n#' main = \"polygon fill (default)\")\n#' tinyplot(Month ~ Temp, data = aq,\n#' type = type_ridge(gradient = TRUE, alpha = 0.5, raster = TRUE),\n#' main = \"raster fill\")\n#'\n#' # highlighting only the center 50% of the density (i.e., 25%-75% quantiles)\n#' tinyplot(Month ~ Temp, data = aq, type = type_ridge(\n#' gradient = hcl.colors(3, \"Dark Mint\")[c(2, 1, 2)],\n#' probs = c(0.25, 0.75), col = \"white\"))\n#'\n#' # highlighting the probability distribution by color gradient\n#' # (darkest point = median)\n#' tinyplot(Month ~ Temp, data = aq, type = type_ridge(\n#' gradient = hcl.colors(250, \"Dark Mint\")[c(250:1, 1:250)],\n#' probs = 0:500/500))\n#'\n#' # faceting also works, although we recommend switching (back) to the \"ridge\"\n#' # theme for faceted ridge plots\n#' \n#' tinytheme(\"ridge\")\n#' tinyplot(Month ~ Ozone, facet = ~ Late, data = aq,\n#' type = type_ridge(gradient = TRUE))\n#' \n#' ## use the joint.max argument to vary the maximum density used for\n#' ## determining relative scaling...\n#' \n#' # jointly across all densities (default) vs. per facet\n#' tinyplot(Month ~ Temp, facet = ~ Late, data = aq,\n#' type = type_ridge(scale = 1))\n#' tinyplot(Month ~ Temp, facet = ~ Late, data = aq,\n#' type = type_ridge(scale = 1, joint.max = \"facet\"))\n#' \n#' # jointly across all densities (default) vs. per by row\n#' tinyplot(Month ~ Temp | Late, data = aq,\n#' type = type_ridge(scale = 1))\n#' tinyplot(Month ~ Temp | Late, data = aq,\n#' type = type_ridge(scale = 1, joint.max = \"by\"))\n#' \n#' # restore the default theme\n#' tinytheme()\n#'\n#' @export\ntype_ridge = function(\n scale = 1.5,\n joint.max = c(\"all\", \"facet\", \"by\"),\n breaks = NULL,\n probs = NULL,\n ylevels = NULL,\n bw = \"nrd0\",\n joint.bw = c(\"mean\", \"full\", \"none\"),\n adjust = 1,\n kernel = c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"),\n n = 512,\n # more args from density here?\n gradient = FALSE,\n raster = FALSE,\n col = NULL,\n alpha = NULL\n ) {\n \n kernel = match.arg(kernel, c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"))\n if (is.logical(joint.bw)) {\n joint.bw = ifelse(joint.bw, \"mean\", \"none\")\n }\n joint.bw = match.arg(joint.bw, c(\"mean\", \"full\", \"none\"))\n\n out = list(\n draw = draw_ridge(),\n data = data_ridge(bw = bw, adjust = adjust, kernel = kernel, n = n,\n joint.bw = joint.bw,\n scale = scale,\n joint.max = joint.max,\n gradient = gradient,\n breaks = breaks,\n probs = probs,\n ylevels = ylevels,\n raster = raster,\n col = col,\n alpha = alpha\n ),\n name = \"ridge\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n#\n## Underlying data_ridge function\ndata_ridge = function(bw = \"nrd0\", adjust = 1, kernel = \"gaussian\", n = 512,\n joint.bw = \"mean\",\n scale = 1.5,\n joint.max = \"all\",\n gradient = FALSE,\n breaks = NULL,\n probs = NULL,\n ylevels = NULL,\n raster = FALSE,\n col = NULL,\n alpha = NULL\n ) {\n fun = function(datapoints, yaxt = NULL, null_by, ...) {\n # catch for special cases\n anyby = !null_by\n x_by = anyby && identical(datapoints$x, datapoints$by)\n y_by = anyby && identical(datapoints$y, datapoints$by)\n if (x_by) {\n gradient = TRUE\n datapoints$by = \"\"\n } else if (y_by) {\n datapoints$by = \"\"\n } else if (anyby && is.null(alpha)) {\n alpha = 0.6\n }\n # flag for (non-gradient) interior fill adjustment\n fill_by = anyby || y_by\n if (isTRUE(x_by)) fill_by = FALSE\n # if (isTRUE(anyby) && is.null(alpha)) alpha = 0.6\n\n ## reorder levels of y-variable if requested\n if (!is.null(ylevels)) {\n if (!is.factor(datapoints$y)) datapoints$y = factor(datapoints$y)\n datapoints$y = factor(datapoints$y, levels = if(is.numeric(ylevels)) levels(datapoints$y)[ylevels] else ylevels)\n if (y_by) datapoints$by = datapoints$y\n }\n\n ##\n datapoints = split(datapoints, list(datapoints$y, datapoints$by, datapoints$facet))\n\n if (joint.bw == \"none\" || is.numeric(bw)) {\n dens_bw = bw\n } else {\n if (joint.bw == \"mean\") {\n # Use weighted mean of subgroup bandwidths\n bws = sapply(datapoints, function(dat) bw_fun(kernel = bw, dat$x))\n ws = sapply(datapoints, nrow)\n dens_bw = weighted.mean(bws, ws)\n } else if (joint.bw == \"full\") {\n dens_bw = bw_fun(kernel = bw, unlist(sapply(datapoints, `[[`, \"x\")))\n }\n }\n\n datapoints = lapply(datapoints, function(dat) {\n dens = density(dat$x, bw = dens_bw, kernel = kernel, n = n)\n out = data.frame(\n by = dat$by[1], # already split\n facet = dat$facet[1], # already split\n x = dens$x,\n y = dat$y[1],\n ymin = 0L,\n ymax = dens$y\n )\n return(out)\n })\n datapoints = do.call(rbind, datapoints)\n\n if (is.character(joint.max)) {\n joint.max = match.arg(joint.max, c(\"all\", \"facet\", \"by\"))\n joint.max = switch(joint.max,\n \"all\" = rep.int(1, nrow(datapoints)),\n \"facet\" = datapoints$facet,\n \"by\" = interaction(datapoints$facet, datapoints$y)\n )\n joint.max = ave(datapoints$ymax, joint.max, FUN = max)\n }\n datapoints$ymax = datapoints$ymax / joint.max * scale\n\n datapoints = split(datapoints, datapoints$facet)\n offset_z = function(k) {\n ksplit = split(k, k$y)\n for (idx in seq_along(ksplit)) {\n ksplit[[idx]]$ymax = ksplit[[idx]]$ymax + idx - 1\n ksplit[[idx]]$ymin = ksplit[[idx]]$ymin + idx - 1\n }\n k = do.call(rbind, ksplit)\n return(k)\n }\n datapoints = do.call(rbind, lapply(datapoints, offset_z))\n\n if (y_by) {\n datapoints$y = factor(datapoints$y)\n datapoints$by = factor(datapoints$y, levels = rev(levels(datapoints$y)))\n } else if (x_by) {\n datapoints$by = datapoints$x\n }\n\n # Manual breaks flag. Only used if gradient is on\n manbreaks = !is.null(breaks) || !is.null(probs)\n\n ## use color gradient?\n xlim = range(datapoints$x, na.rm = TRUE)\n if (!is.null(probs)) {\n if (!is.null(breaks)) {\n warning(\"only one of 'breaks' and 'quantile' must be specified\")\n probs = NULL\n } else {\n if (probs[1L] > 0) probs = c(0, probs)\n if (probs[length(probs)] < 1) probs = c(probs, 1)\n }\n }\n if (!isFALSE(gradient)) {\n dotspal = list(...)[[\"palette\"]]\n palette = if (!is.null(dotspal)) dotspal else gradient\n gradient = TRUE\n if (isTRUE(palette)) {\n palette = if (!is.null(.tpar[[\"palette.sequential\"]])) .tpar[[\"palette.sequential\"]] else \"viridis\"\n }\n\n if (length(palette) > 1L || !is.character(palette)) {\n ## color vector already given\n if (is.null(breaks) && is.null(probs)) {\n breaks = seq(from = xlim[1L], to = xlim[2L], length.out = length(palette) + 1L)\n } else {\n npal = pmax(length(breaks), length(probs)) - 1L\n if (length(palette) != npal) {\n warning(\"length of 'palette' does not match 'breaks'/'probs'\")\n palette = rep_len(palette, npal)\n }\n if (isTRUE(raster)) raster = npal > 20L\n }\n } else {\n ## only palette name given\n npal = if (is.null(breaks) && is.null(probs)) 512L else pmax(length(breaks), length(probs)) - 1L\n palette = hcl.colors(npal, palette = palette)\n if (is.null(breaks) && is.null(probs)) breaks = seq(from = xlim[1L], to = xlim[2L], length.out = npal + 1L)\n if (isTRUE(raster)) raster = npal > 20L\n }\n } else {\n palette = NULL\n if (!is.null(breaks) || !is.null(probs)) gradient = TRUE\n }\n if (!is.null(breaks)) {\n breaks[1L] = pmin(breaks[1L], xlim[1L])\n breaks[length(breaks)] = pmax(breaks[length(breaks)], xlim[2L])\n }\n \n if (is.null(col) && (!anyby || x_by)) col = \"black\"\n\n out = list(\n datapoints = datapoints,\n yaxt = \"n\",\n ylim = c(min(datapoints$ymin), max(datapoints$ymax)),\n type_info = list(\n gradient = gradient,\n palette = palette,\n breaks = breaks,\n probs = probs,\n manbreaks = manbreaks,\n yaxt = yaxt,\n raster = raster,\n x_by = x_by,\n y_by = y_by,\n fill_by = fill_by,\n col = col,\n alpha = alpha\n )\n )\n return(out)\n }\n return(fun)\n}\n\n\n#\n## Underlying draw_ridge function\ndraw_ridge = function() {\n fun = function(ix, iy, iz, ibg, icol, iymin, iymax, type_info, ...) {\n ridge_theme = identical(.tpar[[\"tinytheme\"]], \"ridge\") || identical(.tpar[[\"tinytheme\"]], \"ridge2\")\n d = data.frame(x = ix, y = iy, ymin = iymin, ymax = iymax)\n dsplit = split(d, d$y)\n if (is.null(ibg)) {\n default_bg = if (!ridge_theme && !is.null(.tpar[[\"palette.qualitative\"]])) seq_palette(by_col(), n = 2)[2] else \"gray\"\n ibg = if (isTRUE(type_info[[\"fill_by\"]])) seq_palette(icol, n = 2)[2] else default_bg\n }\n if (!is.null(type_info[[\"alpha\"]]) && is.null(type_info[[\"palette\"]])) {\n ibg = adjustcolor(ibg, alpha.f = type_info[[\"alpha\"]])\n }\n if (!is.null(type_info[[\"col\"]])) icol = type_info[[\"col\"]]\n lab = if (is.factor(d$y)) levels(d$y) else unique(d$y)\n if (isTRUE(type_info[[\"y_by\"]])) {\n # avoid duplicating the y-axis labs for the special y==by case\n # val = match(lab, levels(d$y)) - 1\n val = match(d$y[1], levels(d$y))\n lab = lab[val]\n val = val - 1\n } else {\n val = cumsum(rep(1, length(lab))) - 1\n }\n if (ridge_theme) abline(h = val, col = .tpar[[\"grid.col\"]])\n draw_segments = if (type_info[[\"raster\"]]) segmented_raster else segmented_polygon\n for (i in rev(seq_along(dsplit))) {\n if (type_info[[\"gradient\"]]) {\n with(\n dsplit[[i]],\n draw_segments(\n x, ymax, ymin = ymin[1L],\n breaks = type_info[[\"breaks\"]],\n probs = type_info[[\"probs\"]],\n manbreaks = type_info[[\"manbreaks\"]],\n col = if (is.null(type_info[[\"palette\"]])) ibg else type_info[[\"palette\"]],\n # border = if (is.null(type_info[[\"palette\"]])) icol else \"transparent\",\n alpha = type_info[[\"alpha\"]]\n )\n )\n }\n with(dsplit[[i]], polygon(x, ymax, col = if (type_info[[\"gradient\"]]) \"transparent\" else ibg, border = NA))\n with(dsplit[[i]], lines(x, ymax, col = icol))\n }\n # tinyAxis(x = d$y, side = 2, at = val, labels = lab, type = type_info[[\"yaxt\"]], padj = padj)\n if (ridge_theme) {\n tinyAxis(x = d$y, side = 2, at = val, labels = lab, type = type_info[[\"yaxt\"]],\n padj = 0,\n mgp = c(3, 1, 0) - c(0.5, 0.5 + 0.3, 0),\n tcl = 0)\n if (identical(.tpar[[\"tinytheme\"]], \"ridge2\")) axis(1, labels = FALSE)\n } else {\n tinyAxis(x = d$y, side = 2, at = val, labels = lab, type = type_info[[\"yaxt\"]])\n }\n }\n return(fun)\n}\n\n\n#\n## Auxiliary functions\n\n## auxiliary function for drawing shaded segmented polygon\nsegmented_polygon = function(x, y, ymin = 0, breaks = range(x), probs = NULL, manbreaks = FALSE, col = \"lightgray\", border = \"transparent\", alpha = NULL) {\n\n if (!is.null(probs)) {\n ## map quantiles to breaks\n if (!(missing(breaks) || is.null(breaks))) stop(\"only one of 'breaks' and 'probs' must be specified\")\n breaks = quantile.density(list(x = x, y = y - ymin), probs = probs)\n }\n\n ## sanity check\n if (breaks[1L] > x[1L] || breaks[length(breaks)] < x[length(x)]) stop(\"'breaks' do no span range of 'x'\")\n\n # ## recycle color (if necessary) rather use colorRampPalette below\n # col = rep_len(col, length(breaks) - 1L)\n \n # Create individual polygons\n if (isFALSE(manbreaks)) {\n # Special case for length(breaks)==length(x). We can take a fully vectorised\n # shortcut\n xx = c(rbind(x[-length(x)], x[-1], x[-1], x[-length(x)], NA))\n yy = c(rbind(y[-length(y)], y[-1], ymin, ymin, NA))\n } else {\n # For other cases, we'll do a bit more work to make sure that the polygons\n # overlap\n bvals = do.call(c, sapply(seq_along(breaks[-1]), function(b) tail(x[x= xrange[1] & breaks < xrange[2])\n idx = c(idx, length(idx)+1)\n col = col[idx]\n col = colorRampPalette(col, alpha = TRUE)(length(x)) # support alpha?\n }\n } else if (isFALSE(manbreaks) || length(col) > length(x) || length(x) %% length(col) != 0) {\n xrange = range(xx, na.rm = TRUE)\n idx = which(breaks >= xrange[1] & breaks < xrange[2])\n idx = c(idx, length(idx)+1)\n col = col[idx]\n col = colorRampPalette(col, alpha = TRUE)(length(x)) # support alpha?\n }\n }\n border = if (is.null(alpha)) col else adjustcolor(col = col, alpha.f = alpha/2)\n \n ## draw all polygons\n polygon(xx, yy, col = col, border = border, lwd = 0.5)\n}\n\n#' @importFrom graphics rasterImage\n#' @importFrom grDevices as.raster\nsegmented_raster = function(x, y, ymin = 0, breaks = range(x), probs = NULL, manbreaks = FALSE, col = \"lightgray\", border = \"transparent\", alpha = NULL) {\n ## set up raster matrix on x-grid and 500 y-pixels \n n = length(x) - 1L\n m = 500L ## FIXME: hard-coded?\n r = matrix(1:n, ncol = n, nrow = m, byrow = TRUE)\n\n ## map quantiles to breaks\n if (!is.null(probs)) {\n if (!(missing(breaks) || is.null(breaks))) stop(\"only one of 'breaks' and 'probs' must be specified\")\n breaks = quantile.density(list(x = x, y = y - ymin), probs = probs)\n }\n\n if (!is.null(alpha)) col = adjustcolor(col, alpha.f = alpha)\n col = rev(col) ## uncomment to make extreme cols dark\n ## map colors to intervals and fill colors by column\n col = col[cut(x, breaks = breaks, include.lowest = TRUE)]\n r[] = col[r]\n\n ## clip raster pixels above density line\n ymax = max(y)\n ix = cbind(as.vector(row(r)), as.vector(col(r)))\n ix = ix[seq(from = ymax, to = ymin, length.out = m)[row(r)] > y[col(r)], , drop = FALSE]\n r[ix] = NA\n\n ## plot density and add raster gradient\n rasterImage(as.raster(r), min(x), ymin, max(x), ymax, interpolate = length(breaks) >= 20L) ## FIXME: improve quality for \"few\" breaks?\n}\n\n## auxiliary function for determining quantiles based on density function\n\n#' @importFrom stats median approx\nquantile.density = function(x, probs = seq(0, 1, 0.25), ...) {\n ## sanity check for probabilities\n if (any(probs < 0 | probs > 1)) stop(\"'probs' outside [0,1]\")\n\n ## probability density function, extrapolated to zero, use midpoints\n n = length(x$x)\n pdf = x$y\n pdf = c(0, pdf, 0)\n\n ## x variable, also extrapolated, use midpoints\n x = x$x\n delta = median(diff(x))\n x = c(x[1L] - delta, x, x[n] + delta)\n\n ## numerical integration of density\n cdf = c(0, cumsum(diff(x) * (pdf[-1L] + pdf[-(n + 2L)])/2))\n cdf = cdf/cdf[n + 2L]\n\n ## approximate quantiles\n approx(cdf, x, xout = probs, rule = 2)$y \n}\n"], ["/tinyplot/R/draw_legend.R", "#' @title Calculate placement of legend and draw it\n#' \n#' @description Function used to calculate the placement of (including\n#' outside the plotting area) and drawing of legend.\n#' \n#' @md\n#' @param legend Legend placement keyword or list, passed down from [tinyplot].\n#' @param legend_args Additional legend arguments to be passed to\n#' \\code{\\link[graphics]{legend}}.\n#' @param by_dep The (deparsed) \"by\" grouping variable name.\n#' @param lgnd_labs The labels passed to `legend(legend = ...)`.\n#' @param type Plotting type(s), passed down from [tinyplot].\n#' @param pch Plotting character(s), passed down from [tinyplot].\n#' @param lty Plotting linetype(s), passed down from [tinyplot].\n#' @param lwd Plotting line width(s), passed down from [tinyplot].\n#' @param col Plotting colour(s), passed down from [tinyplot].\n#' @param bg Plotting character background fill colour(s), passed down from [tinyplot].\n#' @param cex Plotting character expansion(s), passed down from [tinyplot].\n#' @param gradient Logical indicating whether a continuous gradient swatch\n#' should be used to represent the colors.\n#' @param lmar Legend margins (in lines). Should be a numeric vector of the form\n#' `c(inner, outer)`, where the first number represents the \"inner\" margin\n#' between the legend and the plot, and the second number represents the\n#' \"outer\" margin between the legend and edge of the graphics device. If no\n#' explicit value is provided by the user, then reverts back to `tpar(\"lmar\")`\n#' for which the default values are `c(1.0, 0.1)`.\n#' @param has_sub Logical. Does the plot have a sub-caption. Only used if\n#' keyword position is \"bottom!\", in which case we need to bump the legend\n#' margin a bit further.\n#' @param new_plot Logical. Should we be calling plot.new internally?\n#' @param draw Logical. If `FALSE`, no legend is drawn but the sizes are\n#' returned. Note that a new (blank) plot frame will still need to be started\n#' in order to perform the calculations. \n#' \n#' @returns No return value, called for side effect of producing a(n empty) plot\n#' with a legend in the margin.\n#' \n#' @importFrom graphics grconvertX grconvertY rasterImage strwidth\n#' @importFrom grDevices as.raster recordGraphics\n#' @importFrom utils modifyList\n#' \n#' @examples\n#' oldmar = par(\"mar\")\n#' \n#' draw_legend(\n#' legend = \"right!\", ## default (other options incl, \"left(!)\", \"\"bottom(!)\", etc.)\n#' legend_args = list(title = \"Key\", bty = \"o\"),\n#' lgnd_labs = c(\"foo\", \"bar\"),\n#' type = \"p\",\n#' pch = 21:22,\n#' col = 1:2\n#' )\n#' \n#' # The legend is placed in the outer margin...\n#' box(\"figure\", col = \"cyan\", lty = 4)\n#' # ... and the plot is proportionally adjusted against the edge of this\n#' # margin.\n#' box(\"plot\")\n#' # You can add regular plot objects per normal now\n#' plot.window(xlim = c(1,10), ylim = c(1,10))\n#' points(1:10)\n#' points(10:1, pch = 22, col = \"red\")\n#' axis(1); axis(2)\n#' # etc.\n#' \n#' # Important: A side effect of draw_legend is that the inner margins have been\n#' # adjusted. (Here: The right margin, since we called \"right!\" above.)\n#' par(\"mar\")\n#' \n#' # To reset you should call `dev.off()` or just reset manually.\n#' par(mar = oldmar)\n#' \n#' # Note that the inner and outer margin of the legend itself can be set via\n#' # the `lmar` argument. (This can also be set globally via\n#' # `tpar(lmar = c(inner, outer))`.)\n#' draw_legend(\n#' legend_args = list(title = \"Key\", bty = \"o\"),\n#' lgnd_labs = c(\"foo\", \"bar\"),\n#' type = \"p\",\n#' pch = 21:22,\n#' col = 1:2,\n#' lmar = c(0, 0.1) ## set inner margin to zero\n#' )\n#' box(\"figure\", col = \"cyan\", lty = 4)\n#' \n#' par(mar = oldmar)\n#' \n#' # Continuous (gradient) legends are also supported\n#' draw_legend(\n#' legend = \"right!\",\n#' legend_args = list(title = \"Key\"),\n#' lgnd_labs = LETTERS[1:5],\n#' col = hcl.colors(5),\n#' gradient = TRUE ## enable gradient legend\n#' )\n#' \n#' par(mar = oldmar)\n#' \n#' @export\ndraw_legend = function(\n legend = NULL,\n legend_args = NULL,\n by_dep = NULL,\n lgnd_labs = NULL,\n type = NULL,\n pch = NULL,\n lty = NULL,\n lwd = NULL,\n col = NULL,\n bg = NULL,\n cex = NULL,\n gradient = FALSE,\n lmar = NULL,\n has_sub = FALSE,\n new_plot = TRUE,\n draw = TRUE\n) {\n \n if (is.null(lmar)) {\n lmar = tpar(\"lmar\")\n } else {\n if (!is.numeric(lmar) || length(lmar)!=2) stop (\"lmar must be a numeric of length 2.\")\n }\n \n assert_logical(gradient)\n assert_logical(has_sub)\n assert_logical(new_plot)\n assert_logical(draw)\n \n #\n ## legend args ----\n \n if (is.null(legend_args[[\"x\"]])) {\n if (is.null(legend)) {\n legend_args[[\"x\"]] = \"right!\"\n } else if (is.character(legend)) {\n legend_args = utils::modifyList(legend_args, list(x = legend))\n } else if (class(legend) %in% c(\"call\", \"name\")) {\n largs = as.list(legend)\n if (is.null(largs[[\"x\"]])) {\n lnms = names(largs)\n # check second position b/c first will be a symbol \n if (is.null(lnms)) {\n largs = stats::setNames(largs, c(\"\", \"x\"))\n } else if (length(largs)>=2 && lnms[2] == \"\") {\n lnms[2] = \"x\"\n largs = stats::setNames(largs, lnms)\n } else {\n largs[[\"x\"]] = \"right!\"\n }\n }\n # Finally, combine with any pre-existing legend args (e.g., title from the by label)\n legend_args = utils::modifyList(legend_args, largs, keep.null = TRUE)\n }\n }\n \n ## Use `!exists` rather than `is.null` for title in case user specified no title\n if (!exists(\"title\", where = legend_args)) legend_args[[\"title\"]] = by_dep\n \n legend_args[[\"pch\"]] = legend_args[[\"pch\"]] %||% pch\n legend_args[[\"lty\"]] = legend_args[[\"lty\"]] %||% lty\n legend_args[[\"col\"]] = legend_args[[\"col\"]] %||% col\n legend_args[[\"bty\"]] = legend_args[[\"bty\"]] %||% \"n\"\n legend_args[[\"horiz\"]] = legend_args[[\"horiz\"]] %||% FALSE\n legend_args[[\"xpd\"]] = legend_args[[\"xpd\"]] %||% NA\n \n if (!isTRUE(type %in% c(\"p\", \"ribbon\", \"polygon\", \"polypath\"))) {\n legend_args[[\"lwd\"]] = legend_args[[\"lwd\"]] %||% lwd\n }\n \n if (isTRUE(type %in% c(\"p\", \"pointrange\", \"errorbar\")) && (length(col) == 1 || length(cex) == 1)) {\n legend_args[[\"pt.cex\"]] = legend_args[[\"pt.cex\"]] %||% cex\n }\n \n # turn off inner line for \"barplot\" type\n if (identical(type, \"barplot\")) {\n legend_args[[\"lty\"]] = 0\n }\n \n if (isTRUE(type %in% c(\"rect\", \"ribbon\", \"polygon\", \"polypath\", \"boxplot\", \"hist\", \"histogram\", \"spineplot\", \"ridge\", \"barplot\", \"violin\")) || gradient) {\n legend_args[[\"pch\"]] = 22\n legend_args[[\"pt.cex\"]] = legend_args[[\"pt.cex\"]] %||% 3.5\n legend_args[[\"y.intersp\"]] = legend_args[[\"y.intersp\"]] %||% 1.25\n legend_args[[\"seg.len\"]] = legend_args[[\"seg.len\"]] %||% 1.25\n }\n \n if (isTRUE(type %in% c(\"ribbon\", \"hist\", \"histogram\", \"spineplot\"))) {\n legend_args[[\"pt.lwd\"]] = legend_args[[\"pt.lwd\"]] %||% 0\n }\n \n if (identical(type, \"p\")) {\n legend_args[[\"pt.lwd\"]] = legend_args[[\"pt.lwd\"]] %||% lwd\n }\n \n if (identical(type, \"n\") && isFALSE(gradient)) {\n legend_args[[\"pch\"]] = legend_args[[\"pch\"]] %||% par(\"pch\")\n }\n \n if (identical(type, \"spineplot\")) {\n legend_args[[\"pt.bg\"]] = legend_args[[\"pt.bg\"]] %||% legend_args[[\"col\"]]\n }\n \n if (identical(type, \"ridge\") && isFALSE(gradient)) {\n legend_args[[\"pt.bg\"]] = legend_args[[\"pt.bg\"]] %||% sapply(legend_args[[\"col\"]], function(ccol) seq_palette(ccol, n = 2)[2])\n }\n \n legend_args[[\"pt.bg\"]] = legend_args[[\"pt.bg\"]] %||% bg\n \n legend_args[[\"legend\"]] = legend_args[[\"legend\"]] %||% lgnd_labs\n if (length(lgnd_labs) != length(eval(legend_args[[\"legend\"]]))) {\n warning(\n \"\\nUser-supplied legend labels do not match the number of groups.\\n\",\n \"Defaulting to automatic labels determined by the group splits in `by`,\\n\"\n )\n legend_args[[\"legend\"]] = lgnd_labs\n }\n \n if (isTRUE(gradient)) {\n legend_args[[\"ncol\"]] = NULL\n }\n \n #\n ## legend placement ----\n \n # Note: \"side\" = left/right ; \"end\" = top/bottom\n outer_side = outer_end = outer_right = outer_bottom = FALSE ## placeholders\n \n ooma = par(\"oma\")\n omar = par(\"mar\")\n topmar_epsilon = 0.1\n \n # Catch to avoid recursive offsets, e.g. repeated tinyplot calls with\n # \"bottom!\" legend position.\n \n ## restore inner margin defaults\n ## (in case the plot region/margins were affected by the preceding tinyplot call)\n dynmar = isTRUE(.tpar[[\"dynmar\"]])\n if (any(ooma != 0) && !dynmar) {\n if ( ooma[1] != 0 & omar[1] == par(\"mgp\")[1] + 1*par(\"cex.lab\") ) omar[1] = 5.1\n if ( ooma[2] != 0 & omar[2] == par(\"mgp\")[1] + 1*par(\"cex.lab\") ) omar[2] = 4.1\n if ( ooma[3] == topmar_epsilon & omar[3] != 4.1 ) omar[3] = 4.1\n if ( ooma[4] != 0 & omar[4] == 0 ) omar[4] = 2.1\n par(mar = omar)\n }\n ## restore outer margin defaults\n par(omd = c(0,1,0,1))\n ooma = par(\"oma\")\n \n ## Legend to outer side (either right or left) of plot\n if (grepl(\"right!$|left!$\", legend_args[[\"x\"]])) {\n \n outer_side = TRUE\n outer_right = grepl(\"right!$\", legend_args[[\"x\"]])\n \n # extra bump for spineplot if outer_right legend (to accommodate secondary y-axis)\n if (identical(type, \"spineplot\")) lmar[1] = lmar[1] + 1.1\n \n ## Switch position anchor (we'll adjust relative to the _opposite_ side below)\n if (outer_right) legend_args[[\"x\"]] = gsub(\"right!$\", \"left\", legend_args[[\"x\"]])\n if (!outer_right) legend_args[[\"x\"]] = gsub(\"left!$\", \"right\", legend_args[[\"x\"]])\n \n ## We have to set the inner margins of the plot before the (fake) legend is\n ## drawn, otherwise the inset calculation---which is based in the legend\n ## width---will be off the first time.\n if (outer_right) {\n omar[4] = 0\n } else {\n # For outer left we have to account for the y-axis label too, which\n # requires additional space\n omar[2] = par(\"mgp\")[1] + 1*par(\"cex.lab\")\n }\n par(mar = omar)\n \n if (new_plot && draw) {\n plot.new()\n # For themed + dynamic plots, we need to make sure the adjusted plot\n # margins for the legend are reinstated (after being overwritten by\n # the before.plot.new hook.\n if (dynmar) {\n omar = par(\"mar\")\n if (outer_right) {\n omar[4] = 0\n } else {\n omar[2] = par(\"mgp\")[1] + 1*par(\"cex.lab\")\n }\n par(mar = omar)\n }\n }\n \n legend_args[[\"horiz\"]] = FALSE\n \n ## Legend at the outer top or bottom of plot\n } else if (grepl(\"bottom!$|top!$\", legend_args[[\"x\"]])) {\n\n outer_end = TRUE\n outer_bottom = grepl(\"bottom!$\", legend_args[[\"x\"]])\n\n ## Switch position anchor (we'll adjust relative to the _opposite_ side below)\n if (outer_bottom) legend_args[[\"x\"]] = gsub(\"bottom!$\", \"top\", legend_args[[\"x\"]])\n if (!outer_bottom) legend_args[[\"x\"]] = gsub(\"top!$\", \"bottom\", legend_args[[\"x\"]])\n\n ## We have to set the inner margins of the plot before the (fake) legend is\n ## drawn, otherwise the inset calculation---which is based in the legend\n ## width---will be off the first time.\n if (outer_bottom) {\n omar[1] = par(\"mgp\")[1] + 1*par(\"cex.lab\")\n if (has_sub && (is.null(.tpar[[\"side.sub\"]]) || .tpar[[\"side.sub\"]]==1)) omar[1] = omar[1] + 1*par(\"cex.sub\")\n } else {\n ## For \"top!\", the logic is slightly different: We don't expand the outer\n ## margin b/c we need the legend to come underneath the main title. So\n ## we rather expand the existing inner margin.\n ooma[3] = ooma[3] + topmar_epsilon\n par(oma = ooma)\n }\n par(mar = omar)\n\n if (new_plot && draw) {\n plot.new()\n # For themed + dynamic plots, we need to make sure the adjusted plot\n # margins for the legend are reinstated (after being overwritten by\n # the before.plot.new hook.\n if (dynmar) {\n omar = par(\"mar\")\n if (outer_bottom) {\n # omar[1] = par(\"mgp\")[1] + 1*par(\"cex.lab\")\n omar[1] = theme_clean$mgp[1] + 1*par(\"cex.lab\") ## bit of a hack\n if (has_sub && (is.null(.tpar[[\"side.sub\"]]) || .tpar[[\"side.sub\"]]==1)) omar[1] = omar[1] + 1*par(\"cex.sub\")\n } else {\n ooma[3] = ooma[3] + topmar_epsilon\n par(oma = ooma)\n }\n par(mar = omar)\n }\n }\n\n # enforce horizontal legend if user hasn't specified ncol arg\n # (exception: gradient legends at bottom/top are always horizontal)\n if (is.null(legend_args[[\"ncol\"]]) || gradient) legend_args[[\"horiz\"]] = TRUE\n\n } else {\n \n legend_args[[\"inset\"]] = 0\n if (new_plot && draw) plot.new()\n \n }\n \n # Additional tweaks for horiz and/or multi-column legends\n if (isTRUE(legend_args[[\"horiz\"]]) || !is.null(legend_args[[\"ncol\"]])) {\n # tighter horizontal labelling\n # See: https://github.com/grantmcdermott/tinyplot/issues/434\n if (!gradient) {\n legend_args[[\"text.width\"]] = NA\n # Add a space to all labs except the outer most right ones\n nlabs = length(legend_args[[\"legend\"]])\n nidx = nlabs\n if (!is.null(legend_args[[\"ncol\"]])) nidx = tail(1:nlabs, (nlabs %/% legend_args[[\"ncol\"]]))\n legend_args[[\"legend\"]][-nidx] = paste(legend_args[[\"legend\"]][-nidx], \" \")\n }\n # catch for horizontal ribbon legend spacing\n if (type==\"ribbon\") {\n if (legend_args[[\"pt.lwd\"]] == 1) {\n legend_args[[\"x.intersp\"]] = 1\n } else {\n legend_args[[\"x.intersp\"]] = 0.5\n }\n } else if (gradient) {\n legend_args[[\"x.intersp\"]] = 0.5\n }\n }\n \n #\n ## draw the legend ----\n \n # Legend drawing is handled by the internal `tinylegend()` function, which:\n # 1. calculates appropriate insets for \"outer\" legend placement\n # 2. can draw gradient legends (via `gradient_legend()` below)\n #\n # Note: We wrap everything in `recordGraphics()` to preserve legend spacing\n # if the plot is resized (also necessary for Positron graphics logic regardless)\n recordGraphics(\n tinylegend(\n legend_args = legend_args,\n ooma = ooma,\n omar = omar,\n lmar = lmar,\n topmar_epsilon = topmar_epsilon,\n outer_side = outer_side,\n outer_right = outer_right,\n outer_end = outer_end,\n outer_bottom = outer_bottom,\n gradient = gradient,\n draw = draw\n ),\n list = list(\n legend_args = legend_args,\n ooma = ooma,\n omar = omar,\n lmar = lmar,\n topmar_epsilon = topmar_epsilon,\n outer_side = outer_side,\n outer_right = outer_right,\n outer_end = outer_end,\n outer_bottom = outer_bottom,\n gradient = gradient,\n draw = draw\n ),\n env = getNamespace(\"tinyplot\")\n )\n \n}\n\n\n# tinylegend ----\n\n## Internal workhorse function that draws the legend, given a set of legend\n## arguments and other graphical parameters. It does this in three steps:\n## 1) draw a fake legend, 2) calculate the associated inset and adjust the plot\n## margins accordingly, 3) draw the real legend\n\ntinylegend = function(\n legend_args,\n ooma, omar, lmar, topmar_epsilon,\n outer_side, outer_right, outer_end, outer_bottom,\n gradient,\n draw\n) {\n \n #\n ## Step 1: \"draw\" fake legend\n \n fklgnd.args = modifyList(\n legend_args,\n list(plot = FALSE),\n keep.null = TRUE\n )\n \n if (gradient) {\n lgnd_labs_tmp = na.omit(fklgnd.args[[\"legend\"]])\n if (length(lgnd_labs_tmp) < 5L) {\n nmore = 5L - length(lgnd_labs_tmp)\n lgnd_labs_tmp = c(lgnd_labs_tmp, rep(\"\", nmore))\n }\n fklgnd.args = modifyList(\n fklgnd.args,\n list(legend = lgnd_labs_tmp),\n keep.null = TRUE\n )\n if (outer_end) fklgnd.args = modifyList(fklgnd.args, list(title = NULL), keep.null = TRUE)\n }\n \n if (draw) {\n fklgnd = do.call(\"legend\", fklgnd.args)\n } else {\n plot.new()\n fklgnd = do.call(\"legend\", fklgnd.args)\n return(fklgnd)\n }\n \n #\n ## Step 2: Calculate legend inset (for outer placement in plot region)\n \n # calculate outer margin width in lines\n soma = 0\n if (outer_side) {\n soma = grconvertX(fklgnd$rect$w, to=\"lines\") - grconvertX(0, to=\"lines\")\n } else if (outer_end) {\n soma = grconvertY(fklgnd$rect$h, to=\"lines\") - grconvertY(0, to=\"lines\")\n }\n # Add legend margins to the outer margin\n soma = soma + sum(lmar)\n \n ## differing outer margin adjustments depending on side\n if (outer_side) {\n if (outer_right) {\n ooma[4] = soma\n } else {\n ooma[2] = soma\n }\n } else if (outer_end) {\n if (outer_bottom) {\n ooma[1] = soma\n } else {\n omar[3] = omar[3] + soma - topmar_epsilon\n par(mar = omar)\n }\n }\n par(oma = ooma)\n \n # determine legend inset\n inset = 0\n if (outer_side) {\n inset = grconvertX(lmar[1], from=\"lines\", to=\"npc\") - grconvertX(0, from = \"lines\", to = \"npc\")\n # extra space needed for \"left!\" b/c of lhs inner margin\n if (!outer_right) {\n inset_bump = grconvertX(par(\"mar\")[2], from = \"lines\", to = \"npc\") - grconvertX(0, from = \"lines\", to = \"npc\")\n inset = inset + inset_bump\n }\n inset = c(1+inset, 0)\n } else if (outer_end) {\n inset = grconvertY(lmar[1], from=\"lines\", to=\"npc\") - grconvertY(0, from=\"lines\", to=\"npc\")\n if (outer_bottom) {\n # extra space needed for \"bottom!\" b/c of lhs inner margin\n inset_bump = grconvertY(par(\"mar\")[1], from=\"lines\", to=\"npc\") - grconvertY(0, from=\"lines\", to=\"npc\")\n inset = inset + inset_bump\n } else {\n epsilon_bump = grconvertY(topmar_epsilon, from=\"lines\", to=\"npc\") - grconvertY(0, from=\"lines\", to=\"npc\")\n inset = inset + epsilon_bump\n }\n inset = c(0, 1+inset)\n }\n \n # GM: The legend inset spacing only works _exactly_ if we refresh the plot\n # area. I'm not sure why (and it works properly if we use the same\n # parameters manually while debugging), but this hack seems to work.\n ## v0.3.0 update: Using (temporary) hook instead of direct par(new = TRUE)\n ## assignment to play nice with tinytheme logic.\n oldhook = getHook(\"before.plot.new\")\n setHook(\"before.plot.new\", function() par(new = TRUE), action = \"append\")\n setHook(\"before.plot.new\", function() par(mar = omar), action = \"append\")\n plot.new()\n setHook(\"before.plot.new\", oldhook, action = \"replace\")\n \n # Finally, set the inset as part of the legend args.\n legend_args[[\"inset\"]] = inset\n \n #\n ## Step 3: Draw the legend\n\n if (gradient) {\n if (!more_than_n_unique(legend_args[[\"col\"]], 1)) {\n if (!is.null(legend_args[[\"pt.bg\"]]) && length(legend_args[[\"pt.bg\"]])==100) {\n legend_args[[\"col\"]] = legend_args[[\"pt.bg\"]]\n }\n }\n gradient_legend(\n legend_args = legend_args,\n fklgnd = fklgnd,\n lmar = lmar,\n outer_side = outer_side,\n outer_end = outer_end,\n outer_right = outer_right,\n outer_bottom = outer_bottom\n )\n } else {\n do.call(\"legend\", legend_args)\n }\n \n}\n\n\n# gradient legend ----\n\n# For gradient (i.e., continuous color) legends, we'll role our own bespoke\n# legend function based on grDevices::as.raster\n\ngradient_legend = function(legend_args, fklgnd, lmar, outer_side, outer_end, outer_right, outer_bottom) {\n pal = legend_args[[\"col\"]]\n lgnd_labs = legend_args[[\"legend\"]]\n if (!is.null(legend_args[[\"horiz\"]])) horiz = legend_args[[\"horiz\"]] else horiz = FALSE\n if (isTRUE(horiz)) {\n rasterlgd = as.raster(matrix(pal, nrow = 1))\n } else {\n rasterlgd = as.raster(matrix(rev(pal), ncol = 1))\n }\n \n corners = par(\"usr\")\n rasterbox = rep(NA_real_, 4)\n \n inner = !any(c(outer_side, outer_end))\n inner_right = inner_bottom = FALSE\n if (inner) {\n if (!is.null(legend_args[[\"x\"]]) && grepl(\"left$|right$\", legend_args[[\"x\"]])) {\n inner_right = grepl(\"right$\", legend_args[[\"x\"]])\n }\n if (!is.null(legend_args[[\"x\"]]) && grepl(\"^bottoml|^top\", legend_args[[\"x\"]])) {\n inner_bottom = grepl(\"^bottom\", legend_args[[\"x\"]])\n }\n }\n \n if (inner) {\n \n fklgnd$rect$h = fklgnd$rect$h - (grconvertY(1.5 + 0.4, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\"))\n \n rasterbox[1] = fklgnd$rect$left\n if (isFALSE(inner_right)) rasterbox[1] = rasterbox[1] + (grconvertX(0.2, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\"))\n rasterbox[2] = fklgnd$rect$top - fklgnd$rect$h - (grconvertY(1.5 + 0.2, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\"))\n rasterbox[3] = rasterbox[1] + (grconvertX(1.25, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\"))\n rasterbox[4] = rasterbox[2] + fklgnd$rect$h\n \n } else if (outer_side) {\n \n rb1_adj = grconvertX(lmar[1] + 0.2, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\")\n rb3_adj = grconvertX(1.25, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\")\n rb2_adj = (corners[4] - corners[3] - (grconvertY(5+1 + 2.5, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\"))) / 2\n # override if top or bottom\n if (!is.null(legend_args[[\"x\"]])) {\n if (grepl(\"^bottom\", legend_args[[\"x\"]])) {\n rb2_adj = corners[3]\n }\n if (grepl(\"^top\", legend_args[[\"x\"]])) {\n rb2_adj = corners[4] - (grconvertY(5+1 + 2.5, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\"))\n }\n }\n rb4_adj = grconvertY(5+1, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n \n if (outer_right) {\n rasterbox[1] = corners[2] + rb1_adj\n rasterbox[2] = rb2_adj \n rasterbox[3] = rasterbox[1] + rb3_adj\n rasterbox[4] = rasterbox[2] + rb4_adj\n } else {\n rb1_adj = rb1_adj + grconvertX(par(\"mar\")[2] + 1, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\")\n rasterbox[1] = corners[1] - rb1_adj\n rasterbox[2] = rb2_adj \n rasterbox[3] = rasterbox[1] - rb3_adj\n rasterbox[4] = rasterbox[2] + rb4_adj\n }\n \n } else if (outer_end) {\n \n rb1_adj = (corners[2] - corners[1] - (grconvertX(5+1, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\"))) / 2\n rb3_adj = grconvertX(5+1, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\")\n rb2_adj = grconvertY(lmar[1], from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n rb4_adj = grconvertY(1.25, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n \n if (outer_bottom) {\n rb2_adj = rb2_adj + grconvertY(par(\"mar\")[2], from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n rasterbox[1] = rb1_adj\n rasterbox[2] = corners[3] - rb2_adj \n rasterbox[3] = rasterbox[1] + rb3_adj\n rasterbox[4] = rasterbox[2] - rb4_adj\n } else {\n rb2_adj = rb2_adj + grconvertY(1.25 + 1, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n rasterbox[1] = rb1_adj\n rasterbox[2] = corners[4] + rb2_adj \n rasterbox[3] = rasterbox[1] + rb3_adj\n rasterbox[4] = rasterbox[2] - rb4_adj\n }\n \n }\n \n #\n ## Draw the gradient swatch\n \n rasterImage(\n rasterlgd,\n rasterbox[1], #x1\n rasterbox[2], #y1\n rasterbox[3], #x2\n rasterbox[4], #y2\n xpd = NA\n ) \n \n #\n ## Add the labels, tick marks, and title \n \n if (isFALSE(horiz)) {\n labs_idx = !is.na(lgnd_labs)\n lgnd_labs[labs_idx] = paste0(\" \", format(lgnd_labs[labs_idx]))\n lbl_x_anchor = rasterbox[3]\n ttl_x_anchor = rasterbox[1]\n lbl_adj = c(0, 0.5)\n tck_adj = c(1, 0.5)\n ttl_adj = c(0, 0)\n if (!inner && !outer_right) {\n lbl_x_anchor = rasterbox[1]\n ttl_x_anchor = ttl_x_anchor + max(strwidth(lgnd_labs[labs_idx]))\n ttl_adj = c(1, 0)\n }\n text(\n x = lbl_x_anchor,\n y = seq(rasterbox[2], rasterbox[4], length.out = length(lgnd_labs)),\n labels = lgnd_labs,\n xpd = NA, \n adj = lbl_adj\n )\n # legend tick marks\n lgnd_ticks = lgnd_labs\n lgnd_ticks[labs_idx] = \"- -\"\n text(\n x = lbl_x_anchor,\n y = seq(rasterbox[2], rasterbox[4], length.out = length(lgnd_labs)),\n labels = lgnd_ticks, col = \"white\",\n xpd = NA, adj = tck_adj\n )\n # legend title\n text(\n x = ttl_x_anchor,\n y = rasterbox[4] + grconvertY(1, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\"),\n labels = legend_args[[\"title\"]],\n xpd = NA, adj = ttl_adj\n )\n } else {\n lbl_y_anchor = rasterbox[4]\n ttl_y_anchor = rasterbox[4]\n lbl_adj = c(0.5, 1.25)\n tck_adj = c(0, 0.5)\n ttl_adj = c(1, -0.5)\n # legend labs\n text(\n x = seq(rasterbox[1], rasterbox[3], length.out = length(lgnd_labs)),\n y = lbl_y_anchor,\n labels = lgnd_labs,\n xpd = NA, adj = lbl_adj\n )\n # legend tick marks\n lgnd_ticks = lgnd_labs\n lgnd_ticks[!is.na(lgnd_ticks)] = \"- -\"\n text(\n x = seq(rasterbox[1], rasterbox[3], length.out = length(lgnd_labs)),\n y = lbl_y_anchor,\n labels = lgnd_ticks, col = \"white\",\n xpd = NA, adj = tck_adj, srt = 90\n )\n # legend title\n text(\n x = rasterbox[1],\n y = ttl_y_anchor,\n labels = paste0(legend_args[[\"title\"]], \" \"),\n xpd = NA, adj = ttl_adj\n )\n }\n}\n\n\n"], ["/tinyplot/R/type_spline.R", "#' Spline plot type\n#' \n#' @description Type function for plotting a cubic (or Hermite) spline interpolation.\n#' Arguments are passed to \\code{\\link[stats]{spline}}; see this latter function\n#' for default argument values.\n#' \n#' @inheritParams stats::spline\n#' @inherit stats::spline details\n#' @importFrom stats spline\n#' @examples\n#' # \"spline\" type convenience string\n#' tinyplot(dist ~ speed, data = cars, type = \"spline\")\n#' \n#' # Use `type_spline()` to pass extra arguments for customization\n#' tinyplot(dist ~ speed, data = cars, type = type_spline(method = \"natural\", n = 25),\n#' add = TRUE, lty = 2)\n#' @export\ntype_spline = function(\n n = NULL,\n method = \"fmm\",\n xmin = NULL,\n xmax = NULL,\n xout = NULL,\n ties = mean\n ) {\n out = list(\n draw = draw_lines(),\n data = data_spline(method = method, ties = ties, n = n, xmin = xmin, xmax = xmax, xout = xout),\n name = \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_spline = function(n, method, xmin, xmax, xout, ties, ...) {\n fun = function(datapoints, ...) {\n datapoints = split(datapoints, list(datapoints$facet, datapoints$by), drop = TRUE)\n datapoints = lapply(datapoints, function(dat) {\n if (is.null(n)) n = 3*length(dat$x)\n if (is.null(xmax)) xmax = max(dat$x)\n if (is.null(xmin)) xmin = min(dat$x)\n if (is.null(xout)) {\n fit = spline(x = dat$x, y = dat$y, n = n, method = method, xmin = xmin, xmax = xmax, ties = ties)\n } else {\n fit = spline(x = dat$x, y = dat$y, n = n, method = method, xmin = xmin, xmax = xmax, xout = xout, ties = ties)\n }\n fit = as.data.frame(fit)\n fit$facet = dat$facet[1]\n fit$by = dat$by[1]\n fit\n return(fit)\n })\n datapoints = do.call(rbind, datapoints)\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_rug.R", "#' Add a rug to a plot\n#' \n#' @description\n#' Adds a rug representation (1-d plot) of the data to the plot.\n#' \n#' @details\n#' This function should only be used as part of [`tinyplot_add()`], i.e. adding\n#' to an existing plot.\n#' \n#' In most cases, determining which variable receives the rug representation\n#' will be based on the `side` argument (i.e., x-variable if side is 1 or 3, and\n#' y-variable if side is 2 or 4). An exception is if the preceding plot type was\n#' either `\"density\"` or `\"histogram\"`; for these latter cases, the x-variable\n#' will always be used. See Examples.\n#' \n#' @inheritParams graphics::rug\n#' @param jitter Logical. Add jittering to separate ties? Default is `FALSE`.\n#' @param amount Numeric. Amount of jittering (see \\code{\\link[base]{jitter}}).\n#' Only used if `jitter` is `TRUE`.\n#' @examples\n#' tinyplot(~wt | am, data = mtcars, type = \"density\", facet = \"by\", fill = \"by\")\n#' tinyplot_add(type = \"rug\")\n#' # use type_rug() to pass extra options\n#' tinyplot_add(type = type_rug(side = 3, ticksize = 0.05))\n#' \n#' # For ties, use jittering\n#' tinyplot(eruptions ~ waiting, data = faithful, type = \"lm\")\n#' tinyplot_add(type = type_rug(jitter = TRUE, amount = 0.3))\n#' tinyplot_add(type = type_rug(jitter = TRUE, amount = 0.1, side = 2))\n#' # Add original points just for reference\n#' tinyplot_add(type = \"p\")\n#' \n#' @importFrom graphics rug\n#' @export\ntype_rug = function(ticksize = 0.03, side = 1, quiet = getOption(\"warn\") < 0, jitter = FALSE, amount = NULL) {\n data_rug = function(datapoints, ...) {\n if (nrow(datapoints) == 0) {\n msg = \"`type_rug() only works on existing plots with x and y data points.\"\n stop(msg, call. = FALSE)\n }\n return(datapoints)\n }\n draw_rug = function(.ticksize = ticksize, .side = side, .quiet = quiet, .jitter = jitter, .amount = amount) {\n fun = function(ix, iy, icol, ilwd, ...) {\n lc = getOption(\"tinyplot_last_call\", default = NULL)\n swapy = !is.null(lc$type) && lc$type %in% c(\"density\", \"hist\", \"histogram\")\n rugx = if (swapy) iy else if (side %in% c(1, 3)) ix else iy\n if (isTRUE(jitter)) rugx = jitter(rugx, amount = .amount)\n rug(\n x = rugx,\n col = icol,\n lwd = ilwd,\n ticksize = .ticksize,\n side = .side,\n quiet = .quiet\n )\n }\n return(fun)\n }\n\n out = list(\n draw = draw_rug(),\n data = data_rug,\n name = \"rug\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_text.R", "#' Text annotations plot type\n#'\n#' @description Type function for adding text annotations to a plot. This function allows\n#' you to draw text at specified (x,y) coordinates.\n#'\n#' @param labels Character vector of length 1 or of the same length as the\n#' number of x,y coordinates.\n#' @param font Font to be used, following [graphics::par()].\n#' @param xpd Logical value or `NA` denoting text clipping behaviour, following\n#' [graphics::par()].\n#' @param srt Numeric giving the desired string rotation in degrees.\n#' @inheritParams graphics::text\n#' @examples\n#' tinyplot(mpg ~ hp | factor(cyl),\n#' data = mtcars,\n#' type = type_text(\n#' labels = row.names(mtcars),\n#' font = 2,\n#' adj = 0\n#' )\n#' )\n#' \n#' # to avoid clipping text at the plot region, we can use xpd = NA\n#' tinyplot(mpg ~ hp | factor(cyl),\n#' data = mtcars,\n#' type = type_text(\n#' labels = row.names(mtcars),\n#' font = 2,\n#' adj = 0,\n#' xpd = NA\n#' )\n#' )\n#'\n#' @export\ntype_text = function(labels, adj = NULL, pos = NULL, offset = 0.5, vfont = NULL, font = NULL, xpd = NULL, srt = 0) {\n out = list(\n draw = draw_text(adj = adj, pos = pos, offset = offset, vfont = vfont, font = font, xpd = xpd, srt = srt),\n data = data_text(labels = labels),\n name = \"text\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\ndata_text = function(labels) {\n fun = function(datapoints, ...) {\n if (length(labels) != 1 && length(labels) != nrow(datapoints)) {\n msg <- sprintf(\"`labels` must be of length 1 or %s.\", nrow(datapoints))\n stop(msg, call. = FALSE)\n }\n datapoints$labels = labels\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\ndraw_text = function(adj = NULL, pos = NULL, offset = 0.5, vfont = NULL, font = NULL, xpd = NULL, srt = 0) {\n if (is.null(xpd)) xpd = par(\"xpd\")\n fun = function(ix, iy, ilabels, icol, cex, ...) {\n text(\n x = ix, y = iy, labels = ilabels, col = icol,\n adj = adj, pos = pos, offset = offset,\n vfont = vfont, font = font,\n xpd = xpd,\n srt = srt,\n cex = cex\n )\n }\n}\n"], ["/tinyplot/R/type_barplot.R", "#' Barplot type\n#'\n#' @description Type function for producing barplots. For formulas of type\n#' `~ x` (without left-hand side) the barplot visualizes the counts (absolute\n#' frequencies) of the levels of `x`. For formulas of type `y ~ x` the value\n#' of `y` within each level of `x` is visualized, if necessary aggregated\n#' using some function (default: mean).\n#'\n#' @param width numeric, optional vector of bar widths. (The distance between\n#' the midpoints of the bars is always 1.)\n#' @param beside logical. In case of a `by` grouping variable, should bars be\n#' juxtaposed? Default is to use stacked bars instead.\n#' @param center logical or numeric. In case of stacked barplots (`beside = FALSE`)\n#' should the bars be centered (or all start at zero, default)? If set to\n#' `TRUE` the center is at the mid-point of the middle category (in case of\n#' uneven number of categories) or between the two middle categories (in case\n#' of an even number). Additionally it is possible to set `center = 2` or\n#' `center = 2.5` to indicate that centering should be after the second category\n#' or the mid-way in the third category, respectively.\n#' @param FUN a function to compute the summary statistic for `y` within each\n#' group of `x` in case of using a two-sided formula `y ~ x` (default: mean).\n#' @param xlevels a character or numeric vector specifying the ordering of the\n#' levels of the `x` variable (if character) or the corresponding indexes\n#' (if numeric) for the plot.\n#' @param xaxlabels a character vector with the axis labels for the `x` variable,\n#' defaulting to the levels of `x`.\n#' @param drop.zeros logical. Should bars with zero height be dropped? If set\n#' to `FALSE` (default) a zero height bar is still drawn for which the border\n#' lines will still be visible.\n#'\n#' @examples\n#' # Basic examples of frequency tables (without y variable)\n#' tinyplot(~ cyl, data = mtcars, type = \"barplot\")\n#' tinyplot(~ cyl | vs, data = mtcars, type = \"barplot\")\n#' tinyplot(~ cyl | vs, data = mtcars, type = \"barplot\", beside = TRUE)\n#' tinyplot(~ cyl | vs, data = mtcars, type = \"barplot\", beside = TRUE, fill = 0.2)\n#' \n#' # Reorder x variable categories either by their character levels or numeric indexes\n#' tinyplot(~ cyl, data = mtcars, type = \"barplot\", xlevels = c(\"8\", \"6\", \"4\"))\n#' tinyplot(~ cyl, data = mtcars, type = \"barplot\", xlevels = 3:1)\n#' \n#' # Note: Above we used automatic argument passing for `beside`. But this\n#' # wouldn't work for `width`, since it would conflict with the top-level\n#' # `tinyplot(..., width = )` argument. It's safer to pass these args\n#' # through the `type_barplot()` functional equivalent.\n#' tinyplot(~ cyl | vs, data = mtcars, fill = 0.2,\n#' type = type_barplot(beside = TRUE, drop.zeros = TRUE, width = 0.65))\n#'\n#' tinytheme(\"clean2\")\n#' \n#' # Example for numeric y aggregated by x (default: FUN = mean) + facets\n#' tinyplot(extra ~ ID | group, facet = \"by\", data = sleep,\n#' type = \"barplot\", fill = 0.6)\n#' \n#' # Fancy frequency table:\n#' tinyplot(Freq ~ Sex | Survived, facet = ~ Class, data = as.data.frame(Titanic),\n#' type = \"barplot\", facet.args = list(nrow = 1), flip = TRUE, fill = 0.6)\n#'\n#' # Centered barplot for conditional proportions of hair color (black/brown vs.\n#' # red/blond) given eye color and sex\n#' tinytheme(\"clean2\", palette.qualitative = c(\"black\", \"sienna\", \"indianred\", \"goldenrod\"))\n#' hec = as.data.frame(proportions(HairEyeColor, 2:3))\n#' tinyplot(Freq ~ Eye | Hair, facet = ~ Sex, data = hec, type = \"barplot\",\n#' center = TRUE, flip = TRUE, facet.args = list(ncol = 1), yaxl = \"percent\")\n#'\n#' tinytheme()\n#' \n#' @export\ntype_barplot = function(width = 5/6, beside = FALSE, center = FALSE, FUN = NULL, xlevels = NULL, xaxlabels = NULL, drop.zeros = FALSE) {\n out = list(\n data = data_barplot(width = width, beside = beside, center = center, FUN = FUN, xlevels = xlevels, xaxlabels = xaxlabels, drop.zeros = drop.zeros),\n draw = draw_rect(),\n name = \"barplot\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n#' @importFrom stats aggregate\ndata_barplot = function(width = 5/6, beside = FALSE, center = FALSE, FUN = NULL, xlevels = NULL, xaxlabels = NULL, drop.zeros = FALSE) {\n fun = function(datapoints, col, bg, lty, lwd, palette, xlab = NULL, ylab = NULL, xlim = NULL, ylim = NULL, xaxt = NULL, yaxl = NULL, yaxt = NULL, axes = TRUE, null_by, facet_by, ...) {\n\n \n ## tabulate/aggregate datapoints\n if (is.null(datapoints$y)) {\n xlab = ylab\n ylab = \"Count\"\n \n datapoints$y = numeric(nrow(datapoints)) \n if (!is.null(FUN)) warning(\"without 'y' variable 'FUN' specification is ignored\")\n FUN = length\n } else {\n if (is.null(FUN)) FUN = function(x, ...) mean(x, ..., na.rm = TRUE)\n }\n if (!is.factor(datapoints$x)) datapoints$x = factor(datapoints$x)\n if (!is.null(xlevels)) {\n xlevels = if(is.numeric(xlevels)) levels(datapoints$x)[xlevels] else xlevels\n if (any(is.na(xlevels)) || !all(xlevels %in% levels(datapoints$x))) warning(\"not all 'xlevels' correspond to levels of 'x'\")\n datapoints$x = factor(datapoints$x, levels = xlevels)\n }\n if (!is.null(xaxlabels)) levels(datapoints$x) <- xaxlabels\n datapoints = aggregate(datapoints[, \"y\", drop = FALSE], datapoints[, c(\"x\", \"by\", \"facet\")], FUN = FUN, drop = FALSE)\n datapoints$y[is.na(datapoints$y)] = 0 #FIXME: always?#\n if (!is.factor(datapoints$by)) datapoints$by = factor(datapoints$by)\n if (!is.factor(datapoints$facet)) datapoints$facet = factor(datapoints$facet)\n \n if (isFALSE(null_by) && isFALSE(facet_by) && !beside && any(datapoints$y < 0)) {\n warning(\"'beside' must be TRUE if there are negative 'y' values\")\n beside = TRUE\n }\n if (beside & !isFALSE(center)) {\n warning(\"'center' is currently only supported for 'beside = FALSE'\")\n }\n offset_sum = function(z, center = TRUE, na.rm = TRUE) {\n n = length(z)\n if (isFALSE(center) || n < 1L) return(0)\n mid = if (isTRUE(center)) n/2 else center\n z[floor(mid) + 1L] = (mid - floor(mid)) * z[floor(mid) + 1L]\n sum(z[0L:floor(mid) + 1L], na.rm = TRUE)\n }\n if (is.null(xlim)) xlim = c(1, length(levels(datapoints$x))) + c(-0.5, 0.5) * width\n if (is.null(ylim)) ylim = if (beside || length(unique(datapoints$by)) == 1L) {\n c(pmin(0, min(datapoints$y, na.rm = TRUE) * 1.02), pmax(0, max(datapoints$y, na.rm = TRUE) * 1.02))\n } else {\n range(unlist(tapply(\n datapoints$y,\n interaction(datapoints$x, datapoints$facet),\n function(z) c(0, sum(z, na.rm = TRUE)) - offset_sum(z, center = center)\n ))) * 1.02\n }\n\n ## default color palette\n ngrps = length(unique(datapoints$by))\n if (ngrps == 1L && is.null(palette)) {\n if (is.null(col)) col = par(\"fg\")\n if (is.null(bg)) bg = \"grey\"\n } else {\n if (is.null(bg)) bg = \"by\"\n }\n\n ## calculate bar rectangles per facet \n sdat = split(datapoints, datapoints$facet)\n datapoints = lapply(sdat, function(df) {\n \n df = df[order(df$x), , drop = FALSE]\n nx = length(levels(df$x))\n nb = length(levels(df$by))\n \n if (beside) { \n xl = as.numeric(df$x) - width/2 + (as.numeric(df$by) - 1) * width/nb * as.numeric(!facet_by)\n xr = if (facet_by) xl + width else xl + width/nb\n yb = 0\n yt = df$y\n } else {\n cs = tapply(df$y, df$x, function(z) cumsum(c(0, z)) - offset_sum(z, center = center))\n xl = as.numeric(df$x) - width/2\n xr = xl + width\n yb = if (facet_by) 0 else unlist(lapply(cs, `[`, -(nb + 1L)))\n yt = if (facet_by) df$y else unlist(lapply(cs, `[`, -1L))\n }\n \n df$xmin = xl\n df$xmax = xr\n df$ymin = yb\n df$ymax = yt\n df$nx = nx\n \n if (drop.zeros) {\n yb = rep_len(yb, length(yt))\n yok = abs(yt - yb) > 0\n df = df[yok, , drop = FALSE]\n }\n \n return(df)\n })\n datapoints = do.call(\"rbind\", datapoints)\n nx = datapoints$nx[1]\n datapoints$nx = NULL\n xlabs = 1L:nx\n names(xlabs) = levels(datapoints$x)\n \n if (!isFALSE(center)) {\n if (is.null(yaxl)) {\n yaxl = abs\n } else if (is.character(yaxl)) {\n yaxl = paste0(\"abs_\", yaxl)\n }\n }\n \n out = list(\n datapoints = datapoints,\n xlab = xlab,\n ylab = ylab,\n xlim = xlim,\n ylim = ylim,\n axes = FALSE, #FIXME\n axes = TRUE,\n xlabs = xlabs, \n frame.plot = FALSE,\n xaxs = \"r\",\n xaxt = if (xaxt == \"s\") \"l\" else xaxt,\n yaxl = yaxl,\n yaxs = \"i\",\n col = col,\n bg = bg\n )\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_density.R", "#' Density plot type\n#' \n#' @md\n#' @description Type function for density plots.\n#' @inheritParams stats::density\n#' @param kernel a character string giving the smoothing kernel to be used. This\n#' must partially match one of `\"gaussian\"`, `\"rectangular\"`, `\"triangular\"`,\n#' `\"epanechnikov\"`, `\"biweight\"`, `\"cosine\"` or `\"optcosine\"`, with default\n#' `\"gaussian\"`, and may be abbreviated to a unique prefix (single letter).\n#'\n#' `\"cosine\"` is smoother than `\"optcosine\"`, which is the usual 'cosine'\n#' kernel in the literature and almost MSE-efficient. However, `\"cosine\"` is\n#' the version used by S.\n#' @inheritParams type_ribbon\n#' @param joint.bw character string indicating whether (and how) the smoothing\n#' bandwidth should be computed from the joint data distribution when there\n#' are multiple subgroups. The options are `\"mean\"` (the default), `\"full\"`,\n#' and `\"none\"`. Also accepts a logical argument, where `TRUE` maps to\n#' `\"mean\"` and `FALSE` maps to `\"none\"`. See the \"Bandwidth selection\"\n#' section below for a discussion of practical considerations.\n#' @inherit stats::density details\n#' @section Bandwidth selection: While the choice of smoothing bandwidth will\n#' always stand to affect a density visualization, it gains an added\n#' importance when multiple densities are drawn simultaneously (e.g., for\n#' subgroups with respect to `by` or `facet`). Allowing each subgroup to\n#' compute its own separate bandwidth independently offers greater flexibility\n#' in capturing the unique characteristics of each subgroup, particularly when\n#' distributions differ substantially in location and/or scale. However, this\n#' approach may overemphasize small random variations and make it harder to\n#' visually compare densities across subgroups. Hence, it is often useful to\n#' employ the same (\"joint\") bandwidth across all subgroups. The following\n#' strategies are available via the `joint.bw` argument:\n#' \n#' - The default `joint.bw = \"mean\"` first computes the individual bandwidths\n#' for each group but then computes their mean, weighted by the number of\n#' observations in each group. This will work well when all groups have\n#' similar amounts of scatter (similar variances), even when they have\n#' potentially rather different locations. The weighted averaging stabilizes\n#' potential fluctuations in the individual bandwidths, especially when some\n#' subgroups are rather small.\n#' \n#' - Alternatively, `joint.bw = \"full\"` can be used to compute the joint\n#' bandwidth from the full joint distribution (merging all groups). This will\n#' yield an even more robust bandwidth, especially when the groups overlap\n#' substantially (i.e., have similar locations and scales). However, it may\n#' lead to too large bandwidths and thus too much smoothing, especially when\n#' the locations of the groups differ substantially.\n#' \n#' - Finally, `joint.bw = \"none\"` disables the joint bandwidth so that each\n#' group just employs its individual bandwidth. This is often the best choice\n#' if the amounts of scatter differ substantially between the groups, thus\n#' necessitating different amounts of smoothing.\n#' @section Titles: This tinyplot method for density plots differs from the base\n#' \\code{\\link[stats]{plot.density}} function in its treatment of titles. The\n#' x-axis title displays only the variable name, omitting details about the\n#' number of observations and smoothing bandwidth. Additionally, the main\n#' title is left blank by default for a cleaner appearance.\n#' @examples\n#' # \"density\" type convenience string\n#' tinyplot(~Sepal.Length, data = iris, type = \"density\")\n#' \n#' # grouped density example\n#' tinyplot(~Sepal.Length | Species, data = iris, type = \"density\")\n#' \n#' # use `bg = \"by\"` (or, equivalent `fill = \"by\"`) to get filled densities\n#' tinyplot(~Sepal.Length | Species, data = iris, type = \"density\", fill = \"by\")\n#' \n#' # use `type_density()` to pass extra arguments for customization\n#' tinyplot(\n#' ~Sepal.Length | Species, data = iris,\n#' type = type_density(bw = \"SJ\"),\n#' main = \"Bandwidth computed using Sheather & Jones (1991)\"\n#' )\n#' \n#' # The default for grouped density plots is to use the mean of the\n#' # individual subgroup bandwidths (weighted by group size) as the\n#' # joint bandwidth. Alternatively, the bandwidth from the \"full\"\n#' # data or separate individual bandwidths (\"none\") can be used.\n#' tinyplot(~Sepal.Length | Species, data = iris,\n#' ylim = c(0, 1.25), type = \"density\") # mean (default)\n#' tinyplot_add(joint.bw = \"full\", lty = 2) # full data\n#' tinyplot_add(joint.bw = \"none\", lty = 3) # none (individual)\n#' legend(\"topright\", c(\"Mean\", \"Full\", \"None\"), lty = 1:3, bty = \"n\", title = \"Joint BW\")\n#' \n#' @importFrom stats density weighted.mean\n#' @importFrom stats bw.SJ bw.bcv bw.nrd bw.nrd0 bw.ucv \n#' @export\ntype_density = function(\n bw = \"nrd0\",\n joint.bw = c(\"mean\", \"full\", \"none\"),\n adjust = 1,\n kernel = c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"),\n n = 512,\n # more args from density here?\n alpha = NULL\n ) {\n kernel = match.arg(kernel, c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"))\n if (is.logical(joint.bw)) {\n joint.bw = ifelse(joint.bw, \"mean\", \"none\")\n }\n joint.bw = match.arg(joint.bw, c(\"mean\", \"full\", \"none\"))\n out = list(\n data = data_density(bw = bw, adjust = adjust, kernel = kernel, n = n,\n joint.bw = joint.bw, alpha = alpha),\n draw = NULL,\n name = \"density\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\ndata_density = function(bw = \"nrd0\", adjust = 1, kernel = \"gaussian\", n = 512,\n joint.bw = \"none\", alpha = NULL) {\n fun = function(by, facet, ylab, col, bg, ribbon.alpha, datapoints, ...) {\n \n ribbon.alpha = if (is.null(alpha)) .tpar[[\"ribbon.alpha\"]] else (alpha)\n \n if (is.null(ylab)) ylab = \"Density\"\n \n datapoints = split(datapoints, list(datapoints$by, datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n \n if (joint.bw == \"none\" || is.numeric(bw)) {\n dens_bw = bw\n } else {\n if (joint.bw == \"mean\") {\n # Use weighted mean of subgroup bandwidths\n bws = sapply(datapoints, function(dat) bw_fun(kernel = bw, dat$x))\n ws = sapply(datapoints, nrow)\n dens_bw = weighted.mean(bws, ws)\n } else if (joint.bw == \"full\") {\n dens_bw = bw_fun(kernel = bw, unlist(sapply(datapoints, `[[`, \"x\")))\n }\n }\n \n datapoints = lapply(datapoints, function(dat) {\n d = density(dat$x, bw = dens_bw, kernel = kernel, n = n)\n out = data.frame(\n by = dat$by[1], # already split\n facet = dat$facet[1], # already split\n y = d$y,\n x = d$x\n )\n return(out)\n })\n datapoints = do.call(rbind, datapoints)\n datapoints$ymax = datapoints$y\n datapoints$ymin = rep.int(0, nrow(datapoints))\n \n # flags for legend and fill\n dtype = if (!is.null(bg)) \"ribbon\" else \"l\"\n dwas_area_type = !is.null(bg)\n \n out = list(\n ylab = ylab,\n type = dtype,\n was_area_type = dwas_area_type,\n ribbon.alpha = ribbon.alpha,\n datapoints = datapoints,\n by = if (length(unique(datapoints$by)) == 1) by else datapoints$by, \n facet = if (length(unique(datapoints$facet)) == 1) facet else datapoints$facet\n )\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/tinytheme.R", "#' Set or Reset Plot Themes for `tinyplot`\n#'\n#' @md\n#' @description\n#' The `tinytheme` function sets or resets the theme for plots created with\n#' `tinyplot`. Themes control the appearance of plots, such as text alignment,\n#' font styles, axis labels, and even dynamic margin adjustment to reduce\n#' whitespace.\n#'\n#' @param theme A character string specifying the name of the theme to apply.\n#' Themes are arranged in an approximate hierarchy, adding or subtracting\n#' elements in the order presented below. Note that several themes are\n#' _dynamic_, in the sense that they attempt to reduce whitespace in a way\n#' that is responsive to the length of axes labels, tick marks, etc. These\n#' dynamic plots are marked with an asterisk (*) below.\n#' \n#' - `\"default\"`: inherits the user's default base graphics settings.\n#' - `\"basic\"`: light modification of `\"default\"`, only adding filled points, a panel background grid, and light gray background to facet titles.\n#' - `\"clean\"` (*): builds on `\"basic\"` by moving the subtitle above the plotting area, adding horizontal axis labels, employing tighter default plot margins and title gaps to reduce whitespace, and setting different default palettes (\"Tableau 10\" for discrete colors and \"agSunset\" for gradient colors). The first of our dynamic themes and the foundation for several derivative themes that follow below.\n#' - `\"clean2\"` (*): removes the plot frame (box) from `\"clean\"`.\n#' - `\"classic\"` (*): connects the axes in a L-shape, but removes the other top and right-hand edges of the plot frame (box). Also sets the \"Okabe-Ito\" palette as a default for discrete colors. Inspired by the **ggplot2** theme of the same name. \n#' - `\"bw\"` (*): similar to `\"clean\"`, except uses thinner lines for the plot frame (box), solid grid lines, and sets the \"Okabe-Ito\" palette as a default for discrete colors. Inspired by the **ggplot2** theme of the same name. \n#' - `\"minimal\"` (*): removes the plot frame (box) from `\"bw\"`, as well as the background for facet titles. Inspired by the **ggplot2** theme of the same name. \n#' - `\"ipsum\"` (*): similar to `\"minimal\"`, except subtitle is italicised and axes titles are aligned to the far edges. Inspired by the **hrbrthemes** theme of the same name for **ggplot2**. \n#' - `\"dark\"` (*): similar to `\"minimal\"`, but set against a dark background with foreground and a palette colours lightened for appropriate contrast.\n#' - `\"ridge\"` (*): a specialized theme for ridge plots (see [`type_ridge()`]). Builds off of `\"clean\"`, but adds ridge-specific tweaks (e.g. default \"Zissou 1\" palette for discrete colors, solid horizontal grid lines, and minor adjustments to y-axis labels). Not recommended for non-ridge plots.\n#' - `\"ridge2\"` (*): removes the plot frame (box) from `\"ridge\"`, but retains the x-axis line. Again, not recommended for non-ridge plots.\n#' - `\"tufte\"`: floating axes and minimalist plot artifacts in the style of Edward Tufte.\n#' - `\"void\"`: switches off all axes, titles, legends, etc.\n#' @param ... Named arguments to override specific theme settings. These\n#' arguments are passed to `tpar()` and take precedence over the predefined\n#' settings in the selected theme.\n#'\n#' @details\n#' Sets a list of graphical parameters using `tpar()`\n#'\n#' To reset the theme to default settings (no customization), call `tinytheme()`\n#' without arguments.\n#' \n#' **Caveat emptor:** Themes are a somewhat experimental feature of `tinyplot`.\n#' While we feel confident that themes should work as expected for most\n#' \"standard\" cases, there may be some sharp edges. Please report any unexpected\n#' behaviour to our GitHub repo:\n#' \n#' \n#' Known current limitations include:\n#' \n#' - Themes do not work well when `legend = \"top!\"`.\n#' - Dynamic margin spacing does not account for multi-line strings (e.g., axes\n#' or main titles that contain \"\\\\n\").\n#'\n#' @return The function returns nothing. It is called for its side effects.\n#' \n#' @seealso [`tpar`] which does the heavy lifting under the hood.\n#'\n#' @examples\n#' # Reusable plot function\n#' p = function() tinyplot(\n#' lat ~ long | depth, data = quakes,\n#' main = \"Earthquakes off Fiji\",\n#' sub = \"Data courtesy of the Harvard PRIM-H project\"\n#' )\n#' p()\n#' \n#' # Set a theme\n#' tinytheme(\"bw\")\n#' p()\n#'\n#' # Try a different theme\n#' tinytheme(\"dark\")\n#' p()\n#' \n#' # Customize the theme by overriding default settings\n#' tinytheme(\"bw\", fg = \"green\", font.main = 2, font.sub = 3, family = \"Palatino\")\n#' p()\n#' \n#' # Another custom theme example\n#' tinytheme(\"bw\", font.main = 2, col.axis = \"darkcyan\", family = \"HersheyScript\")\n#' p()\n#' \n#' # Aside: One or two specialized themes are only meant for certain plot types\n#' tinytheme(\"ridge2\")\n#' tinyplot(I(cut(lat, 10)) ~ depth, data = quakes, type = \"ridge\")\n#'\n#' # Reset the theme\n#' tinytheme()\n#' p()\n#' \n#' # Themes showcase\n#' ## We'll use a slightly more intricate plot (long y-axis labs and facets)\n#' ## to demonstrate dynamic margin adjustment etc.\n#' \n#' thms = eval(formals(tinytheme)$theme)\n#' \n#' for (thm in thms) {\n#' tinytheme(thm)\n#' tinyplot(\n#' I(Sepal.Length*1e4) ~ Petal.Length | Species, facet = \"by\", data = iris,\n#' main = \"Demonstration of tinyplot themes\",\n#' sub = paste0('tinytheme(\"', thm, '\")')\n#' )\n#' }\n#' \n#' # Reset\n#' tinytheme()\n#'\n#' @export\ntinytheme = function(\n theme = c(\n \"default\", \"basic\",\n \"clean\", \"clean2\", \"bw\", \"classic\",\n \"minimal\", \"ipsum\", \"dark\",\n \"ridge\", \"ridge2\",\n \"tufte\", \"void\"\n ),\n ...\n ) {\n \n theme = match.arg(theme)\n\n # in notebooks, we don't want to close the device because no image.\n # init_tpar() tries to be smart, but may fail.\n init_tpar(rm_hook = TRUE)\n\n assert_choice(\n theme,\n c(\n \"default\",\n sort(c(\"basic\", \"bw\", \"classic\", \"clean\", \"clean2\", \"dark\", \"ipsum\",\n \"minimal\", \"ridge\", \"ridge2\", \"tufte\", \"void\"))\n )\n )\n\n settings = switch(theme,\n \"default\" = theme_default,\n \"basic\" = theme_basic,\n \"bw\" = theme_bw,\n \"classic\" = theme_classic,\n \"clean\" = theme_clean,\n \"clean2\" = theme_clean2,\n \"dark\" = theme_dark,\n \"ipsum\" = theme_ipsum,\n \"minimal\" = theme_minimal,\n \"ridge\" = theme_ridge,\n \"ridge2\" = theme_ridge2,\n \"tufte\" = theme_tufte,\n \"void\" = theme_void,\n )\n\n dots = list(...)\n for (n in names(dots)) {\n settings[[n]] = dots[[n]]\n }\n\n if (length(settings) > 0) {\n if (theme == \"default\") {\n # for default theme, we want to revert the original pars and turn off the\n # before.new.plot hook (otherwise manual par(x = y) changes won't work) \n tpar(settings, hook = FALSE)\n old_hooks = get_environment_variable(\".tpar_hooks\")\n remove_hooks(old_hooks)\n } else {\n tpar(settings, hook = TRUE)\n }\n }\n\n return(invisible(NULL))\n}\n\n\n\n#\n## Themes (these are read and set at initial load time)\n\n# theme_default = list()\n\ntheme_default = list(\n tinytheme = \"default\",\n adj = par(\"adj\"), # 0.5,\n adj.main = par(\"adj\"), # 0.5,\n adj.sub = par(\"adj\"), # 0.5,\n bg = \"white\", # par(\"bg\") # \"white\"\n bty = par(\"bty\"), #\"o\",\n cex.axis = par(\"cex.axis\"), #1,\n cex.main = par(\"cex.main\"), #1.2,\n cex.xlab = par(\"cex.axis\"), #1,\n cex.ylab = par(\"cex.axis\"), #1,\n col.axis = par(\"col.axis\"), #1,\n col.xaxs = par(\"col.axis\"), #1,\n col.yaxs = par(\"col.axis\"), #1,\n col.lab = par(\"col.lab\"), #\"black\",\n col.main = par(\"col.main\"), #\"black\",\n col.sub = par(\"col.sub\"), #\"black\",\n dynmar = FALSE,\n facet.bg = NULL,\n facet.border = NA,\n family = par(\"family\"), # \"\"\n fg = par(\"fg\"),\n font = par(\"font\"), # 1,\n font.axis = par(\"font.axis\"), # 1,\n font.lab = par(\"font.lab\"), # 1,\n font.main = par(\"font.main\"), # 2,\n font.sub = par(\"font.sub\"), # 2,\n grid = FALSE,\n grid.col = \"lightgray\",\n grid.lty = \"dotted\",\n grid.lwd = 1,\n lab = par(\"lab\"), # c(5, 5, 7),\n las = par(\"las\"), # 0,\n lwd = par(\"lwd\"), # 1,\n lwd.axis = par(\"lwd\"), # 1,\n mar = c(5.1, 4.1, 4.1, 2.1), ## test\n mgp = par(\"mgp\"),\n # palette.qualitative = \"R4\",\n # palette.sequential = \"Viridis\",\n pch = par(\"pch\"), # 1,\n side.sub = 1,\n tck = NA,\n xaxt = \"standard\",\n yaxt = \"standard\"\n)\n\n# derivatives of \"default\" \n# - basic\n# - tufte\n# - void\n\ntheme_basic = modifyList(theme_default, list(\n tinytheme = \"basic\",\n facet.bg = \"gray90\",\n facet.border = \"black\",\n grid = TRUE,\n pch = 16\n))\n\ntheme_tufte = modifyList(theme_default, list(\n tinytheme = \"tufte\",\n adj.main = 0,\n adj.sub = 0,\n bty = \"n\",\n font.main = 1,\n lab = c(10, 10, 7),\n # palette.sequential = \"Grays\",\n pch = 16,\n side.sub = 3,\n tcl = 0.2\n))\n\ntheme_void = modifyList(theme_default, list(\n tinytheme = \"void\",\n adj.main = 0,\n adj.sub = 0,\n font.main = 1,\n palette.qualitative = \"Tableau 10\",\n palette.sequential = \"ag_Sunset\",\n pch = 16,\n side.sub = 3,\n # tck = -.02,\n xaxt = \"none\",\n yaxt = \"none\"\n))\n\n# derivatives of \"basic\" \n# - clean\n\ntheme_clean = modifyList(theme_basic, list(\n ## Notes:\n ## - 1. Reduce axis title gap by 0.5 lines and also reduce tcl to 0.3 lines.\n ## - 2. Sub moves to top.\n ## - 3. Also want to remove excess white on rhs of plot margin (when no legend).\n ## - Together, 1, 2, and 3 imply that...\n ## -- mgp[1] should be adjusted by 0.8 (= 0.5 + 0.3)\n ## -- mgp[2] should be adjusted by 0.3\n ## -- mar[1] should be adjusted by 1.8 (= 1 (no sub) + 0.5 + 0.3 (tighter axis labs))\n ## -- mar[2] should be adjusted by 0.8 (= 0.5 + 0.3)\n ## -- mar[3] should remain unchanged (main + sub will adjust automatically)\n ## -- mar[4] should be adjusted by 1.5 (relative to 2.1)\n ##\n tinytheme = \"clean\",\n adj.main = 0,\n adj.sub = 0,\n dynmar = TRUE,\n las = 1,\n mar = c(5.1, 4.1, 4.1, 2.1) - c(1+0.5+0.3, 0.5+0.3, 0, 1.5), ## test\n mgp = c(3, 1, 0) - c(0.5+0.3, 0.3, 0), # i.e., subtract 0.5 lines + the (abs) value of the tcl adjustment\n palette.qualitative = \"Tableau 10\",\n palette.sequential = \"ag_Sunset\",\n side.sub = 3,\n tcl = -0.3\n))\n\n# derivatives of \"clean\" \n# - clean2\n# - classic\n# - bw\n\ntheme_clean2 = modifyList(theme_clean, list(\n tinytheme = \"clean2\",\n facet.border = \"gray90\",\n xaxt = \"labels\",\n yaxt = \"labels\"\n))\n\ntheme_classic = modifyList(theme_clean, list(\n tinytheme = \"classic\",\n bty = \"l\",\n facet.bg = NULL,\n font.main = 1,\n grid = FALSE,\n palette.qualitative = \"Okabe-Ito\"\n))\n\ntheme_bw = modifyList(theme_clean, list(\n tinytheme = \"bw\",\n font.main = 1,\n grid.lty = 1,\n grid.lwd = 0.5,\n lwd = 0.5,\n lwd.axis = 0.5,\n palette.qualitative = \"Okabe-Ito\"\n))\n\n# derivatives of \"bw\"\n# - minimal\n# - ipsum\n# - dark\n \ntheme_minimal = modifyList(theme_bw, list(\n tinytheme = \"minimal\",\n bty = \"n\",\n facet.bg = NULL,\n facet.border = NULL,\n xaxt = \"labels\",\n yaxt = \"labels\"\n))\n\ntheme_ipsum = modifyList(theme_minimal, list(\n tinytheme = \"ipsum\",\n bty = \"n\",\n font.sub = 3,\n adj.ylab = 1,\n adj.xlab = 1\n))\n\ntheme_dark = modifyList(theme_minimal, list(\n tinytheme = \"dark\",\n bg = \"#1A1A1A\",\n fg = \"#BBBBBB\",\n # col = \"white\",\n col.xaxs = \"#BBBBBB\",\n col.yaxs = \"#BBBBBB\",\n col.lab = \"#BBBBBB\",\n col.main = \"#BBBBBB\",\n col.sub = \"#BBBBBB\",\n col.axis = \"#BBBBBB\",\n # facet.bg = \"gray20\",\n grid.col = \"#6D6D6D\",\n palette.qualitative = \"Set 2\",\n palette.sequential = \"Sunset\"\n))\n\n# derivative of clean/clean2\n\ntheme_ridge = modifyList(theme_clean, list(\n tinytheme = \"ridge\",\n palette.qualitative = \"Zissou 1\",\n grid = FALSE\n))\ntheme_ridge2 = modifyList(theme_clean2, list(\n tinytheme = \"ridge2\",\n palette.qualitative = \"Zissou 1\",\n grid = FALSE\n))\n"], ["/tinyplot/R/type_glm.R", "#' Generalized linear model plot type\n#' \n#' @description Type function for plotting a generalized model fit.\n#' Arguments are passed to \\code{\\link[stats]{glm}}.\n#' \n#' @param se logical. If TRUE, confidence intervals are drawn.\n#' @inheritParams stats::glm\n#' @inheritParams stats::predict.glm\n#' @inheritParams stats::confint\n#' @importFrom stats glm predict\n#' @examples\n#' # \"glm\" type convenience string\n#' tinyplot(am ~ mpg, data = mtcars, type = \"glm\")\n#' \n#' # Use `type_glm()` to pass extra arguments for customization\n#' tinyplot(am ~ mpg, data = mtcars, type = type_glm(family = \"binomial\"))\n#' @export\ntype_glm = function(family = \"gaussian\", se = TRUE, level = 0.95, type = \"response\") {\n assert_flag(se)\n out = list(\n draw = draw_ribbon(),\n data = data_glm(family = family, se = se, level = level, type = type),\n name = if (isTRUE(se)) \"ribbon\" else \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_glm = function(family, se, level, type, ...) {\n fun = function(datapoints, ...) {\n dat = split(datapoints, list(datapoints$facet, datapoints$by))\n dat = lapply(dat, function(x) {\n if (nrow(x) == 0) return(x)\n if (nrow(x) < 3) {\n x$y = NA\n return(x)\n }\n fit = glm(y ~ x, data = x, family = family)\n nd = data.frame(x = seq(min(x$x, na.rm = TRUE), max(x$x, na.rm = TRUE), length.out = 100))\n nd$by = x$by[1]\n nd$facet = x$facet[1]\n if (se == TRUE) {\n if (identical(type, \"response\")) {\n p = predict(fit, newdata = nd, type = \"link\", se.fit = TRUE)\n p = ci(p$fit, p$se.fit, conf.level = level, fit$df.residual, backtransform = stats::family(fit)$linkinv)\n nd$y = p$estimate\n nd$ymax = p$conf.high\n nd$ymin = p$conf.low\n\n } else {\n nd$y = predict(fit, newdata = nd, type = type)\n nd = ci(nd$y, nd$se, level, fit$df.residual, backtransform = stats::family(fit)$linkinv)\n }\n } else {\n nd$y = predict(fit, nd, type = type)\n }\n nd\n })\n datapoints = do.call(rbind, dat)\n datapoints = datapoints[order(datapoints$facet, datapoints$by, datapoints$x), ]\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\n\n#' Calculate confidence intervals\n#' @importFrom stats qt\n#' @keywords internal\nci = function(estimate, std.error, conf.level, df, backtransform = identity) {\n crit = qt(1 - (1 - conf.level) / 2, df)\n out = list(\n estimate = backtransform(estimate),\n conf.low = backtransform(estimate - crit * std.error),\n conf.high = backtransform(estimate + crit * std.error)\n )\n return(out)\n}\n"], ["/tinyplot/R/type_lm.R", "#' Linear model plot type\n#'\n#' @description Type function for plotting a linear model fit.\n#' Arguments are passed to \\code{\\link[stats]{lm}}.\n#' \n#' @inheritParams type_glm\n#' @importFrom stats lm predict\n#' @examples\n#' # \"lm\" type convenience string\n#' tinyplot(Sepal.Width ~ Petal.Width, data = iris, type = \"lm\")\n#' \n#' # Grouped model fits (here: illustrating an example of Simpson's paradox)\n#' tinyplot(Sepal.Width ~ Petal.Width | Species, data = iris, type = \"lm\")\n#' tinyplot_add(type = \"p\")\n#' \n#' # Use `type_lm()` to pass extra arguments for customization\n#' tinyplot(Sepal.Width ~ Petal.Width, data = iris, type = type_lm(level = 0.8))\n#' @export\ntype_lm = function(se = TRUE, level = 0.95) {\n assert_flag(se)\n out = list(\n draw = draw_ribbon(),\n data = data_lm(se = se, level = level),\n name = if (isTRUE(se)) \"ribbon\" else \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_lm = function(se, level, ...) {\n fun = function(datapoints, ...) {\n dat = split(datapoints, list(datapoints$facet, datapoints$by))\n dat = lapply(dat, function(x) {\n if (nrow(x) == 0) return(x)\n if (nrow(x) < 3) {\n x$y = NA\n return(x)\n }\n fit = lm(y ~ x, data = x)\n nd = data.frame(x = seq(min(x$x, na.rm = TRUE), max(x$x, na.rm = TRUE), length.out = 100))\n nd$by = x$by[1]\n nd$facet = x$facet[1]\n if (se == TRUE) {\n p = predict(fit, newdata = nd, se.fit = TRUE)\n p = ci(p$fit, p$se.fit, conf.level = level, fit$df.residual)\n nd$y = p$estimate\n nd$ymax = p$conf.high\n nd$ymin = p$conf.low\n } else {\n nd$y = predict(fit, newdata = nd)\n }\n nd\n })\n datapoints = do.call(rbind, dat)\n datapoints = datapoints[order(datapoints$facet, datapoints$by, datapoints$x), ]\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_hline.R", "#' @rdname type_abline\n#' @param h y-value(s) for horizontal line(s). Numeric of length 1, or equal to\n#' the number of groups or number of facets (or the product thereof).\n#' @export\ntype_hline = function(h = 0) {\n assert_numeric(h)\n data_hline = function(datapoints, lwd, lty, col, ...) {\n if (nrow(datapoints) == 0) {\n msg = \"`type_hline() only works on existing plots with x and y data points.\"\n stop(msg, call. = FALSE)\n }\n # keep track of unique lty and lwd (needed for group catch / escape hatch\n # later in draw_hline)\n ul_lwd = length(unique(lwd))\n ul_lty = length(unique(lty))\n ul_col = length(unique(col))\n return(list(type_info = list(ul_lty = ul_lty, ul_lwd = ul_lwd, ul_col = ul_col)))\n }\n draw_hline = function() {\n fun = function(\n ifacet, iby, data_facet, icol, ilty, ilwd,\n ngrps, nfacets, by_continuous, facet_by,\n type_info,\n ...\n ) {\n \n # flag for aesthetics by groups\n grp_aes = type_info[[\"ul_col\"]] == 1 || type_info[[\"ul_lty\"]] == ngrps || type_info[[\"ul_lwd\"]] == ngrps\n \n if (length(h) != 1) {\n if (!length(h) %in% c(ngrps, nfacets, ngrps*nfacets)) {\n msg = \"Length of 'h' must be 1, or equal to the number of facets or number of groups (or product thereof).\"\n stop(msg, call. = FALSE)\n }\n if (!facet_by && length(h) == nfacets) {\n h = h[ifacet]\n if (!grp_aes && type_info[[\"ul_col\"]]!=ngrps) {\n icol = 1\n } else if (by_continuous) {\n icol = 1\n }\n } else if (!by_continuous && length(h) == ngrps * nfacets) {\n h = h[ifacet * ngrps - c(ngrps - iby)]\n } else if (!by_continuous) {\n h = h[iby]\n }\n } else if (!grp_aes) {\n icol = 1\n }\n\n abline(h = h, col = icol, lty = ilty, lwd = ilwd)\n }\n return(fun)\n }\n out = list(\n draw = draw_hline(),\n data = data_hline,\n name = \"hline\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_vline.R", "#' @param v x-value(s) for vertical line(s). Numeric of length 1, or equal to\n#' the number of groups or number of facets (or the product thereof).\n#' @rdname type_abline\n#' @export\ntype_vline = function(v = 0) {\n assert_numeric(v)\n data_vline = function(datapoints, lwd, lty, col, ...) {\n if (nrow(datapoints) == 0) {\n msg = \"`type_vline() only works on existing plots with x and y data points.\"\n stop(msg, call. = FALSE)\n }\n # keep track of unique lty and lwd (needed for group catch / escape hatch\n # later in draw_hline)\n ul_lwd = length(unique(lwd))\n ul_lty = length(unique(lty))\n ul_col = length(unique(col))\n return(list(type_info = list(ul_lty = ul_lty, ul_lwd = ul_lwd, ul_col = ul_col)))\n }\n draw_vline = function() {\n fun = function(\n ifacet, iby, data_facet, icol, ilty, ilwd,\n ngrps, nfacets, by_continuous, facet_by,\n type_info,\n ...\n ) {\n\n # flag for aesthetics by groups\n grp_aes = type_info[[\"ul_col\"]] == 1 || type_info[[\"ul_lty\"]] == ngrps || type_info[[\"ul_lwd\"]] == ngrps\n \n if (length(v) != 1) {\n if (!length(v) %in% c(ngrps, nfacets, ngrps*nfacets)) {\n msg = \"Length of 'v' must be 1, or equal to the number of facets or number of groups (or product thereof).\"\n stop(msg, call. = FALSE)\n }\n if (!facet_by && length(v) == nfacets) {\n v = v[ifacet]\n if (!grp_aes && type_info[[\"ul_col\"]]!=ngrps) {\n icol = 1\n } else if (by_continuous) {\n icol = 1\n }\n } else if (!by_continuous && length(v) == ngrps * nfacets) {\n v = v[ifacet * ngrps - c(ngrps - iby)]\n } else if (!by_continuous) {\n v = v[iby]\n }\n } else if (!grp_aes) {\n icol = 1\n }\n \n abline(v = v, col = icol, lty = ilty, lwd = ilwd)\n }\n return(fun)\n }\n out = list(\n draw = draw_vline(),\n data = data_vline,\n name = \"vline\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/by_aesthetics.R", "by_col = function(ngrps = 1L, col = NULL, palette = NULL, gradient = NULL, ordered = NULL, alpha = NULL) {\n if (is.null(alpha)) alpha = 1\n if (is.null(ordered)) ordered = FALSE\n if (is.null(gradient)) gradient = FALSE\n assert_logical(ordered)\n assert_logical(gradient)\n if (gradient) {\n ngrps = 100L\n }\n \n # pal_qual = get_tpar(\"palette.qualitative\", default = NULL)\n pal_theme = get_tpar(\"palette.qualitative\", default = NULL)\n theme_flag = !is.null(pal_theme)\n\n # palette = substitute(palette, env = parent.env(environment()))\n\n # special \"by\" convenience keyword (will treat as NULL & handle grouping below)\n if (!anyNA(col) && !is.null(col) && length(col) == 1 && col == \"by\") col = NULL\n\n #\n ## Base case: If no color or palette provided, pass colors as a sequence of\n ## numbers (will inherit from / cycle over the user's default palette)\n \n if (is.null(col) && (is.null(palette) && !theme_flag)) {\n if (ngrps <= length(palette()) && !ordered) {\n col = palette()[seq_len(ngrps)]\n if (alpha) col = adjustcolor(col, alpha.f = alpha)\n } else {\n # fallback to restricted viridis palette\n col = colorRampPalette(\n hcl.colors(n = 100, palette = \"Viridis\", alpha = alpha)[(100 * 0.1 + 1):(100 * 0.9)],\n alpha = TRUE\n )(ngrps)\n }\n if (gradient || ordered) col = rev(col)\n return(col)\n }\n\n #\n ## Next simplest case: No palette, but color(s) provided directly. We do\n ## some simple sanity checks, apply alpha transparency and return as-is.\n\n if (is.atomic(col) && is.vector(col)) {\n if (length(col) == 1) {\n col = rep(col, ngrps)\n if (alpha) col = adjustcolor(col, alpha.f = alpha)\n return(col)\n } else if (length(col) < ngrps) {\n # if (!gradient) {\n # stop(sprintf(\"`col` must be of length 1, or greater than or equal to %s.\", ngrps), call. = FALSE)\n # } else {\n # # interpolate gradient colors\n # col = colorRampPalette(colors = col, alpha = TRUE)(ngrps)\n # }\n # if manual colours < ngrps, either (1) interpolate for gradient\n # colors, or (2) recycle for discrete colours\n if (gradient) {\n col = colorRampPalette(colors = col, alpha = TRUE)(ngrps)\n } else {\n ncolsstr = paste0(\"(\", length(col), \")\")\n ngrpsstr = paste0(\"(\", ngrps, \")\")\n warning(\n \"\\nFewer colours \", ncolsstr, \" provided than than there are groups \",\n ngrpsstr, \". Recycling to make up the shortfall.\"\n )\n col = rep(col, length.out = ngrps)\n }\n \n }\n if (gradient) {\n col = rev(col)\n } else if (!ordered && is.numeric(col)) {\n # col = palette()[col]\n if (ngrps <= length(palette())) {\n col = palette()[col]\n # if (alpha) col = adjustcolor(col, alpha.f = alpha)\n } else {\n col = hcl.colors(max(col), alpha = alpha)[col]\n }\n }\n if (anyNA(col) || is.character(col)) {\n if (alpha) col = adjustcolor(col, alpha.f = alpha)\n return(col)\n }\n }\n \n \n #\n ## Theme case: No palette provided, but fallback to tinytheme palette\n\n # we need to fix palette string, determine if in palette.pals() and then\n # determine no. of groups, before kicking over to sequential\n if (is.null(palette) && theme_flag) {\n if (length(pal_theme) == 1) {\n qual_match = match_pal(pal_theme, palette.pals())\n if (!is.na(qual_match)) {\n if (ngrps >= get_pal_lens(pal_theme) || ordered) {\n pal_theme = get_tpar(\"palette.sequential\", default = NULL)\n }\n # mostly a catch for x-gradient fills, e.g. type_ridge\n } else if (gradient && !is.na(match_pal(pal_theme, hcl.pals()))) {\n pal_theme = get_tpar(\"palette.sequential\", default = NULL)\n }\n }\n if (length(pal_theme) == 1) {\n palette_fun = gen_pal_fun(pal = pal_theme, gradient = gradient, alpha = alpha)\n args = list(n = ngrps, palette = pal_theme, alpha = alpha)\n }\n palette = pal_theme\n }\n \n if (is.null(palette)) {\n if (ngrps <= length(palette()) && !ordered && !gradient) {\n palette_fun = function(alpha) adjustcolor(palette(), alpha) # must be function to avoid arg ambiguity\n args = list(alpha = alpha)\n } else {\n if (ngrps <= 8 && !ordered) { # ngrps < 100 so we know gradient is FALSE too\n palette = \"R4\"\n palette_fun = palette.colors\n } else {\n palette = \"Viridis\"\n if (!gradient && !ordered) {\n palette_fun = hcl.colors\n } else {\n palette_fun_gradient = function(n, palette, from = 0.1, to = 0.9, alpha = 1) {\n colorRampPalette(\n hcl.colors(n = 100, palette = palette, alpha = alpha)[(100 * from + 1):(100 * to)],\n alpha = TRUE\n )(n)\n }\n palette_fun = palette_fun_gradient\n }\n }\n args = list(n = ngrps, palette = palette, alpha = alpha)\n }\n } else {\n if (is.character(palette)) {\n # special case: if vector of character strings, we assume that the user\n # must have passed a vector of colours (e.g., c(\"red\", \"blue\")) rather\n # than a known/named colour palette (e.g. \"Harmonic\")\n if (length(palette) > 1) {\n palette_fun = \"c\"\n if (!is.null(alpha)) palette = adjustcolor(palette, alpha.f = alpha)\n args = as.list(palette)\n if (length(args) < ngrps && length(args) != 1) {\n # if manual colours < ngrps, either (1) interpolate for gradient\n # colors, or (2) recycle for discrete colours\n if (gradient) {\n args = list(colorRampPalette(args, alpha = TRUE)(ngrps))\n } else {\n ncolsstr = paste0(\"(\", length(args), \")\")\n ngrpsstr = paste0(\"(\", ngrps, \")\")\n warning(\n \"\\nFewer colours \", ncolsstr, \" provided than than there are groups \",\n ngrpsstr, \". Recycling to make up the shortfall.\"\n )\n args = rep(args, length.out = ngrps)\n }\n }\n } else {\n palette_fun = gen_pal_fun(palette, gradient = gradient, alpha = alpha, n = ngrps)\n args = list(n = ngrps, palette = palette, alpha = alpha)\n }\n } else if (inherits(palette, c(\"call\", \"name\"))) {\n # catch for when using passes palette as named object (e.g,\n # pal26 = palette.colors(\"Alphabet\"))\n if (inherits(palette, \"name\") && is.character(eval(palette))) {\n args = as.list(eval(palette))\n palette_fun = \"c\"\n } else {\n args = as.list(palette)\n palette_fun = paste(args[[1]])\n args[[1]] = NULL\n }\n # catch for direct vector or list\n if (palette_fun %in% c(\"c\", \"list\")) {\n if (palette_fun == \"list\") palette_fun = \"c\"\n if (!is.null(alpha)) args = lapply(args, function(a) adjustcolor(a, alpha.f = alpha))\n if (length(args) < ngrps && length(args) != 1) {\n # if manual colours < ngrps, either (1) interpolate for gradient\n # colors, or (2) recycle for discrete colours\n if (gradient) {\n args = list(colorRampPalette(args, alpha = TRUE)(ngrps))\n } else {\n ncolsstr = paste0(\"(\", length(args), \")\")\n ngrpsstr = paste0(\"(\", ngrps, \")\")\n warning(\n \"\\nFewer colours \", ncolsstr, \" provided than than there are groups \",\n ngrpsstr, \". Recycling to make up the shortfall.\"\n )\n args = rep(args, length.out = ngrps)\n }\n }\n } else {\n args[[\"n\"]] = ngrps\n # remove unnamed arguments to prevent unintentional argument sliding\n if (any(names(args) == \"\")) args[[which(names(args) == \"\")]] = NULL\n }\n } else if (inherits(palette, \"function\")) {\n args = list()\n palette_fun = palette\n } else {\n stop(\n \"\\nInvalid palette argument. Must be a recognized keyword, or a \",\n \"palette-generating function with named arguments.\\n\"\n )\n }\n }\n\n cols = tryCatch(\n do.call(palette_fun, args),\n error = function(e) do.call(eval(palette), args) # catch for bespoke palette generating funcs\n )\n\n if (length(cols) > ngrps) cols = cols[1:ngrps]\n\n # For gradient and ordered colors, we'll run high to low\n if (gradient || ordered) cols = rev(cols)\n\n return(cols)\n}\n\n# Some utility functions for palette matching, etc.\n\nmatch_pal = function(pal, pals) {\n fx = function(x) tolower(gsub(\"[-, _, \\\\,, (, ), \\\\ , \\\\.]\", \"\", x))\n charmatch(fx(pal), fx(pals))\n}\n\nget_pal_lens = function(pal) {\n pal_lens = c(\n R3 = 8L, R4 = 8L, ggplot2 = 8L, `Okabe-Ito` = 9L, Accent = 8L,\n `Dark 2` = 8L, Paired = 12L, `Pastel 1` = 9L, `Pastel 2` = 8L, \n `Set 1` = 9L, `Set 2` = 8L, `Set 3` = 12L, `Tableau 10` = 10L, \n `Classic Tableau` = 10L, `Polychrome 36` = 36L, Alphabet = 26L\n )\n pal_lens[pal]\n}\n\n# take a character string, match to either palette.pals() pr hcl.pals(), and\n# generate the corresponding function factor with alpha transparency\ngen_pal_fun = function(pal, gradient = FALSE, alpha = NULL, n = NULL) {\n pal_match = match_pal(pal, palette.pals())\n if (!is.na(pal_match)) {\n if (pal_match < 1L) stop(\"'palette' is ambiguous\")\n pal_fun = palette.colors\n if (!is.null(n) && n >= get_pal_lens(pal_match)) {\n warning(\n \"\\nFewer colours \", get_pal_lens(pal_match), \" provided than than there are groups \",\n n, \". Recycling to make up the shortfall.\"\n )\n pal_fun = function(n, palette, alpha) palette.colors(n = n, palette = pal, alpha = alpha, recycle = TRUE)\n }\n if (gradient) {\n pal_fun = function(n, palette, alpha) colorRampPalette(palette.colors(palette = pal, alpha = alpha))(n)\n }\n } else {\n pal_match = match_pal(pal, hcl.pals())\n if (!is.na(pal_match)) {\n if (pal_match < 1L) stop(\"'palette' is ambiguous\")\n pal_fun = hcl.colors\n } else {\n stop(\n \"\\nPalette string not recogized. Must be a value produced by either\",\n \"`palette.pals()` or `hcl.pals()`.\\n\",\n call. = FALSE\n )\n }\n }\n return(pal_fun)\n}\n\n\nby_pch = function(ngrps, type, pch = NULL) {\n no_pch = FALSE\n if (identical(type, \"text\")) {\n pch <- rep(15, ngrps)\n } else if (!type %in% c(\"p\", \"b\", \"o\", \"pointrange\", \"errorbar\", \"boxplot\", \"qq\")) {\n no_pch = TRUE\n pch = NULL\n\n # special \"by\" convenience keyword\n } else if (!is.null(pch) && length(pch) == 1 && pch == \"by\") {\n no_pch = TRUE # skip checks below\n pch = 1:ngrps + par(\"pch\") - 1\n # correctly recycle if over max pch type\n pch_ceiling = 25 # see ?pch\n if (max(pch) > pch_ceiling) {\n pch_below = pch[pch <= pch_ceiling]\n pch_above = pch[pch > pch_ceiling]\n pch_above = rep_len(0:pch_ceiling, length(pch_above))\n pch = c(pch_below, pch_above)\n }\n\n # return NULL if not a valid point type\n } else if (is.null(pch)) {\n pch = par(\"pch\")\n }\n\n if (!no_pch) {\n if (!is.atomic(pch) || !is.vector(pch) || !(is.numeric(pch) || is.character(pch)) || (length(pch) != 1 && length(pch) != ngrps)) {\n # if (!is.atomic(pch) || !is.vector(pch) || !is.numeric(pch) || (length(pch) != 1 && length(pch) != ngrps)) {\n stop(sprintf(\"`pch` must be `NULL`, or a numeric or character vector of length 1 or %s.\", ngrps), call. = FALSE)\n }\n\n if (length(pch) == 1) {\n pch = rep(pch, ngrps)\n }\n }\n\n return(pch)\n}\n\n\nby_lty = function(ngrps, type, lty = NULL) {\n # We only care about line types, otherwise return NULL\n if (!type %in% c(\"l\", \"b\", \"o\", \"c\", \"h\", \"s\", \"S\", \"ribbon\", \"barplot\", \"boxplot\", \"rect\", \"segments\", \"qq\", \"abline\", \"hline\", \"vline\")) {\n out = NULL\n\n # special \"by\" convenience keyword\n } else if (!is.null(lty) && length(lty) == 1 && lty == \"by\") {\n lty_dict = c(\"solid\", \"dashed\", \"dotted\", \"dotdash\", \"longdash\", \"twodash\")\n par_lty = par(\"lty\")\n\n if (!par_lty %in% lty_dict) {\n warning(\n \"\\nBesoke lty specifications (i.e., using string combinations) are not\",\n \"currently supported alongside the lty='by' keyword argument.\",\n \"Defaulting to 1 and looping from there.\\n\"\n )\n par_lty = 1\n } else {\n par_lty = which(par_lty == lty_dict)\n }\n out = 1:ngrps + par_lty - 1\n # correctly recycle if over max pch type\n lty_ceiling = 6 # see ?pch\n if (max(out) > lty_ceiling) {\n lty_below = out[out <= lty_ceiling]\n lty_above = out[out > lty_ceiling]\n lty_above = rep_len(1:lty_ceiling, length(lty_above))\n out = c(lty_below, lty_above)\n }\n\n # NULL -> solid (or default) line\n } else if (is.null(lty)) {\n if (identical(type, \"boxplot\")) {\n out = NULL\n } else {\n out = rep(par(\"lty\"), ngrps)\n }\n\n # atomic vector: sanity check length\n } else if (is.atomic(lty) && is.vector(lty)) {\n if (length(lty) == 1) {\n out = rep(lty, ngrps)\n } else {\n if (length(lty) != ngrps) {\n stop(sprintf(\"`lty` must be `NULL` or a numeric vector of length 1 or %s.\", ngrps), call. = FALSE)\n }\n out = lty\n }\n }\n\n return(out)\n}\n\n\nby_lwd = function(ngrps, type, lwd = NULL) {\n lwd_base = par(\"lwd\")\n lwd_floor = lwd_base / min(5, max((ngrps - 1), 1))\n lwd_ceiling = lwd_base * min(5, ngrps)\n\n no_lwd = FALSE\n # special \"by\" convenience keyword\n if (!is.null(lwd) && length(lwd) == 1 && lwd == \"by\") {\n no_lwd = TRUE # skip checks below\n lwd = seq(lwd_floor, lwd_ceiling, length.out = ngrps)\n } else if (is.null(lwd)) {\n no_lwd = TRUE\n lwd = NULL\n }\n\n if (!no_lwd) {\n if (!is.atomic(lwd) || !is.vector(lwd) || !is.numeric(lwd) || (length(lwd) != 1 && length(lwd) != ngrps)) {\n stop(sprintf(\"`lwd` must be `NULL` or a numeric vector of length 1 or %s.\", ngrps), call. = FALSE)\n }\n if (length(lwd) == 1) {\n lwd = rep(lwd, ngrps)\n }\n }\n\n return(lwd)\n}\n\n\nby_bg = function(\n adjustcolor,\n alpha,\n bg,\n by,\n by_continuous,\n by_ordered,\n col,\n fill,\n ngrps,\n palette,\n ribbon.alpha,\n type) {\n if (is.null(bg) && !is.null(fill)) bg = fill\n if (!is.null(bg) && length(bg) == 1 && is.numeric(bg) && bg >= 0 && bg <= 1) {\n alpha = bg\n bg = \"by\"\n }\n if (!is.null(bg) && length(bg) == 1 && bg == \"by\") {\n bg = by_col(\n ngrps = ngrps,\n col = NULL,\n palette = palette,\n gradient = by_continuous,\n ordered = by_ordered,\n alpha = alpha\n )\n } else if (length(bg) != ngrps) {\n bg = rep(bg, ngrps)\n }\n if (type == \"ribbon\" || (type == \"boxplot\" && !is.null(by))) {\n if (!is.null(bg)) {\n bg = adjustcolor(bg, ribbon.alpha)\n } else if (!is.null(col)) {\n bg = adjustcolor(col, ribbon.alpha)\n }\n }\n\n return(bg)\n}\n"], ["/tinyplot/R/type_histogram.R", "#' Histogram plot type\n#' \n#' @md\n#' @description Type function for histogram plots. `type_hist` is an alias for\n#' `type_histogram`.\n#' @param breaks Passed to \\code{\\link[graphics]{hist}}. One of:\n#' - a vector giving the breakpoints between histogram cells,\n#' - a function to compute the vector of breakpoints,\n#' - a single number giving the number of cells for the histogram,\n#' - a character string naming an algorithm to compute the number of cells (see ‘Details’ of \\code{\\link[graphics]{hist}}),\n#' - a function to compute the number of cells.\n#' In the last three cases the number is a suggestion only; as the breakpoints\n#' will be set to pretty values, the number is limited to 1e6 (with a warning if\n#' it was larger). If breaks is a function, the x vector is supplied to it as\n#' the only argument (and the number of breaks is only limited by the amount of\n#' available memory).\n#' @param free.breaks Logical indicating whether the breakpoints should be\n#' computed separately for each group or facet? Default is `FALSE`, meaning\n#' that the breakpoints are computed from the full dataset; thus ensuring\n#' common bin widths across each group/facet. Can also use `free` as an\n#' acceptable argument alias. Ignored if there are no groups and/or facets.\n#' @param drop.zeros Logical indicating whether bins with zero counts should be\n#' dropped before plotting. Default is `TRUE`. Note that switching to `FALSE`\n#' may interfere with faceted plot behaviour if `facet.args = list(free)`,\n#' since the `x` variable is effectively recorded over the full range of the\n#' x-axis (even if it does not extend over this range for every group).\n#' @inheritParams graphics::hist\n#' @examples\n#' # \"histogram\"/\"hist\" type convenience string(s)\n#' tinyplot(Nile, type = \"histogram\")\n#' \n#' # Use `type_histogram()` to pass extra arguments for customization\n#' tinyplot(Nile, type = type_histogram(breaks = 30))\n#' tinyplot(Nile, type = type_histogram(breaks = 30, freq = FALSE))\n#' # etc.\n#' \n#' # Grouped histogram example\n#' tinyplot(\n#' ~Petal.Width | Species,\n#' type = \"histogram\",\n#' data = iris\n#' )\n#' \n#' # Faceted version\n#' tinyplot(\n#' ~Petal.Width, facet = ~Species,\n#' type = \"histogram\",\n#' data = iris\n#' )\n#' \n#' # For visualizing faceted histograms across varying scales, you may also wish\n#' # to impose free histogram breaks too (i.e., calculate breaks separately for\n#' # each group). Compare:\n#' \n#' # free facet scales + shared histogram breaks, versus...\n#' tinyplot(\n#' ~Petal.Width, facet = ~Species,\n#' facet.args = list(free = TRUE),\n#' type = type_histogram(),\n#' data = iris\n#' )\n#' # ... free facet scales + free histogram breaks\n#' tinyplot(\n#' ~Petal.Width, facet = ~Species,\n#' facet.args = list(free = TRUE),\n#' type = type_histogram(free = TRUE),\n#' data = iris\n#' )\n#' \n#' @export\ntype_histogram = function(breaks = \"Sturges\",\n freq = NULL, right = TRUE,\n free.breaks = FALSE, drop.zeros = TRUE) {\n out = list(\n data = data_histogram(breaks = breaks,\n free.breaks = free.breaks, drop.zeros = drop.zeros,\n freq = freq, right = right),\n draw = draw_rect(),\n name = \"histogram\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n#' @export\n#' @name type_hist\n#' @rdname type_histogram\ntype_hist = type_histogram\n\n\ndata_histogram = function(breaks = \"Sturges\",\n free.breaks = FALSE, drop.zeros = TRUE,\n freq = NULL, right = TRUE) {\n \n hbreaks = breaks\n hfree.breaks = free.breaks\n hdrop.zeros = drop.zeros\n hfreq = freq\n hright = right\n \n fun = function(by, facet, ylab, col, bg, ribbon.alpha, datapoints, .breaks = hbreaks, .freebreaks = hfree.breaks, .freq = hfreq, .right = hright, .drop.zeros = hdrop.zeros, ...) {\n \n hbreaks = ifelse(!sapply(.breaks, is.null), .breaks, \"Sturges\")\n \n if (is.null(by) && is.null(palette)) {\n if (is.null(col)) col = par(\"fg\")\n if (is.null(bg)) bg = \"lightgray\"\n } else {\n if (is.null(bg)) bg = ribbon.alpha\n }\n\n if (!.freebreaks) xbreaks = hist(datapoints$x, breaks = hbreaks, right = .right, plot = FALSE)$breaks\n datapoints = split(datapoints, list(datapoints$by, datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n \n datapoints = lapply(datapoints, function(k) {\n if (.freebreaks) xbreaks = breaks\n h = hist(k$x, breaks = xbreaks, right = .right, plot = FALSE)\n # zero count cases\n if (.drop.zeros) {\n nzidx = which(h$counts > 0)\n h$density = h$density[nzidx]\n h$counts = h$counts[nzidx]\n h$breaks = h$breaks[c(1, nzidx+1)]\n h$mids = h$mids[nzidx]\n }\n freq = if(!is.null(.freq)) .freq else is.null(.freq) && h$equidist\n out = data.frame(\n by = k$by[1], # already split\n facet = k$facet[1], # already split\n ymin = 0,\n ymax = if (freq) h$counts else h$density,\n xmin = h$breaks[-1],\n xmax = h$mids + (h$mids - h$breaks[-1]),\n freq = freq\n )\n return(out)\n })\n datapoints = do.call(rbind, datapoints)\n \n if (is.null(ylab)) {\n ylab = ifelse(datapoints$freq[1], \"Frequency\", \"Density\")\n }\n\n out = list(\n x = c(datapoints$xmin, datapoints$xmax), \n y = c(datapoints$ymin, datapoints$ymax),\n ymin = datapoints$ymin, \n ymax = datapoints$ymax, \n xmin = datapoints$xmin, \n xmax = datapoints$xmax, \n ylab = ylab, \n col = col, \n bg = bg, \n datapoints = datapoints,\n by = if (length(unique(datapoints$by)) == 1) by else datapoints$by, \n facet = if (length(unique(datapoints$facet)) == 1) facet else datapoints$facet\n )\n return(out)\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_summary.R", "#' Plot summary values of `y` at unique values of `x`\n#'\n#' @md\n#' @description\n#' Applies a summary function to `y` along unique values of `x`. For example,\n#' plot the mean `y` value for each `x` value. Internally,\n#' `type_summary()` applies a thin wrapper around \\code{\\link[stats]{ave}} and\n#' then passes the result to [`type_lines`] for drawing.\n#'\n#' @param fun summarizing function. Should be compatible with\n#' \\code{\\link[stats]{ave}}. Defaults to \\code{\\link[base]{mean}}.\n#' @param ... Additional arguments are passed to the `lines()` function,\n#' ex: `type=\"p\"`, `col=\"pink\"`.\n#' @seealso [`ave`] which performs the summarizing (averaging) behind the\n#' scenes.\n#' @examples\n#' # Plot the mean chick weight over time\n#' tinyplot(weight ~ Time, data = ChickWeight, type = \"summary\")\n#' \n#' # Note: \"mean\" is the default function, so these are also equivalent:\n#' # tinyplot(weight ~ Time, data = ChickWeight, type = type_summary())\n#' # tinyplot(weight ~ Time, data = ChickWeight, type = type_summary(mean))\n#' \n#' # Plot the median instead\n#' tinyplot(weight ~ Time, data = ChickWeight, type = type_summary(median))\n#' \n#' # Works with groups and/or facets too\n#' tinyplot(weight ~ Time | Diet, facet = \"by\", data = ChickWeight, type = \"summary\")\n#'\n#' # Custom/complex function example\n#' tinyplot(\n#' weight ~ Time | Diet, facet = \"by\", data = ChickWeight,\n#' type = type_summary(function(y) quantile(y, probs = 0.9)/max(y))\n#' )\n#' \n#' @importFrom stats ave\n#' @export\ntype_summary = function(fun = mean, ...) {\n assert_function(fun)\n lines_args = list(...)\n data_summary = function(fun) {\n funky = function(datapoints, ...) {\n datapoints = split(datapoints, list(datapoints$facet, datapoints$by), drop = TRUE)\n datapoints = lapply(datapoints, function(dat) {\n newy = ave(dat$y, dat$x, FUN = fun)\n dat$y = newy\n dat = dat[order(dat$x), ]\n return(dat)\n })\n datapoints = do.call(rbind, datapoints)\n out = list(datapoints = datapoints)\n return(out)\n }\n return(funky)\n }\n out = list(\n draw = draw_lines(...),\n data = data_summary(fun = fun),\n name = \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_loess.R", "#' Local polynomial regression plot type\n#' \n#' @description Type function for plotting a LOESS (LOcal regrESSion) fit.\n#' Arguments are passed to \\code{\\link[stats]{loess}}.\n#' \n#' @inheritParams stats::loess\n#' @param se logical. If `TRUE` (the default), confidence intervals are drawn.\n#' @param level the confidence level required if `se = TRUE`. Default is 0.95.\n#' @importFrom stats loess loess.control predict\n#' @examples\n#' # \"loess\" type convenience string\n#' tinyplot(dist ~ speed, data = cars, type = \"loess\")\n#' \n#' # Use `type_loess()` to pass extra arguments for customization\n#' tinyplot(dist ~ speed, data = cars, type = type_loess(span = 0.5, degree = 1))\n#' @export\ntype_loess = function(\n span = 0.75,\n degree = 2,\n family = \"gaussian\",\n control = loess.control(),\n se = TRUE,\n level = 0.95\n ) {\n out = list(\n draw = draw_ribbon(),\n data = data_loess(span = span, degree = degree, family = family, control = control, se = se, level = level),\n name = if (isTRUE(se)) \"ribbon\" else \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_loess = function(span, degree, family, control, se, level, ...) {\n fun = function(datapoints, ...) {\n datapoints = split(datapoints, list(datapoints$facet, datapoints$by))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n datapoints = lapply(datapoints, function(dat) {\n fit = loess(y ~ x, data = dat, span = span, degree = degree, family = family, control = control)\n if (se == TRUE) {\n p = predict(fit, newdata = dat, se = TRUE)\n p = ci(p$fit, p$se.fit, conf.level = level, p$df)\n dat$y = p$estimate\n dat$ymax = p$conf.high\n dat$ymin = p$conf.low\n } else {\n dat$y = predict(fit, dat)\n }\n dat\n })\n datapoints = do.call(rbind, datapoints)\n datapoints = datapoints[order(datapoints$facet, datapoints$by, datapoints$x), ]\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_jitter.R", "#' Jittered points plot type\n#'\n#' @description Type function for plotting jittered points.\n#' Arguments are passed to \\code{\\link[base]{jitter}}.\n#'\n#' @inheritParams base::jitter\n#' @inherit base::jitter details\n#' @examples\n#' # \"jitter\" type convenience string\n#' tinyplot(Sepal.Length ~ Species, data = iris, type = \"jitter\")\n#' \n#' # Use `type_jitter()` to pass extra arguments for customization\n#' tinyplot(Sepal.Length ~ Species, data = iris, type = type_jitter(factor = 0.5))\n#' @export\ntype_jitter = function(factor = 1, amount = NULL) {\n out = list(\n draw = draw_points(),\n data = data_jitter(factor = factor, amount = amount),\n name = \"p\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_jitter = function(factor, amount) {\n fun = function(datapoints, ...) {\n x = datapoints$x\n y = datapoints$y\n if (is.factor(x)) {\n xlvls = levels(x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n x = as.integer(x)\n } else {\n xlabs = NULL\n }\n if (is.factor(y)) {\n ylvls = levels(y)\n ylabs = seq_along(ylvls)\n names(ylabs) = ylvls\n y = as.integer(y)\n } else {\n ylabs = NULL\n }\n x = jitter(x, factor = factor, amount = amount)\n y = jitter(y, factor = factor, amount = amount)\n\n datapoints$x = x\n datapoints$y = y\n\n out = list(\n datapoints = datapoints,\n x = x,\n y = y,\n xlabs = xlabs,\n ylabs = ylabs\n )\n return(out)\n }\n}\n\n"], ["/tinyplot/R/type_violin.R", "#' Violin plot type\n#' \n#' @md\n#' @description Type function for violin plots, which are an alternative to box\n#' plots for visualizing continuous distributions (by group) in the form of\n#' mirrored densities.\n#' @inheritParams type_density\n#' @param trim logical indicating whether the violins should be trimmed to the\n#' range of the data. Default is `FALSE`.\n#' @param width numeric (ideally in the range `[0, 1]`, although this isn't\n#' enforced) giving the normalized width of the individual violins.\n#' @inherit stats::density details\n#' @details See [`type_density`] for more details and considerations related to\n#' bandwidth selection and kernel types.\n#' \n#' @examples\n#' # \"violin\" type convenience string\n#' tinyplot(count ~ spray, data = InsectSprays, type = \"violin\")\n#' \n#' # aside: to match the defaults of `ggplot2::geom_violin()`, use `trim = TRUE`\n#' # and `joint.bw = FALSE`\n#' tinyplot(count ~ spray, data = InsectSprays, type = \"violin\",\n#' trim = TRUE, joint.bw = FALSE)\n#' \n#' # use flip = TRUE to reorient the axes\n#' tinyplot(count ~ spray, data = InsectSprays, type = \"violin\", flip = TRUE)\n#' \n#' # for flipped plots with long group labels, it's better to use a theme for\n#' # dynamic plot resizing\n#' tinytheme(\"clean\")\n#' tinyplot(weight ~ feed, data = chickwts, type = \"violin\", flip = TRUE)\n#' \n#' # you can group by the x var to add colour (here with the original orientation)\n#' tinyplot(weight ~ feed | feed, data = chickwts, type = \"violin\", legend = FALSE)\n#' \n#' # dodged grouped violin plot example (different dataset)\n#' tinyplot(len ~ dose | supp, data = ToothGrowth, type = \"violin\", fill = 0.2)\n#' \n#' # note: above we relied on `...` argument passing alongside the \"violin\"\n#' # type convenience string. But this won't work for `width`, since it will\n#' # clash with the top-level `tinyplot(..., width = )` arg. To ensure\n#' # correct arg passing, it's safer to use the formal `type_violin()` option.\n#' tinyplot(len ~ dose | supp, data = ToothGrowth, fill = 0.2,\n#' type = type_violin(width = 0.8))\n#' \n#' # reset theme\n#' tinytheme()\n#' \n#' @importFrom stats density weighted.mean\n#' @importFrom stats bw.SJ bw.bcv bw.nrd bw.nrd0 bw.ucv \n#' @export\ntype_violin = function(\n bw = \"nrd0\",\n joint.bw = c(\"mean\", \"full\", \"none\"),\n adjust = 1,\n kernel = c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"),\n n = 512,\n # more args from density here?\n trim = FALSE,\n width = 0.9\n ) {\n kernel = match.arg(kernel, c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"))\n if (is.logical(joint.bw)) {\n joint.bw = ifelse(joint.bw, \"mean\", \"none\")\n }\n joint.bw = match.arg(joint.bw, c(\"mean\", \"full\", \"none\"))\n out = list(\n data = data_violin(bw = bw, adjust = adjust, kernel = kernel, n = n,\n joint.bw = joint.bw, trim = trim, width = width),\n # draw = NULL,\n # name = \"polygon\"\n draw = draw_polygon(density = NULL),\n name = \"violin\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\ndata_violin = function(bw = \"nrd0\", adjust = 1, kernel = \"gaussian\", n = 512,\n joint.bw = \"none\", trim = FALSE, width = 0.9) {\n fun = function(datapoints, by, facet, ylab, col, bg, palette, log, null_by, null_facet, ...) {\n \n # Handle ordering based on by and facet variables\n ngrps = if (null_by) 1 else length(unique(datapoints$by))\n nfacets = if (null_facet) 1 else length(unique(datapoints$facet))\n \n # catch for special cases\n x_by = y_by = facet_by = FALSE\n if (!null_by) {\n x_by = identical(datapoints$x, datapoints$by)\n y_by = identical(datapoints$y, datapoints$by)\n if (!null_facet) facet_by = identical(datapoints$facet, datapoints$by)\n }\n \n # FIXME (once we add support for gradient fill to draw_polygon)\n if (y_by) {\n warning(\"\\n`y` == `by` is not currently supported for `type_violin`. We hope to support this in a future release, but for now `y` grouping will be turned off automatically.\\n\")\n by = NULL\n datapoints$by = \"\"\n ngrps = 1\n null_by = TRUE\n }\n \n # Convert x to factor if it's not already\n datapoints$x = as.factor(datapoints$x)\n if (x_by) datapoints$by = datapoints$x\n\n # Handle factor levels and maintain order\n xlvls = levels(datapoints$x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n # xlabs = levels(datapoints$x)\n datapoints$x = as.integer(datapoints$x)\n\n if (null_by && null_facet) {\n xord = order(datapoints$x)\n } else if (null_facet) {\n xord = order(datapoints$by, datapoints$x)\n } else if (null_by) {\n xord = order(datapoints$facet, datapoints$x)\n } else {\n xord = order(datapoints$by, datapoints$facet, datapoints$x)\n }\n\n if (length(unique(datapoints[[\"by\"]])) == 1 && is.null(palette)) {\n if (is.null(col)) col = par(\"fg\")\n if (is.null(bg)) bg = \"lightgray\"\n } else if (is.null(bg)) {\n bg = \"by\"\n }\n\n # Reorder x, y, ymin, and ymax based on the order determined\n datapoints = datapoints[xord,]\n\n \n datapoints = split(datapoints, list(datapoints$x, datapoints$by, datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n \n if (joint.bw == \"none\" || is.numeric(bw)) {\n dens_bw = bw\n } else {\n if (joint.bw == \"mean\") {\n # Use weighted mean of subgroup bandwidths\n bws = sapply(datapoints, function(dat) bw_fun(kernel = bw, dat$y))\n ws = sapply(datapoints, nrow)\n dens_bw = weighted.mean(bws, ws)\n } else if (joint.bw == \"full\") {\n dens_bw = bw_fun(kernel = bw, unlist(sapply(datapoints, `[[`, \"x\")))\n }\n }\n \n datapoints = lapply(seq_along(datapoints), function(d) {\n dat = datapoints[[d]]\n if (trim) {\n yrng = range(dat$y)\n dens = density(dat$y, bw = dens_bw, kernel = kernel, n = n, from = yrng[1], to = yrng[2])\n } else {\n dens = density(dat$y, bw = dens_bw, kernel = kernel, n = n)\n }\n \n x = dens$y\n y = dens$x\n \n \n if (log %in% c(\"y\", \"xy\")) {\n if (x[1] <= 0) {\n warning(\"\\nNon-positive density values have been trimmed as part of the logarthmic transformation.\\n\")\n xidx = x > 0\n x = x[xidx]\n y = y[xidx]\n } \n }\n \n x = c(x, rev(-x))\n y = c(y, rev(y))\n \n xwidth = xwidth_orig = width\n # dodge groups (if any)\n if ((ngrps > 1) && isFALSE(x_by) && isFALSE(facet_by)) {\n xwidth = xwidth_orig / ngrps - 0.01\n x = rescale_num(x, to = c(0, xwidth))\n x = x + as.numeric(sub(\"^([0-9]+)\\\\..*\", \"\\\\1\", names(datapoints)[d])) - xwidth/2\n x = x + seq(-((xwidth_orig - xwidth) / 2), ((xwidth_orig - xwidth) / 2), length.out = ngrps)[dat$by[1]]\n } else if (nfacets > 1) {\n x = rescale_num(x, to = c(0, xwidth))\n x = x + as.numeric(sub(\"^([0-9]+)\\\\..*\", \"\\\\1\", names(datapoints)[d])) - xwidth/2\n } else {\n x = rescale_num(x, to = c(0, xwidth))\n x = x + d - xwidth/2\n }\n \n x = c(x, NA)\n y = c(y, NA)\n \n out = data.frame(\n by = dat$by[1], # already split\n facet = dat$facet[1], # already split\n y = y,\n x = x\n )\n return(out)\n })\n datapoints = do.call(rbind, datapoints)\n datapoints = datapoints[1:(nrow(datapoints)-1), ]\n \n out = list(\n datapoints = datapoints,\n by = if (length(unique(datapoints$by)) == 1) by else datapoints$by, \n facet = if (length(unique(datapoints$facet)) == 1) facet else datapoints$facet,\n ylab = ylab,\n xlabs = xlabs,\n col = col,\n bg = bg\n )\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/tpar.R", "#' @title Set or query graphical parameters\n#'\n#' @description Extends \\code{\\link[graphics]{par}}, serving as a (near) drop-in\n#' replacement for setting or querying graphical parameters. The key\n#' differences is that, beyond supporting the standard group of R graphical\n#' parameters in \\code{\\link[graphics]{par}}, `tpar` also supports additional\n#' graphical parameters that are provided by `tinyplot`. Similar to\n#' \\code{\\link[graphics]{par}}, parameters are set by passing appropriate\n#' `key = value` argument pairs, and multiple parameters can be set or queried\n#' at the same time.\n#'\n#' @param ... arguments of the form `key = value`. This includes all of the\n#' parameters typically supported by \\code{\\link[graphics]{par}}, as well as\n#' the `tinyplot`-specific ones described in the 'Graphical Parameters'\n#' section below.\n#' @param hook Logical. If `TRUE`, base graphical parameters persist across \n#' plots via a hook applied before each new plot (see `?setHook`).\n#'\n#' @md\n#' @details The `tinyplot`-specific parameters are saved in an internal\n#' environment called `.tpar` for performance and safety reasons. However,\n#' they can also be set at package load time via \\code{\\link[base]{options}},\n#' which may prove convenient for users that want to enable different default\n#' behaviour at startup (e.g., through an `.Rprofile` file). These options all\n#' take a `tinyplot_*` prefix, e.g.\n#' `options(tinyplot_grid = TRUE, tinyplot_facet.bg = \"grey90\")`.\n#'\n#' For their part, any \"base\" graphical parameters are caught dynamically and\n#' passed on to \\code{\\link[graphics]{par}} as appropriate. Technically, only\n#' parameters that satisfy `par(..., no.readonly = TRUE)` are evaluated.\n#'\n#' However, note the important distinction: `tpar` only evaluates parameters\n#' from \\code{\\link[graphics]{par}} if they are passed _explicitly_ by the\n#' user. This means that `tpar` should not be used to capture the (invisible)\n#' state of a user's entire set of graphics parameters, i.e. `tpar()` !=\n#' `par()`. If you want to capture the _all_ existing graphics settings, then\n#' you should rather use `par()` instead.\n#'\n#' @returns When parameters are set, their previous values are returned in an\n#' invisible named list. Such a list can be passed as an argument to `tpar` to\n#' restore the parameter values.\n#'\n#' When just one parameter is queried, the value of that parameter is returned\n#' as (atomic) vector. When two or more parameters are queried, their values\n#' are returned in a list, with the list names giving the parameters.\n#'\n#' Note the inconsistency: setting one parameter returns a list, but querying\n#' one parameter returns a vector.\n#'\n#' @section Additional Graphical Parameters:\n#'\n#' * `adj.xlab`: Numeric value between 0 and 1 controlling the alignment of the x-axis label.\n#' * `adj.ylab`: Numeric value between 0 and 1 controlling the alignment of the y-axis label.\n#' * `cairo`: Logical indicating whether \\code{\\link[grDevices]{cairo_pdf}} should be used when writing plots to PDF. If `FALSE`, then \\code{\\link[grDevices]{pdf}} will be used instead, with implications for embedding (non-standard) fonts. Only used if `tinyplot(..., file = \".pdf\")` is called. Defaults to the value of `capabilities(\"cairo\")`.\n#' * `dynmar`: Logical indicating whether `tinyplot` should attempt dynamic adjustment of margins to reduce whitespace and/or account for spacing of text elements (e.g., long horizontal y-axis labels). Note that this parameter is tightly coupled to internal `tinythemes()` logic and should _not_ be adjusted manually unless you really know what you are doing or don't mind risking unintended consequences to your plot.\n#' * `facet.bg`: Character or integer specifying the facet background colour. If an integer, will correspond to the user's default colour palette (see `palette`). Passed to `rect`. Defaults to `NULL` (none).\n#' * `facet.border`: Character or integer specifying the facet border colour. If an integer, will correspond to the user's default colour palette (see `palette`). Passed to `rect`. Defaults to `NA` (none).\n#' * `facet.cex`: Expansion factor for facet titles. Defaults to `1`.\n#' * `facet.col`: Character or integer specifying the facet text colour. If an integer, will correspond to the user's default global colour palette (see `palette`). Defaults to `NULL`, which is equivalent to \"black\".\n#' * `facet.font`: An integer corresponding to the desired font face for facet titles. For most font families and graphics devices, one of four possible values: `1` (regular), `2` (bold), `3` (italic), or `4` (bold italic). Defaults to `NULL`, which is equivalent to `1` (i.e., regular).\n#' * `file.height`: Numeric specifying the height (in inches) of any plot that is written to disk using the `tinyplot(..., file = X)` argument. Defaults to `7`.\n#' * `file.res`: Numeric specifying the resolution (in dots per square inch) of any plot that is written to disk in bitmap format (i.e., PNG or JPEG) using the `tinyplot(..., file = X)` argument. Defaults to `300`.\n#' * `file.width`: Numeric specifying the width (in inches) of any plot that is written to disk using the `tinyplot(..., file = X)` argument. Defaults to `7`.\n#' * `fmar`: A numeric vector of form `c(b,l,t,r)` for controlling the (base) margin padding, in terms of lines, between the individual facets in a faceted plot. Defaults to `c(1,1,1,1)`. If more than three facets are detected, the `fmar` parameter is scaled by 0.75 to reduce excess whitespace. For 2x2 plots, the padding better matches the `cex` expansion logic of base graphics.\n#' * `grid.col`: Character or (integer) numeric that specifies the color of the panel grid lines. Defaults to `\"lightgray\"`.\n#' * `grid.lty`: Character or (integer) numeric that specifies the line type of the panel grid lines. Defaults to `\"dotted\"`.\n#' * `grid.lwd`: Non-negative numeric giving the line width of the panel grid lines. Defaults to `1`.\n#' * `grid`: Logical indicating whether a background panel grid should be added to plots automatically. Defaults to `NULL`, which is equivalent to `FALSE`.\n#' * `lmar`: A numeric vector of form `c(inner, outer)` that gives the margin padding, in terms of lines, around the automatic `tinyplot` legend. Defaults to `c(1.0, 0.1)`. The inner margin is the gap between the legend and the plot region, and the outer margin is the gap between the legend and the edge of the graphics device.\n#' * `palette.qualitative`: Palette for qualitative colors. See the `palette` argument in `?tinyplot`.\n#' * `palette.sequential`: Palette for sequential colors. See the `palette` argument in `?tinyplot`.\n#' * `ribbon.alpha`: Numeric factor in the range `[0,1]` for modifying the opacity alpha of \"ribbon\" and \"area\" type plots. Default value is `0.2`.\n#'\n#' @importFrom graphics par\n#' @importFrom utils modifyList\n#' \n#' @seealso [`graphics::par`] which `tpar` builds on top of. [`get_saved_par`]\n#' is a convenience function for retrieving graphical parameters at different\n#' stages of a `tinyplot` call (and used for internal accounting purposes).\n#' [`tinytheme`] allows users to easily set a group of graphics parameters\n#' in a single function call, according to a variety of predefined themes.\n#' \n#' @examples\n#' # Return a list of existing base and tinyplot graphic params\n#' tpar(\"las\", \"pch\", \"facet.bg\", \"facet.cex\", \"grid\")\n#'\n#' # Simple facet plot with these default values\n#' tinyplot(mpg ~ wt, data = mtcars, facet = ~am)\n#'\n#' # Set params to something new. Similar to graphics::par(), note that we save\n#' # the existing values at the same time by assigning to an object.\n#' op = tpar(\n#' las = 1,\n#' pch = 2,\n#' facet.bg = \"grey90\",\n#' facet.cex = 2,\n#' grid = TRUE\n#' )\n#'\n#' # Re-plot with these new params\n#' tinyplot(mpg ~ wt, data = mtcars, facet = ~am)\n#'\n#' # Reset back to original values\n#' tpar(op)\n#'\n#' # Important: tpar() only evalutes parameters that have been passed explicitly\n#' # by the user. So it it should not be used to query and set (restore)\n#' # parameters that weren't explicitly requested, i.e. tpar() != par().\n#'\n#' # Note: The tinyplot-specific parameters can also be be set via `options`\n#' # with a `tinyplot_*` prefix, which can be convenient for enabling\n#' # different default behaviour at startup time (e.g., via an .Rprofile\n#' # file). Example:\n#' # options(tinyplot_grid = TRUE, tinyplot_facet.bg = \"grey90\")\n#'\n#' @export\ntpar = function(..., hook = FALSE) {\n\n opts = list(...)\n if (length(opts) == 1 && is.null(names(opts))) {\n if (inherits(opts[[1]], \"list\") && !is.null(names(opts[[1]]))) {\n opts = opts[[1]]\n }\n }\n\n ###### Assign parameters\n\n # assign tinyplot-specific arguments with known names to .tpar\n assign_tpar(opts)\n\n # return informative error messages if the input is invalid\n assert_tpar(.tpar)\n\n # if tpar(...) includes arguments that are not known to be tinyplot-specific,\n # we set a hook to set them using par() when the graphic device is started\n nam = names(opts)\n if (!is.null(nam)) {\n base_par = setdiff(nam, known_tpar)\n base_par = opts[base_par]\n if (length(base_par) > 0) {\n if (isTRUE(hook)) {\n # append new hook to existing ones\n new_hooks = list(\"before.plot.new\" = function() par(base_par))\n set_hooks(new_hooks, action = \"append\")\n # save new hook to tinyplot environment for later removal\n old_hooks = get_environment_variable(\".tpar_hooks\")\n set_environment_variable(\".tpar_hooks\", c(old_hooks, new_hooks))\n } else {\n par_names = names(par(no.readonly = TRUE))\n base_par = base_par[names(base_par) %in% par_names]\n base_par_old = par(base_par)\n par(base_par)\n }\n }\n }\n\n\n ###### Retrieve parameters\n\n # User didn't assign any new values, but may have requested explicit (print\n # of) some existing value(s)\n tpar_old = as.list(.tpar)\n if (is.null(nam)) {\n known_par = names(par(no.readonly = TRUE))\n if (!is.null(nam)) {\n used_par = intersect(nam, known_par)\n } else {\n used_par = intersect(opts, known_par)\n }\n if (length(used_par)) {\n if (!is.null(nam)) used_par = opts[used_par]\n used_par_old = par(used_par)\n tpar_old = modifyList(as.list(.tpar), used_par_old, keep.null = TRUE)\n }\n if (!is.null(opts) && length(opts) != 0) {\n # specific values requested\n opts = Filter(is.character, opts)\n ret = (`names<-`(lapply(opts, function(x) .tpar[[x]]), opts))\n if (length(used_par)) {\n ret_par = par(used_par)\n ret = modifyList(ret, ret_par, keep.null = TRUE)\n }\n if (length(ret) == 1) ret = ret[[1]]\n return(ret)\n } else {\n # no specific request; return all existing values invisibly\n return(invisible(tpar_old))\n }\n # assign new values, but still return old values for saving existing settings\n # a la `oldpar = par(param = new_value)`\n } else {\n `names<-`(lapply(nam, function(x) .tpar[[x]]), nam)\n if (length(base_par) > 0 && isFALSE(hook)) tpar_old = modifyList(tpar_old, base_par_old, keep.null = TRUE)\n return(invisible(tpar_old))\n }\n}\n\n\n# Two levels of priority: .tpar[[\"name\"]] -> par(\"name\")\nget_tpar = function(opts, default = NULL) {\n # parameter priority\n # .tpar[[\"name\"]] -> par(\"name\")\n for (o in opts) {\n tp = .tpar[[o]]\n if (!is.null(tp)) {\n return(tp)\n } else {\n p = suppressWarnings(par(o))\n if (!is.null(p)) {\n return(p)\n }\n }\n\n }\n return(default)\n}\n\n\nknown_tpar = c(\n \"adj.main\",\n \"adj.sub\",\n \"adj.xlab\",\n \"adj.ylab\",\n \"cex.xlab\",\n \"cex.ylab\",\n \"col.xaxs\",\n \"col.yaxs\",\n \"cairo\",\n \"dynmar\",\n \"facet.bg\",\n \"facet.border\",\n \"facet.cex\",\n \"facet.col\",\n \"facet.font\",\n \"file.height\",\n \"file.res\",\n \"file.width\",\n \"fmar\",\n \"grid\",\n \"grid.bg\",\n \"grid.col\",\n \"grid.lty\",\n \"grid.lwd\",\n \"lmar\",\n \"lty.xaxs\",\n \"lty.yaxs\",\n \"lwd.xaxs\",\n \"lwd.yaxs\",\n \"lwd.axis\",\n \"pch\",\n \"palette.qualitative\",\n \"palette.sequential\",\n \"ribbon.alpha\",\n \"side.sub\",\n \"tinytheme\",\n \"xaxt\",\n \"yaxt\"\n)\n\n\nassign_tpar = function(opts) {\n for (n in intersect(names(opts), known_tpar)) {\n .tpar[[n]] = opts[[n]]\n }\n}\n\n\nassert_tpar = function(.tpar) {\n assert_numeric(.tpar[[\"adj.main\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"adj.main\")\n assert_numeric(.tpar[[\"adj.sub\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"adj.sub\")\n assert_numeric(.tpar[[\"adj.xlab\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"adj.xlab\")\n assert_numeric(.tpar[[\"adj.ylab\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"adj.ylab\")\n assert_flag(.tpar[[\"cairo\"]], name = \"cairo\")\n assert_flag(.tpar[[\"dynmar\"]], null.ok = FALSE, name = \"dynmar\")\n assert_numeric(.tpar[[\"lmar\"]], len = 2, null.ok = TRUE, name = \"lmar\")\n assert_numeric(.tpar[[\"ribbon.alpha\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"ribbon.alpha\")\n assert_numeric(.tpar[[\"grid.lwd\"]], len = 1, lower = 0, null.ok = TRUE, name = \"grid.lwd\")\n assert_flag(.tpar[[\"grid\"]], null.ok = TRUE, name = \"grid\")\n assert_numeric(.tpar[[\"file.res\"]], len = 1, lower = 0, null.ok = TRUE, name = \"file.res\")\n assert_numeric(.tpar[[\"file.height\"]], len = 1, lower = 0, null.ok = TRUE, name = \"file.height\")\n assert_numeric(.tpar[[\"file.width\"]], len = 1, lower = 0, null.ok = TRUE, name = \"file.width\")\n assert_numeric(.tpar[[\"facet.font\"]], len = 1, null.ok = TRUE, name = \"facet.font\")\n assert_numeric(.tpar[[\"facet.cex\"]], len = 1, null.ok = TRUE, name = \"facet.cex\")\n assert_numeric(.tpar[[\"side.sub\"]], len = 1, null.ok = TRUE, name = \"side.sub\")\n assert_string(.tpar[[\"grid.bg\"]], null.ok = TRUE, name = \"grid.bg\")\n assert_numeric(.tpar[[\"fmar\"]], len = 4, null.ok = TRUE, name = \"fmar\")\n\n facet.col = .tpar[[\"facet.col\"]]\n if (!is.null(facet.col)) {\n if (!is.null(facet.col) && !is.numeric(facet.col) && !is.character(facet.col)) {\n stop(\"facet.col needs to be NULL, or a numeric or character\", call. = FALSE)\n }\n assert_true(length(facet.col) == 1, name = \"length(facet.col)==1\")\n }\n\n facet.bg = .tpar$facet.bg\n if (!is.null(facet.bg)) {\n if (!is.numeric(facet.bg) && !is.character(facet.bg)) {\n stop(\"facet.bg needs to be NULL, or a numeric or character\", call. = FALSE)\n }\n assert_true(length(facet.bg) == 1, name = \"length(facet.bg)==1\")\n }\n\n facet.border = .tpar$facet.border\n if (!is.null(facet.border)) {\n if (!is.numeric(facet.border) && !is.character(facet.border) && !is.na(facet.border)) {\n stop(\"facet.border needs to be NULL, or a numeric, character, or NA\", call. = FALSE)\n }\n assert_true(length(facet.border) == 1, name = \"length(facet.border)==1\")\n }\n}\n\n\ninit_tpar = function(rm_hook = FALSE) {\n rm(list = names(.tpar), envir = .tpar)\n\n if (isTRUE(rm_hook)) {\n old_hooks = get_environment_variable(\".tpar_hooks\")\n if (length(old_hooks) > 0) {\n remove_hooks(old_hooks)\n set_environment_variable(\".tpar_hooks\", NULL)\n }\n }\n\n .tpar$cairo = if (is.null(getOption(\"tinyplot_cairo\"))) capabilities(\"cairo\") else as.logical(getOption(\"tinyplot_cairo\"))\n \n \n .tpar$dynmar = if (is.null(getOption(\"tinyplot_dynmar\"))) FALSE else as.logical(getOption(\"tinyplot_dynmar\"))\n \n # Figure output options if written to file\n .tpar$file.width = if (is.null(getOption(\"tinyplot_file.width\"))) 7 else as.numeric(getOption(\"tinyplot_file.width\"))\n .tpar$file.height = if (is.null(getOption(\"tinyplot_file.height\"))) 7 else as.numeric(getOption(\"tinyplot_file.height\"))\n .tpar$file.res = if (is.null(getOption(\"tinyplot_file.res\"))) 300 else as.numeric(getOption(\"tinyplot_file.res\"))\n\n # Facet margin, i.e. gap between the individual facet windows\n .tpar$fmar = if (is.null(getOption(\"tinyplot_fmar\"))) c(1, 1, 1, 1) else as.numeric(getOption(\"tinyplot_fmar\"))\n\n # Other facet options\n .tpar$facet.cex = if (is.null(getOption(\"tinyplot_facet.cex\"))) 1 else as.numeric(getOption(\"tinyplot_facet.cex\"))\n .tpar$facet.font = if (is.null(getOption(\"tinyplot_facet.font\"))) NULL else as.numeric(getOption(\"tinyplot_facet.font\"))\n .tpar$facet.col = if (is.null(getOption(\"tinyplot_facet.col\"))) NULL else getOption(\"tinyplot_facet.col\")\n .tpar$facet.bg = if (is.null(getOption(\"tinyplot_facet.bg\"))) NULL else getOption(\"tinyplot_facet.bg\")\n .tpar$facet.border = if (is.null(getOption(\"tinyplot_facet.border\"))) NA else getOption(\"tinyplot_facet.border\")\n\n # Plot grid\n .tpar$grid = if (is.null(getOption(\"tinyplot_grid\"))) FALSE else as.logical(getOption(\"tinyplot_grid\"))\n .tpar$grid.col = if (is.null(getOption(\"tinyplot_grid.col\"))) \"lightgray\" else getOption(\"tinyplot_grid.col\")\n .tpar$grid.lty = if (is.null(getOption(\"tinyplot_grid.lty\"))) \"dotted\" else getOption(\"tinyplot_grid.lty\")\n .tpar$grid.lwd = if (is.null(getOption(\"tinyplot_grid.lwd\"))) 1 else as.numeric(getOption(\"tinyplot_grid.lwd\"))\n\n # Legend margin, i.e. gap between the legend and the plot elements\n .tpar$lmar = if (is.null(getOption(\"tinyplot_lmar\"))) c(1.0, 0.1) else as.numeric(getOption(\"tinyplot_lmar\"))\n\n # Alpha fill (transparency) default for ribbon and area plots\n .tpar$ribbon.alpha = if (is.null(getOption(\"tinyplot_ribbon.alpha\"))) 0.2 else as.numeric(getOption(\"tinyplot_ribbon.alpha\"))\n}\n"], ["/tinyplot/R/tinyAxis.R", "#' @title Generic function for adding an axis to a (tiny)plot\n#' \n#' @description Internal function used for adding an axis to a [`tinyplot`]\n#' call.\n#' @details `tinyAxis` provides a thin(ish) wrapper around\n#' \\code{\\link[graphics]{Axis}}, but with enhanced flexibility to (i) match\n#' parameter combinations based on the axis type and plotting theme, (ii)\n#' provide better support for date-time variables, and (iii) enable convenient\n#' formatting of axis tick labels.\n#' @inheritParams graphics::Axis\n#' @param type the type of axis to be drawn; inherited from the `xaxt` or `yaxt`\n#' arguments of the parent [`tinyplot()`] call. One of either: `\"standard\"`\n#' (default that draws the axis, ticks, and labels), `\"none\"` (no axes),\n#' `\"ticks\"` (only ticks and labels without axis line), `\"labels\"` (only\n#' labels without ticks and axis line), or `\"axis\"` (only axis line and labels\n#' but no ticks). Partial matching is allowed, e.g. `type = \"s\"`.\n#' @inheritParams tinylabel\n#' @examples\n#' \\dontrun{\n#' \n#' # plot without axes\n#' tinyplot(0:10, axes = \"n\")\n#' # add x-axis (labels only)\n#' tinyplot:::tinyAxis(x = 0:10, side = 1, type = \"l\")\n#' # add y-axis (with custom label formatting)\n#' tinyplot:::tinyAxis(x = 0:10, side = 2, type = \"s\", labeller = \"$\")\n#' }\n#' @keywords internal\ntinyAxis = function(x = NULL, ..., type = \"standard\", labeller = NULL) {\n type = match.arg(type, c(\"standard\", \"none\", \"labels\", \"ticks\", \"axis\"))\n if (type == \"none\") {\n invisible(numeric(0L))\n } else {\n args = list(x = x, ...)\n if (type == \"labels\") {\n args$tick = FALSE\n } else if (type == \"ticks\") {\n args$lwd = 0\n if (!(\"lwd.ticks\" %in% names(args))) args$lwd.ticks = 1\n } else if (type == \"axis\") {\n args$lwd.ticks = 0\n } else {\n args$tick = TRUE\n }\n if (!is.null(labeller)) {\n if (!is.null(args$at)) {\n args$labels = if (!is.null(args$labels)) tinylabel(args$labels, labeller) else tinylabel(args$at, labeller)\n } else {\n args$at = if (!inherits(x, c(\"POSIXt\", \"Date\"))) axTicks(args$side) else axTicksDateTime(args$side, x = x) \n args$labels = tinylabel(args$at, labeller)\n }\n }\n do.call(\"Axis\", args)\n }\n}\n\n# Special case for Date-Time, adapted/simplified from axis.date()\naxTicksDateTime = function(side, x, ...) {\n if (inherits(x, \"POSIXt\")) {\n tz = attr(x, \"tz\")\n range = extendrange(x)\n rangeDateTime = .POSIXct(range, tz = tz)\n } else {\n range = sort(par(\"usr\")[if (side%%2) 1L:2L else 3:4L])\n range[1L] = ceiling(range[1L])\n range[2L] = floor(range[2L])\n rangeDateTime = range\n class(rangeDateTime) = \"Date\"\n }\n z = pretty(rangeDateTime, n = par(\"lab\")[2 - side%%2])\n keep = z >= range[1L] & z <= range[2L]\n z = z[keep]\n return(z)\n}\n"], ["/tinyplot/R/type_function.R", "#' Plot a function\n#'\n#' @details\n#' When using `type_function()` in a `tinyplot()` call, the `x` value indicates\n#' the range of values to plot on the x-axis.\n#'\n#' @param fun Function of `x` to plot. Defaults to \\code{\\link[stats]{dnorm}}.\n#' @param args List of additional arguments to be passed to `fun`.\n#' @param n Number of points to interpolate on the x axis.\n#' @param ... Additional arguments are passed to the `lines()` function,\n#' ex: `type=\"p\"`, `col=\"pink\"`.\n#' @importFrom stats dnorm\n#' \n#' @examples\n#' # Plot the normal density (default function)\n#' tinyplot(x = -4:4, type = \"function\")\n#' # tinyplot(x = -4:4, type = type_function()) # same\n#'\n#' # Customize by passing explicit arguments to your function\n#' tinyplot(x = -1:10, type = type_function(\n#' fun = dnorm, args = list(mean = 3)\n#' ))\n#'\n#' # Additional arguments are passed to the `lines()` function.\n#' tinyplot(x = -4:4, type = type_function(\n#' fun = dnorm,\n#' col = \"pink\", type = \"p\", pch = 3\n#' ))\n#' \n#' # Custom function example\n#' ## (Here using `function(x)`, but you could also use the shorter `\\(x)`\n#' ## anonymous function syntax introduced in R 4.1.0)\n#' tinyplot(x = -4:4, type = type_function(fun = function(x) 0.5 * exp(-abs(x))))\n#'\n#' @export\ntype_function = function(fun = dnorm, args = list(), n = 101, ...) {\n assert_function(fun)\n lines_args = list(...)\n data_function = function(args, fun) {\n funky = function(xlim, ylim, datapoints, ...) {\n if (nrow(datapoints) == 0 || !\"x\" %in% names(datapoints)) {\n stop(\"Need to provide x values to plot the function.\", call. = FALSE)\n }\n if (is.null(xlim)) {\n xlim = range(datapoints[[\"x\"]])\n }\n if (is.null(ylim)) {\n tmp = c(list(datapoints[[\"x\"]]), args)\n tmp = range(tmp)\n tmp = seq(tmp[1], tmp[2], length.out = n)\n tmp = c(list(tmp), args)\n tmp = do.call(fun, tmp)\n ylim = c(min(tmp), max(tmp))\n }\n out = list(xlim = xlim, ylim = ylim)\n return(out)\n }\n }\n draw_function = function() {\n funky = function(ifacet, data_facet, ...) {\n xrange = range(data_facet[[ifacet]][[\"x\"]])\n x = seq(xrange[1], xrange[2], length.out = n)\n y = do.call(fun, c(list(x), args))\n tmp = c(list(x, y), lines_args)\n do.call(lines, tmp)\n }\n return(funky)\n }\n out = list(\n draw = draw_function(),\n data = data_function(args = args, fun = fun),\n name = \"function\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/tinylabel.R", "#' Format labels\n#' \n#' @description Function for formatting label appearance, e.g. axis\n#' ticks labels. This is what the top-level `xaxl` and `yaxl` arguments\n#' from [`tinyplot`] ultimately get passed to.\n#' @param x a numeric or character vector\n#' @param labeller a formatting function to be applied to `x`, e.g. [`format`],\n#' [`toupper`], [`abs`], or other custom function (including from the popular\n#' **scales** package). Can also be one of the following convenience strings\n#' (symbols), for which common formatting transformations are provided:\n#' `\"percent\"` (`\"%\"`), `\"comma\"` (`\",\"`), `\"log\"` (`\"l\"`), `\"dollar\"`\n#' (`\"$\"`), `\"euro\"` (`\"€\"`), or `\"sterling\"` (`\"£\"`).\n#' @examples\n#' x = 1e4\n#' tinylabel(x, \"comma\")\n#' tinylabel(x, \",\") # same\n#' tinylabel(x, \"$\") # or \"dollar\"\n#' \n#' # pass to xaxl/yaxl for adjusting axes tick labels in a tinyplot call\n#' tinyplot(I(mpg/hp) ~ hp, data = mtcars, yaxl = \"%\")\n#' \n#' # log example (combined with axis scaling)\n#' tinyplot(x = 10^c(10:0), y = 0:10, type = \"b\", log = \"x\", xaxl = \"log\")\n#' \n#' # combine with `x/yaxb` to adjust the actual tick marks (\"break points\")\n#' # at the same time\n#' tinyplot(x = 10^c(10:0), y = 0:10, type = \"b\", log = \"x\", xaxl = \"log\",\n#' xaxb = 10^c(1,3,5,7,9))\n#' \n#' #\n#' ## custom function examples\n#' \n#' ## example I: date formatting\n#' \n#' dat = data.frame(\n#' date = seq(as.Date(\"2000/1/1\"), by = \"month\", length.out = 12),\n#' trend = 1:12 + rnorm(12, sd = 1)\n#' )\n#' \n#' tinyplot(trend ~ date, data = dat, xaxl = function(x) format(x, \"%b, %Y\"))\n#' \n#' ## example II: string wrapping \n#' \n#' # create a \"vectorised\" version of `base::strwrap` that breaks long\n#' # strings into new lines every 18 characters\n#' strwrap18 = function(x) sapply(\n#' strwrap(x, width = 18, simplify = FALSE),\n#' paste,\n#' collapse = \"\\n\"\n#' )\n#' \n#' # now demonstrate on a dataset with long y-tick labels\n#' dat2 = data.frame(\n#' x = rep(rnorm(100), 3),\n#' y = c(\n#' \"tinyplot is a lightweight extension of the base R graphics system.\",\n#' \"R is a language for statistical computing.\",\n#' \"Data visualization is an essential skill.\"\n#' )\n#' )\n#' \n#' tinytheme(\"bw\")\n#' tinyplot(y ~ x, data = dat2, type = \"j\", yaxl = strwrap18)\n#' tinytheme()\n#' @export\ntinylabel = function(x, labeller = NULL) {\n if (is.null(labeller)) return(x)\n if (is.character(labeller)) labeller = labeller_fun((labeller))\n return(labeller(x))\n}\n\n\nlabeller_fun = function(label = \"percent\") {\n \n labels = c(\n \"%\" = \"percent\",\n \",\" = \"comma\",\n \"$\" = \"dollar\",\n \"\\u20ac\" = \"euro\",\n \"\\u00a3\" = \"sterling\",\n \"l\" = \"log\"\n )\n if (label %in% names(labels)) label = labels[label]\n \n ## all labels plus absolute value version\n # labels = c(\"percent\", \"comma\", \"dollar\", \"euro\", \"sterling\")\n labels = c(labels, paste0(\"abs_\", labels))\n\n ## match full label first, then store abs_ info separately\n label = match.arg(label, labels)\n abs_ = substr(label, 1L, 4L) == \"abs_\"\n if (abs_) label = substr(label, 5L, nchar(label))\n\n ## actual formatting function\n format_percent = function(x) {\n sprintf(\"%.0f%%\", x * 100)\n }\n \n format_comma = function(x) {\n prettyNum(x, big.mark = \",\", scientific = FALSE)\n }\n \n format_dollar = function(x) {\n paste0(\"$\", prettyNum(x, big.mark = \",\", scientific = FALSE))\n }\n \n format_euro = function(x) {\n paste0(\"\\u20ac\", prettyNum(x, big.mark = \",\", scientific = FALSE))\n }\n \n format_sterling = function(x) {\n paste0(\"\\u00a3\", prettyNum(x, big.mark = \",\", scientific = FALSE))\n }\n \n format_log = function(x) {\n parse(text = paste0(10, \"^\", format(log10(x), digits = 3)))\n }\n \n fun = switch(\n label,\n percent = format_percent,\n comma = format_comma,\n dollar = format_dollar,\n euro = format_euro,\n sterling = format_sterling,\n log = format_log\n )\n\n ## combine with absolute value if necessary\n if (abs_) function(x) fun(abs(x)) else fun\n}\n"], ["/tinyplot/R/sanitize.R", "sanitize_ribbon.alpha = function(ribbon.alpha) {\n assert_numeric(ribbon.alpha, len = 1, lower = 0, upper = 1, null.ok = TRUE)\n if (is.null(ribbon.alpha)) ribbon.alpha = .tpar[[\"ribbon.alpha\"]]\n return(ribbon.alpha)\n}\n\n\n\nsanitize_type = function(type, x, y, dots) {\n if (inherits(type, \"tinyplot_type\")) {\n return(type)\n }\n\n known_types = c(\n \"p\", \"l\", \"o\", \"b\", \"c\", \"h\", \"j\", \"s\", \"S\", \"n\", \n \"abline\",\n \"area\",\n \"bar\", \"barplot\",\n \"box\", \"boxplot\",\n \"density\",\n \"errorbar\",\n \"function\",\n \"glm\",\n \"hist\", \"histogram\",\n \"hline\",\n \"j\", \"jitter\",\n \"lines\",\n \"lm\",\n \"loess\",\n \"pointrange\",\n \"points\",\n \"polygon\", \"polypath\",\n \"qq\",\n \"rect\",\n \"ribbon\",\n \"ridge\",\n \"rug\",\n \"segments\",\n \"spine\", \"spineplot\",\n \"spline\",\n \"summary\",\n \"text\",\n \"violin\",\n \"vline\"\n )\n assert_choice(type, known_types, null.ok = TRUE)\n\n if (is.null(type)) {\n if (!is.null(x) && (is.factor(x) || is.character(x)) && !(is.factor(y) || is.character(y))) {\n # enforce boxplot type for y ~ factor(x)\n type = type_boxplot\n } else if (is.factor(y) || is.character(y)) {\n # enforce spineplot type for factor(y) ~ x\n type = type_spineplot\n } else {\n type = \"p\"\n }\n }\n\n if (is.character(type)) type = switch(type,\n \"abline\" = type_abline,\n \"area\" = type_area,\n \"bar\" = type_barplot,\n \"barplot\" = type_barplot,\n \"box\" = type_boxplot,\n \"boxplot\" = type_boxplot,\n \"density\" = type_density,\n \"errorbar\" = type_errorbar,\n \"function\" = type_function,\n \"glm\" = type_glm,\n \"hist\" = type_histogram,\n \"histogram\" = type_histogram,\n \"hline\" = type_hline,\n \"j\" = type_jitter,\n \"jitter\" = type_jitter,\n \"lines\" = type_lines,\n \"lm\" = type_lm,\n \"loess\" = type_loess,\n \"p\" = type_points,\n \"pointrange\" = type_pointrange,\n \"points\" = type_points,\n \"polygon\" = type_polygon,\n \"polypath\" = type_polypath,\n \"qq\" = type_qq,\n \"rect\" = type_rect,\n \"ribbon\" = type_ribbon,\n \"ridge\" = type_ridge,\n \"rug\" = type_rug,\n \"segments\" = type_segments,\n \"spine\" = type_spineplot,\n \"spineplot\" = type_spineplot,\n \"spline\" = type_spline,\n \"summary\" = type_summary,\n \"text\" = type_text,\n \"violin\" = type_violin,\n \"vline\" = type_vline,\n type # default case\n )\n \n if (is.function(type)) {\n args = intersect(names(formals(type)), names(dots))\n args = if (length(args) >= 1L) dots[args] else list()\n type = do.call(type, args)\n type$dots = dots[setdiff(names(dots), names(args))]\n }\n \n if (inherits(type, \"tinyplot_type\")) return(type)\n\n out = list(draw = NULL, data = NULL, name = type)\n return(out)\n}\n"], ["/tinyplot/R/tinyplot_add.R", "#' Add new elements to the current `tinyplot`\n#'\n#' @description\n#' This convenience function grabs the preceding `tinyplot` call and updates it\n#' with any new arguments that have been explicitly provided by the user. It\n#' then injects `add=TRUE` and evaluates the updated call, thereby drawing a new\n#' layer on top of the existing plot. `plt_add()` is a shorthand alias for\n#' `tinyplot_add()`.\n#'\n#' @section Limitations:\n#' - `tinyplot_add()` works reliably only when adding to a plot originally\n#' created using the [`tinyplot.formula`] method with a valid `data` argument.\n#' We cannot guarantee correct behavior if the original plot was created with\n#' the atomic [`tinyplot.default`] method, due to potential environment\n#' mismatches. (An exception is when the original plot arguments---`x`, `y`,\n#' etc.---are located in the global environment.)\n#'\n#' - Automatic legends for the added elements will be turned off.\n#'\n#' @param ... All named arguments override arguments from the previous calls.\n#' Arguments not supplied to [tinyplot_add] remain unchanged from the previous\n#' call.\n#'\n#' @examples\n#' tinyplot(Sepal.Width ~ Sepal.Length | Species,\n#' facet = ~Species,\n#' data = iris)\n#'\n#' tinyplot_add(type = \"lm\") ## or : plt_add(type = \"lm\")\n#'\n#' ## Note: the previous function is equivalent to (but much more convenient\n#' ## than) re-writing the full call with the new type and `add=TRUE`:\n#'\n#' # tinyplot(Sepal.Width ~ Sepal.Length | Species,\n#' # facet = ~Species,\n#' # data = iris,\n#' # type = \"lm\",\n#' # add = TRUE)\n#'\n#' @returns No return value, called for side effect of producing a plot.\n#'\n#' @export\ntinyplot_add = function(...) {\n cal = getOption(\"tinyplot_last_call\", default = NULL)\n\n ## TODO: remove the global option above and move to this when density is refactored\n # cal = get(\".last_call\", envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n\n if (is.null(cal)) {\n stop(\"No previous tinyplot call found.\")\n }\n\n args = list(...)\n for (n in names(args)) {\n if (n != \"\") {\n cal[[n]] = args[[n]]\n }\n }\n\n # allow first argument in tinyplot_add() to be unnamed\n if (isTRUE(names(args)[1] == \"\")) {\n cal[[2]] = args[[1]]\n }\n\n cal[[\"add\"]] = TRUE\n eval(cal)\n}\n\n\n\n#' @export\n#' @name plt_add\n#' @rdname tinyplot_add\nplt_add = tinyplot_add\n"], ["/tinyplot/R/get_saved_par.R", "#' @title Retrieve the saved graphical parameters\n#' \n#' @description Convenience function for retrieving the graphical parameters\n#' (i.e., the full list of `tag = value` pairs held in\n#' \\code{\\link[graphics]{par}}) from either immediately before or\n#' immediately after the most recent [tinyplot] call.\n#'\n#' @param when character. From when should the saved parameters be retrieved?\n#' Either \"before\" (the default) or \"after\" the preceding `tinyplot` call.\n#' \n#' @details A potential side-effect of [tinyplot] is that it can change a user's\n#' \\code{\\link[graphics]{par}} settings. For example, it may adjust the inner\n#' and outer plot margins to make space for an automatic legend; see\n#' [draw_legend]. While it is possible to immediately restore the original\n#' \\code{\\link[graphics]{par}} settings upon exit via the\n#' `tinyplot(..., restore.par = TRUE)` argument, this is not the default\n#' behaviour. The reason being that we need to preserve the adjusted parameter\n#' settings in case users want to add further graphical annotations to their\n#' plot (e.g., \\code{\\link[graphics]{abline}}, \\code{\\link[graphics]{text}},\n#' etc.) Nevertheless, it may still prove desirable to recall and reset these\n#' original graphical parameters after the fact (e.g., once all these extra\n#' annotations have been added). That is the purpose of this [get_saved_par]\n#' function.\n#' \n#' Of course, users may prefer to manually capture and reset graphical\n#' parameters, as per the standard method described in the\n#' \\code{\\link[graphics]{par}} documentation. For example:\n#' \n#' ```\n#' op = par(no.readonly = TRUE) # save current par settings \n#' # \n#' par(op) # reset original pars\n#' ```\n#' \n#' This standard manual approach may be safer than [get_saved_par] because it\n#' offers more precise control. Specifically, the value of [get_saved_par] \n#' itself will be reset after ever new [tinyplot] call; i.e. it may inherit an\n#' already-changed set of parameters. Users should bear these trade-offs in\n#' mind when deciding which approach to use. As a general rule,\n#' [get_saved_par] offers the convenience of resetting the original\n#' \\code{\\link[graphics]{par}} settings even if a user forgot to save them\n#' beforehand. But one should avoid invoking it after a series of consecutive\n#' [tinyplot] calls.\n#' \n#' Finally, note that users can always call \\code{\\link[grDevices]{dev.off}}\n#' to reset all \\code{\\link[graphics]{par}} settings to their defaults.\n#' \n#' @returns A list of \\code{\\link[graphics]{par}} settings.\n#' \n#' @examples\n#' #\n#' # Contrived example where we draw a grouped scatterplot with a legend and\n#' # manually add corresponding best fit lines for each group...\n#' #\n#' \n#' # First draw the grouped scatterplot\n#' tinyplot(Sepal.Length ~ Petal.Length | Species, iris)\n#' \n#' # Preserving adjusted par settings is good for adding elements to our plot\n#' for (s in levels(iris$Species)) {\n#' abline(\n#' lm(Sepal.Length ~ Petal.Length, iris, subset = Species==s),\n#' col = which(levels(iris$Species)==s)\n#' )\n#' }\n#' \n#' # Get saved par from before the preceding tinyplot call (but don't use yet)\n#' sp = get_saved_par(\"before\")\n#' \n#' # Note the changed margins will affect regular plots too, which is probably\n#' # not desirable\n#' plot(1:10)\n#' \n#' # Reset the original parameters (could use `par(sp)` here)\n#' tpar(sp)\n#' # Redraw our simple plot with our corrected right margin\n#' plot(1:10)\n#' \n#' #\n#' # Quick example going the other way, \"correcting\" for par.restore = TRUE...\n#' #\n#' \n#' tinyplot(Sepal.Length ~ Petal.Length | Species, iris, restore.par = TRUE)\n#' # Our added best lines will be wrong b/c of misaligned par\n#' for (s in levels(iris$Species)) {\n#' abline(\n#' lm(Sepal.Length ~ Petal.Length, iris, subset = Species==s),\n#' col = which(levels(iris$Species)==s), lty = 2\n#' )\n#' }\n#' # grab the par settings from the _end_ of the preceding tinyplot call to fix\n#' tpar(get_saved_par(\"after\"))\n#' # now the best lines are correct\n#' for (s in levels(iris$Species)) {\n#' abline(\n#' lm(Sepal.Length ~ Petal.Length, iris, subset = Species==s),\n#' col = which(levels(iris$Species)==s)\n#' )\n#' }\n#' \n#' # reset again to original saved par settings before exit\n#' tpar(sp)\n#'\n#' @export\nget_saved_par = function(when = c(\"before\", \"after\", \"first\")) {\n when = match.arg(when)\n par_env_name = paste0(\".saved_par_\", when)\n return(get(par_env_name, envir = get(\".tinyplot_env\", envir = parent.env(environment()))))\n}\n\n# (non-exported) companion function(s) for setting the original pars\nset_saved_par = function(when = c(\"before\", \"after\", \"first\"), value) {\n when = match.arg(when)\n par_env_name = paste0(\".saved_par_\", when)\n assign(par_env_name, value, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n}\n"], ["/tinyplot/R/type_area.R", "#' @rdname type_ribbon\n#' @export\ntype_area = function(alpha = NULL) {\n out = list(\n draw = NULL,\n data = data_area(alpha = alpha),\n name = \"area\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_area = function(alpha = alpha) {\n ribbon.alpha = if (is.null(alpha)) .tpar[[\"ribbon.alpha\"]] else (alpha)\n fun = function(datapoints, ...) {\n datapoints$ymax = datapoints$y\n datapoints$ymin = rep.int(0, nrow(datapoints))\n out = list(\n datapoints = datapoints,\n ymax = datapoints$ymax,\n ymin = datapoints$ymin,\n type = \"ribbon\",\n ribbon.alpha = ribbon.alpha\n )\n return(out)\n }\n return(fun)\n}\n"], ["/tinyplot/R/lim.R", "# calculate limits of each plot\n\nlim_args = function(\n datapoints,\n xlim, ylim,\n xaxb = NULL, yaxb = NULL,\n xlim_user = FALSE, ylim_user = FALSE,\n type\n) {\n \n if (is.null(xlim)) {\n xlim = range(c(datapoints[[\"x\"]], datapoints[[\"xmin\"]],\n datapoints[[\"xmax\"]]), finite = TRUE)\n }\n if (is.null(ylim)) {\n ylim = range(c(datapoints[[\"y\"]], datapoints[[\"ymin\"]],\n datapoints[[\"ymax\"]]), finite = TRUE)\n }\n\n if (identical(type, \"boxplot\")) {\n xlim = xlim + c(-0.5, 0.5)\n }\n \n if (!xlim_user && !is.null(xaxb) && type != \"spineplot\") xlim = range(c(xlim, xaxb))\n if (!ylim_user && !is.null(yaxb) && type != \"spineplot\") ylim = range(c(ylim, yaxb))\n\n out = list(xlim = xlim, ylim = ylim)\n return(out)\n}\n\n"], ["/tinyplot/R/zzz.R", "#' Operations on package load\n#' @importFrom utils globalVariables\n#' @param libname library name\n#' @param pkgname package name name\n#' @keywords internal\n#' @noRd\n.onLoad = function(libname, pkgname) {\n # https://stackoverflow.com/questions/12598242/global-variables-in-packages-in-r\n # https://stackoverflow.com/questions/49056642/r-how-to-make-variable-available-to-namespace-at-loading-time?noredirect=1&lq=1\n init_environment()\n init_tpar()\n set_environment_variable(\".saved_par_before\", NULL)\n set_environment_variable(\".saved_par_after\", NULL)\n set_environment_variable(\".saved_par_first\", NULL)\n set_environment_variable(\".last_call\", NULL)\n set_environment_variable(\".tpar_hooks\", NULL)\n\n globalVariables(c(\n \"add\",\n \"asp\",\n \"axes\",\n \"by_continuous\",\n \"by_ordered\",\n \"cex_fct_adj\",\n \"dots\",\n \"draw\",\n \"facet_bg\",\n \"facet_border\",\n \"facet_col\",\n \"facet_font\",\n \"facet_newlines\",\n \"facet_rect\",\n \"facet_text\",\n \"facet.args\",\n \"facet\",\n \"facets\",\n \"fill\",\n \"flip\",\n \"frame.plot\",\n \"has_legend\",\n \"iby\",\n \"ifacet\",\n \"nfacet_cols\",\n \"nfacet_rows\",\n \"nfacets\",\n \"ngrps\",\n \"oxaxis\",\n \"oyaxis\",\n \"ribbon.alpha\",\n \"split_data\",\n \"type\",\n \"x\",\n \"xaxl\",\n \"xaxs\",\n \"xaxt\",\n \"xlabs\",\n \"xlim\",\n \"xlim_user\",\n \"xlvls\",\n \"xmax\",\n \"xmin\",\n \"y\",\n \"yaxl\",\n \"yaxs\",\n \"yaxt\",\n \"ylabs\",\n \"ylim\",\n \"ylim_user\",\n \"ymax\",\n \"ymin\"\n ))\n}\n"], ["/tinyplot/R/utils.R", "rescale_num = function (x, from = NULL, to = NULL) {\n if (is.null(from)) from = range(x)\n if (is.null(to)) to = c(0, 1)\n (x - from[1])/diff(from) * diff(to) + to[1]\n}\n\n## Function for efficiently checking whether a vector has more than n unique\n## values (uses a hash set approach for large vectors to check sequentially)\nmore_than_n_unique = function(x, n, small_vec_len = 1e3L) {\n len_x = length(x)\n # For \"small\" vectors, just use direct length(unique(x)) approach\n if (len_x <= small_vec_len) {\n return(length(unique(x)) > n)\n } else {\n # For larger vectors, use the hash set approach\n env = new.env(hash = TRUE, size = n)\n count = 0\n for (val in x) {\n if (!exists(as.character(val), env)) {\n assign(as.character(val), TRUE, env)\n count = count + 1\n if (count > n) {\n return(TRUE)\n }\n }\n }\n return(FALSE)\n }\n}\n\n\n## Null coalescing operator\nif (getRversion() <= \"4.4.0\") {\n `%||%` = function(x, y) if (is.null(x)) y else x\n}\n\n\n## Function that computes an appropriate bandwidth kernel based on a string\n## input\nbw_fun = function(kernel, x) {\n kernel = tolower(kernel)\n switch(\n kernel,\n nrd0 = bw.nrd0(x),\n nrd = bw.nrd(x),\n ucv = bw.ucv(x),\n bcv = bw.bcv(x),\n sj = bw.SJ(x),\n stop(\"Invalid `bw` string. Choose from 'nrd0', 'nrd', 'ucv', 'bcv', or 'SJ'.\")\n )\n}\n"], ["/tinyplot/R/tinyformula.R", "## auxiliary functions for formula/facet parsing\n\ntinyformula = function(formula, facet = NULL) {\n ## input\n ## - formula: y ~ x or y ~ x | z or ~ x or ~ x | z\n ## - facet: ~ a or ~ a + b or b ~ a\n ##\n ## output:\n ## - x: ~ x\n ## - y: NULL or ~ y\n ## - by: NULL or ~ z or ~ z1 + z2 + ... (use interaction of all)\n ## - xfacet: NULL or ~ a or ~ a + b etc.\n ## - yfacet: NULL or ~ b\n ## - full: e.g. ~ x + y + z + a + b\n\n ## preliminaries\n if (!inherits(formula, \"formula\")) formula = as.formula(formula)\n nf = length(formula)\n\n ## basic formula types\n x = ~ x\n y = if (nf == 2L) NULL else ~ y\n by = if (!inherits(formula[[nf]], \"call\") || formula[[nf]][[1L]] != as.name(\"|\")) NULL else ~ z\n if (is.null(facet) || !inherits(facet, \"formula\")) {\n xfacet = NULL\n yfacet = NULL\n } else {\n xfacet = ~ a\n yfacet = if (length(facet) == 2L) NULL else ~ b\n }\n\n ## fill with actual terms\n environment(x) = environment(formula)\n if (!is.null(y)) {\n environment(y) = environment(formula)\n y[[2L]] = formula[[2L]]\n }\n if (is.null(by)) {\n x[[2L]] = formula[[nf]]\n } else {\n environment(by) = environment(formula)\n by[[2L]] = formula[[nf]][[3L]]\n x[[2L]] = formula[[nf]][[2L]]\n }\n if (!is.null(xfacet)) {\n environment(xfacet) = environment(formula)\n xfacet[[2L]] = facet[[length(facet)]]\n }\n if (!is.null(yfacet)) {\n environment(yfacet) = environment(formula)\n yfacet[[2L]] = facet[[2L]]\n }\n\n ## combine everything\n full = x\n if (!is.null(y)) full[[2L]] = call(\"+\", full[[2L]], y[[2L]])\n if (!is.null(by)) full[[2L]] = call(\"+\", full[[2L]], by[[2L]])\n if (!is.null(xfacet)) full[[2L]] = call(\"+\", full[[2L]], xfacet[[2L]])\n if (!is.null(yfacet)) full[[2L]] = call(\"+\", full[[2L]], yfacet[[2L]])\n\n ## return list of all formulas\n return(list(\n x = x,\n y = y,\n by = by,\n xfacet = xfacet,\n yfacet = yfacet,\n full = full\n ))\n}\n\ntinyframe = function(formula, data, drop = FALSE) {\n ## input\n ## - formula: (sub-)formula\n ## - data: model.frame from full formula\n if (is.null(formula)) return(NULL)\n names = sapply(attr(terms(formula), \"variables\")[-1L], deparse, width.cutoff = 500L)\n data[, names, drop = drop]\n}\n"], ["/tinyplot/R/hooks.R", "# Copied from https://raw.githubusercontent.com/r-lib/evaluate/refs/heads/main/R/hooks.R\n# license: MIT + file LICENSE\n\n\n\n#' Set and remove hooks\n#'\n#' This interface wraps the base [setHook()] function to provide a return\n#' value that makes it easy to undo.\n#'\n#' @param hooks a named list of hooks - each hook can either be a function or\n#' a list of functions.\n#' @param action `\"replace\"`, `\"append\"` or `\"prepend\"`\n#' @keywords internal\nset_hooks <- function(hooks, action = \"append\") {\n old <- list()\n for (hook_name in names(hooks)) {\n old[[hook_name]] <- getHook(hook_name)\n setHook(hook_name, hooks[[hook_name]], action = action)\n }\n invisible(old)\n}\n\n#' @rdname set_hooks\n#' @keywords internal\nremove_hooks <- function(hooks) {\n for (hook_name in names(hooks)) {\n hook <- getHook(hook_name)\n if (length(hook) > 0) {\n for (fun in unlist(hooks[hook_name])) {\n hook[sapply(hook, identical, fun)] <- NULL\n }\n }\n setHook(hook_name, hook, \"replace\")\n }\n}\n"], ["/tinyplot/R/assertions.R", "check_dependency = function(library_name) {\n flag = requireNamespace(library_name, quietly = TRUE)\n if (isFALSE(flag)) {\n msg = sprintf(\"Please install the `%s` package.\", library_name)\n return(msg)\n } else {\n return(TRUE)\n }\n}\n\nassert_dependency = function(library_name) {\n flag = check_dependency(library_name)\n if (!isTRUE(flag)) stop(flag, call. = FALSE)\n return(invisible())\n}\n\nassert_choice = function(x, choice, null.ok = FALSE, name = as.character(substitute(x))) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(TRUE)\n }\n if (is.character(x) && length(x) == 1 && x %in% choice) {\n return(TRUE)\n }\n msg = sprintf(\n \"`%s` must be one of: %s\",\n name,\n paste(choice, collapse = \", \")\n )\n stop(msg, call. = FALSE)\n}\n\ncheck_true = function(x, null.ok = FALSE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(invisible(TRUE))\n }\n if (isTRUE(x)) {\n return(invisible(TRUE))\n }\n return(FALSE)\n}\n\nassert_true = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be true.\", name)\n if (!isTRUE(check_true(x, null.ok = null.ok))) {\n stop(msg, call. = FALSE)\n }\n}\n\ncheck_string = function(x, null.ok = FALSE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(invisible(TRUE))\n }\n if (is.character(x) && length(x) == 1) {\n return(invisible(TRUE))\n }\n return(FALSE)\n}\n\nassert_string = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be a string.\", name)\n if (!isTRUE(check_string(x, null.ok = null.ok))) {\n stop(msg, call. = FALSE)\n }\n}\n\ncheck_flag = function(x, null.ok = FALSE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(TRUE)\n }\n if (is.logical(x) && length(x) == 1) {\n return(TRUE)\n }\n return(FALSE)\n}\n\nassert_flag = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be a logical flag.\", name)\n if (!isTRUE(check_flag(x, null.ok = null.ok))) {\n stop(msg, call. = FALSE)\n }\n}\n\nassert_length = function(x, len = 1, null.ok = FALSE, name = as.character(substitute(x))) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(invisible(TRUE))\n }\n msg = sprintf(\"`%s` must be one of these lengths: %s\", name, paste(len, collapse = \", \"))\n if (!length(x) %in% len) {\n stop(msg, call. = FALSE)\n }\n}\n\nassert_logical = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(invisible(TRUE))\n }\n msg = sprintf(\"`%s` must be a logical vector\", name)\n if (!is.logical(x)) stop(msg, call. = FALSE)\n}\n\n\ncheck_integerish = function(x, len = NULL, lower = NULL, upper = NULL, null.ok = TRUE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(TRUE)\n }\n if (!is.numeric(x)) {\n return(FALSE)\n }\n x = stats::na.omit(x)\n if (!is.null(len) && length(x) != len) {\n return(FALSE)\n }\n if (!is.null(lower) && any(x < lower)) {\n return(FALSE)\n }\n if (!is.null(upper) && any(x > upper)) {\n return(FALSE)\n }\n if (isTRUE(any(abs(x - round(x)) > (.Machine$double.eps)^0.5))) {\n return(FALSE)\n }\n return(TRUE)\n}\n\nassert_integerish = function(x, len = NULL, lower = NULL, upper = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(invisible())\n }\n msg = sprintf(\"`%s` must be integer-ish\", name)\n if (is.null(x) && !isTRUE(null.ok)) stop(sprintf(\"%s should not be NULL.\", name), call. = FALSE)\n if (!isTRUE(check_integerish(x, len = len, lower = lower, upper = upper, null.ok = null.ok))) {\n if (!is.numeric(x)) msg = paste0(msg, \"; it is not numeric\")\n if (!is.null(len) && length(x) != len) msg = paste0(msg, sprintf(\"; its length must be %s\", len))\n if (!is.null(lower) && any(x < lower)) msg = paste0(msg, sprintf(\"; all values must be greater than or equal to %s\", lower))\n if (!is.null(upper) && any(x > upper)) msg = paste0(msg, sprintf(\"; all values must be less than or equal to %s\", upper))\n if (isTRUE(any(abs(x - round(x)) > (.Machine$double.eps)^0.5))) msg = paste0(msg, \"; all values must be close to integers\")\n stop(msg, call. = FALSE)\n }\n}\n\ncheck_numeric = function(x, len = NULL, lower = NULL, upper = NULL, null.ok = TRUE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(TRUE)\n }\n if (!is.numeric(x)) {\n return(FALSE)\n }\n if (!is.null(len) && length(x) != len) {\n return(FALSE)\n }\n if (!is.null(lower) && any(x < lower)) {\n return(FALSE)\n }\n if (!is.null(upper) && any(x > upper)) {\n return(FALSE)\n }\n return(TRUE)\n}\n\nassert_numeric = function(x, len = NULL, lower = NULL, upper = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be numeric\", name)\n if (!isTRUE(check_numeric(x, len = len, lower = lower, upper = upper, null.ok = null.ok))) {\n if (!is.null(len) && length(x) != len) msg = paste0(msg, sprintf(\"; its length must be %s\", len))\n if (!is.null(lower) && any(x < lower)) msg = paste0(msg, sprintf(\"; all values must be greater than or equal to %s\", lower))\n if (!is.null(upper) && any(x > upper)) msg = paste0(msg, sprintf(\"; all values must be less than or equal to %s\", upper))\n stop(msg, call. = FALSE)\n }\n}\n\nassert_data_frame = function(x, min_rows = 0, min_cols = 0, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be a data.frame.\", name)\n if (!is.data.frame(x)) stop(msg, call. = FALSE)\n msg = sprintf(\"Number of rows in `%s` must be at least `%s`\", name, min_rows)\n if (nrow(x) < min_rows) stop(msg, call. = FALSE)\n msg = sprintf(\"Number of columns in `%s` must be at least `%s`\", name, min_cols)\n if (ncol(x) < min_cols) stop(msg, call. = FALSE)\n}\n\n\ncheck_character = function(x, len = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(TRUE)\n } else if (!is.character(x)) {\n msg = sprintf(\"`%s` must be character.\", name)\n return(msg)\n } else if (!is.null(len) && length(x) != len) {\n msg = sprintf(\"`%s` must have length %s.\", name, len)\n return(msg)\n }\n return(TRUE)\n}\n\nassert_character = function(x, len = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n flag = check_character(x, len = len, null.ok = null.ok, name = name)\n if (!isTRUE(flag)) {\n stop(flag, call. = FALSE)\n } else {\n return(invisible(TRUE))\n }\n}\n\nassert_list = function(x, named = FALSE, len = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(invisible(TRUE))\n }\n if (!is.list(x)) stop(\"Input is not a list.\", call. = FALSE)\n if (isTRUE(named)) {\n if (is.null(names(x))) {\n stop(sprintf(\"`%s` should be named list.\", name), call. = FALSE)\n }\n }\n if (!is.null(len)) {\n if (length(x) != len) {\n stop(sprintf(\"`%s` must be of length %s.\", name, len), call. = FALSE)\n }\n }\n}\n\nassert_function = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(invisible(TRUE))\n }\n if (!is.function(x)) {\n msg = sprintf(\"`%s` must be a function.\", name)\n stop(msg, call. = FALSE)\n }\n}\n\ncheck_atomic_vector = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(invisible(TRUE))\n }\n # doesn't work on glue::glue() output\n # flag = is.atomic(x) && is.vector(x) && !is.list(x)\n flag = is.atomic(x) && is.null(dim(x)) && length(x) > 0 && !is.list(x)\n if (flag) {\n out = TRUE\n } else if (is.factor(x) && is.null(dim(x))) {\n out = TRUE\n } else {\n out = sprintf(\"`%s` must be an atomic vector.\", name)\n }\n return(out)\n}\n\nassert_atomic_vector = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n flag = check_atomic_vector(x, null.ok = null.ok, name = name)\n if (!isTRUE(flag)) {\n stop(flag, call. = FALSE)\n } else {\n return(invisible(TRUE))\n }\n}\n\nassert_class = function(x, classname) {\n if (!inherits(x, classname)) {\n msg = sprintf(\"`x` must be of class `%s`.\", classname)\n stop(msg, call. = FALSE)\n }\n}\n\n"], ["/tinyplot/R/setup_device.R", "setup_device = function(file, width, height) {\n # write to file\n if (!is.null(file)) {\n filepath = file\n filewidth = width\n fileheight = height\n if (is.null(filewidth)) filewidth = .tpar[[\"file.width\"]]\n if (is.null(fileheight)) fileheight = .tpar[[\"file.height\"]]\n fileres = .tpar[[\"file.res\"]]\n # catch to close interactive device if one isn't already open\n fkdev = is.null(dev.list())\n # grab existing device pars to pass on to next one\n dop = par(no.readonly = TRUE)\n # close interactive device if not already open\n if (isTRUE(fkdev)) dev.off()\n exttype = file_ext(filepath)\n if (exttype == \"pdf\" && .tpar[[\"cairo\"]]) {\n exttype = \"cairo\"\n } else if (exttype == \"jpg\") {\n exttype = \"jpeg\"\n }\n switch(exttype,\n png = png(filepath, width = filewidth, height = fileheight, units = \"in\", res = fileres),\n jpeg = jpeg(filepath, width = filewidth, height = fileheight, units = \"in\", res = fileres),\n pdf = pdf(filepath, width = filewidth, height = fileheight),\n cairo = cairo_pdf(filepath, width = filewidth, height = fileheight),\n svg = svg(filepath, width = filewidth, height = fileheight),\n stop(\"\\nUnsupported file extension. Only '.png', '.jpg', '.pdf', or '.svg' are allowed.\\n\")\n )\n dop$new = FALSE # catch for some interfaces\n par(dop)\n\n # interactive plot with user-specified width/height\n } else if (!is.null(width) || !is.null(height)) {\n devwidth = width\n devheight = height\n # if one of width or height is missing, set equal to the other\n if (is.null(devwidth)) devwidth = devheight\n if (is.null(devheight)) devheight = devwidth\n # catch to close interactive device if one isn't already open\n fkdev = is.null(dev.list())\n # grab existing device pars to pass on to next one\n dop = par(no.readonly = TRUE)\n # close interactive device if not already open\n if (isTRUE(fkdev)) dev.off()\n dev.new(width = devwidth, height = devheight)\n dop$new = FALSE # catch for some interfaces\n par(dop)\n }\n}\n"], ["/tinyplot/R/environment.R", "init_environment = function() {\n tnypltptns = parent.env(environment())\n assign(\".tinyplot_env\", new.env(), envir = tnypltptns)\n .tpar = new.env()\n assign(\".tpar\", .tpar, envir = tnypltptns)\n}\n\nget_environment_variable = function(name) {\n get(name, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n}\n\nset_environment_variable = function(name, value) {\n assign(name, value, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n}\n"], ["/tinyplot/R/tinyplot-package.R", "#' @keywords internal\n\"_PACKAGE\"\n\nNULL\n"]], "task_instance_info": {"created_time": "2025-08-21 01:20:28", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(type = \"l\") {}", "code_description": "This code segment functions to: Generate a customizable plotting function that applies specified graphical parameters to render connected data points with configurable line styles and visual attributes."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nfunction(type = \"l\") {\n function(x, y, ...) {\n graphics::lines(x, y, type = type, ...)\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-20-50"}, "editdistance_info": {"edit_distance": 17.1429, "calculate_time": "2025-08-21 01:20:50", "true_code_clean": "function(type = \"l\") {\n fun = function(ix, iy, icol, ipch, ibg, ilty, ilwd, cex = 1, ...) {\n lines(\n x = ix,\n y = iy,\n col = icol,\n type = type,\n pch = ipch,\n bg = ibg,\n lty = ilty,\n lwd = ilwd,\n cex = cex\n )\n }\n return(fun)\n}", "predict_code_clean": "function(type = \"l\") {\n function(x, y, ...) {\n graphics::lines(x, y, type = type, ...)\n }\n}"}} {"repo_name": "tinyplot", "file_name": "/tinyplot/R/type_glm.R", "inference_info": {"prefix_code": "#' Generalized linear model plot type\n#' \n#' @description Type function for plotting a generalized model fit.\n#' Arguments are passed to \\code{\\link[stats]{glm}}.\n#' \n#' @param se logical. If TRUE, confidence intervals are drawn.\n#' @inheritParams stats::glm\n#' @inheritParams stats::predict.glm\n#' @inheritParams stats::confint\n#' @importFrom stats glm predict\n#' @examples\n#' # \"glm\" type convenience string\n#' tinyplot(am ~ mpg, data = mtcars, type = \"glm\")\n#' \n#' # Use `type_glm()` to pass extra arguments for customization\n#' tinyplot(am ~ mpg, data = mtcars, type = type_glm(family = \"binomial\"))\n#' @export\ntype_glm = ", "suffix_code": "\n\n\ndata_glm = function(family, se, level, type, ...) {\n fun = function(datapoints, ...) {\n dat = split(datapoints, list(datapoints$facet, datapoints$by))\n dat = lapply(dat, function(x) {\n if (nrow(x) == 0) return(x)\n if (nrow(x) < 3) {\n x$y = NA\n return(x)\n }\n fit = glm(y ~ x, data = x, family = family)\n nd = data.frame(x = seq(min(x$x, na.rm = TRUE), max(x$x, na.rm = TRUE), length.out = 100))\n nd$by = x$by[1]\n nd$facet = x$facet[1]\n if (se == TRUE) {\n if (identical(type, \"response\")) {\n p = predict(fit, newdata = nd, type = \"link\", se.fit = TRUE)\n p = ci(p$fit, p$se.fit, conf.level = level, fit$df.residual, backtransform = stats::family(fit)$linkinv)\n nd$y = p$estimate\n nd$ymax = p$conf.high\n nd$ymin = p$conf.low\n\n } else {\n nd$y = predict(fit, newdata = nd, type = type)\n nd = ci(nd$y, nd$se, level, fit$df.residual, backtransform = stats::family(fit)$linkinv)\n }\n } else {\n nd$y = predict(fit, nd, type = type)\n }\n nd\n })\n datapoints = do.call(rbind, dat)\n datapoints = datapoints[order(datapoints$facet, datapoints$by, datapoints$x), ]\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\n\n#' Calculate confidence intervals\n#' @importFrom stats qt\n#' @keywords internal\nci = function(estimate, std.error, conf.level, df, backtransform = identity) {\n crit = qt(1 - (1 - conf.level) / 2, df)\n out = list(\n estimate = backtransform(estimate),\n conf.low = backtransform(estimate - crit * std.error),\n conf.high = backtransform(estimate + crit * std.error)\n )\n return(out)\n}\n", "middle_code": "function(family = \"gaussian\", se = TRUE, level = 0.95, type = \"response\") {\n assert_flag(se)\n out = list(\n draw = draw_ribbon(),\n data = data_glm(family = family, se = se, level = level, type = type),\n name = if (isTRUE(se)) \"ribbon\" else \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/tinyplot/R/type_lm.R", "#' Linear model plot type\n#'\n#' @description Type function for plotting a linear model fit.\n#' Arguments are passed to \\code{\\link[stats]{lm}}.\n#' \n#' @inheritParams type_glm\n#' @importFrom stats lm predict\n#' @examples\n#' # \"lm\" type convenience string\n#' tinyplot(Sepal.Width ~ Petal.Width, data = iris, type = \"lm\")\n#' \n#' # Grouped model fits (here: illustrating an example of Simpson's paradox)\n#' tinyplot(Sepal.Width ~ Petal.Width | Species, data = iris, type = \"lm\")\n#' tinyplot_add(type = \"p\")\n#' \n#' # Use `type_lm()` to pass extra arguments for customization\n#' tinyplot(Sepal.Width ~ Petal.Width, data = iris, type = type_lm(level = 0.8))\n#' @export\ntype_lm = function(se = TRUE, level = 0.95) {\n assert_flag(se)\n out = list(\n draw = draw_ribbon(),\n data = data_lm(se = se, level = level),\n name = if (isTRUE(se)) \"ribbon\" else \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_lm = function(se, level, ...) {\n fun = function(datapoints, ...) {\n dat = split(datapoints, list(datapoints$facet, datapoints$by))\n dat = lapply(dat, function(x) {\n if (nrow(x) == 0) return(x)\n if (nrow(x) < 3) {\n x$y = NA\n return(x)\n }\n fit = lm(y ~ x, data = x)\n nd = data.frame(x = seq(min(x$x, na.rm = TRUE), max(x$x, na.rm = TRUE), length.out = 100))\n nd$by = x$by[1]\n nd$facet = x$facet[1]\n if (se == TRUE) {\n p = predict(fit, newdata = nd, se.fit = TRUE)\n p = ci(p$fit, p$se.fit, conf.level = level, fit$df.residual)\n nd$y = p$estimate\n nd$ymax = p$conf.high\n nd$ymin = p$conf.low\n } else {\n nd$y = predict(fit, newdata = nd)\n }\n nd\n })\n datapoints = do.call(rbind, dat)\n datapoints = datapoints[order(datapoints$facet, datapoints$by, datapoints$x), ]\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_loess.R", "#' Local polynomial regression plot type\n#' \n#' @description Type function for plotting a LOESS (LOcal regrESSion) fit.\n#' Arguments are passed to \\code{\\link[stats]{loess}}.\n#' \n#' @inheritParams stats::loess\n#' @param se logical. If `TRUE` (the default), confidence intervals are drawn.\n#' @param level the confidence level required if `se = TRUE`. Default is 0.95.\n#' @importFrom stats loess loess.control predict\n#' @examples\n#' # \"loess\" type convenience string\n#' tinyplot(dist ~ speed, data = cars, type = \"loess\")\n#' \n#' # Use `type_loess()` to pass extra arguments for customization\n#' tinyplot(dist ~ speed, data = cars, type = type_loess(span = 0.5, degree = 1))\n#' @export\ntype_loess = function(\n span = 0.75,\n degree = 2,\n family = \"gaussian\",\n control = loess.control(),\n se = TRUE,\n level = 0.95\n ) {\n out = list(\n draw = draw_ribbon(),\n data = data_loess(span = span, degree = degree, family = family, control = control, se = se, level = level),\n name = if (isTRUE(se)) \"ribbon\" else \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_loess = function(span, degree, family, control, se, level, ...) {\n fun = function(datapoints, ...) {\n datapoints = split(datapoints, list(datapoints$facet, datapoints$by))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n datapoints = lapply(datapoints, function(dat) {\n fit = loess(y ~ x, data = dat, span = span, degree = degree, family = family, control = control)\n if (se == TRUE) {\n p = predict(fit, newdata = dat, se = TRUE)\n p = ci(p$fit, p$se.fit, conf.level = level, p$df)\n dat$y = p$estimate\n dat$ymax = p$conf.high\n dat$ymin = p$conf.low\n } else {\n dat$y = predict(fit, dat)\n }\n dat\n })\n datapoints = do.call(rbind, datapoints)\n datapoints = datapoints[order(datapoints$facet, datapoints$by, datapoints$x), ]\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_spline.R", "#' Spline plot type\n#' \n#' @description Type function for plotting a cubic (or Hermite) spline interpolation.\n#' Arguments are passed to \\code{\\link[stats]{spline}}; see this latter function\n#' for default argument values.\n#' \n#' @inheritParams stats::spline\n#' @inherit stats::spline details\n#' @importFrom stats spline\n#' @examples\n#' # \"spline\" type convenience string\n#' tinyplot(dist ~ speed, data = cars, type = \"spline\")\n#' \n#' # Use `type_spline()` to pass extra arguments for customization\n#' tinyplot(dist ~ speed, data = cars, type = type_spline(method = \"natural\", n = 25),\n#' add = TRUE, lty = 2)\n#' @export\ntype_spline = function(\n n = NULL,\n method = \"fmm\",\n xmin = NULL,\n xmax = NULL,\n xout = NULL,\n ties = mean\n ) {\n out = list(\n draw = draw_lines(),\n data = data_spline(method = method, ties = ties, n = n, xmin = xmin, xmax = xmax, xout = xout),\n name = \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_spline = function(n, method, xmin, xmax, xout, ties, ...) {\n fun = function(datapoints, ...) {\n datapoints = split(datapoints, list(datapoints$facet, datapoints$by), drop = TRUE)\n datapoints = lapply(datapoints, function(dat) {\n if (is.null(n)) n = 3*length(dat$x)\n if (is.null(xmax)) xmax = max(dat$x)\n if (is.null(xmin)) xmin = min(dat$x)\n if (is.null(xout)) {\n fit = spline(x = dat$x, y = dat$y, n = n, method = method, xmin = xmin, xmax = xmax, ties = ties)\n } else {\n fit = spline(x = dat$x, y = dat$y, n = n, method = method, xmin = xmin, xmax = xmax, xout = xout, ties = ties)\n }\n fit = as.data.frame(fit)\n fit$facet = dat$facet[1]\n fit$by = dat$by[1]\n fit\n return(fit)\n })\n datapoints = do.call(rbind, datapoints)\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_violin.R", "#' Violin plot type\n#' \n#' @md\n#' @description Type function for violin plots, which are an alternative to box\n#' plots for visualizing continuous distributions (by group) in the form of\n#' mirrored densities.\n#' @inheritParams type_density\n#' @param trim logical indicating whether the violins should be trimmed to the\n#' range of the data. Default is `FALSE`.\n#' @param width numeric (ideally in the range `[0, 1]`, although this isn't\n#' enforced) giving the normalized width of the individual violins.\n#' @inherit stats::density details\n#' @details See [`type_density`] for more details and considerations related to\n#' bandwidth selection and kernel types.\n#' \n#' @examples\n#' # \"violin\" type convenience string\n#' tinyplot(count ~ spray, data = InsectSprays, type = \"violin\")\n#' \n#' # aside: to match the defaults of `ggplot2::geom_violin()`, use `trim = TRUE`\n#' # and `joint.bw = FALSE`\n#' tinyplot(count ~ spray, data = InsectSprays, type = \"violin\",\n#' trim = TRUE, joint.bw = FALSE)\n#' \n#' # use flip = TRUE to reorient the axes\n#' tinyplot(count ~ spray, data = InsectSprays, type = \"violin\", flip = TRUE)\n#' \n#' # for flipped plots with long group labels, it's better to use a theme for\n#' # dynamic plot resizing\n#' tinytheme(\"clean\")\n#' tinyplot(weight ~ feed, data = chickwts, type = \"violin\", flip = TRUE)\n#' \n#' # you can group by the x var to add colour (here with the original orientation)\n#' tinyplot(weight ~ feed | feed, data = chickwts, type = \"violin\", legend = FALSE)\n#' \n#' # dodged grouped violin plot example (different dataset)\n#' tinyplot(len ~ dose | supp, data = ToothGrowth, type = \"violin\", fill = 0.2)\n#' \n#' # note: above we relied on `...` argument passing alongside the \"violin\"\n#' # type convenience string. But this won't work for `width`, since it will\n#' # clash with the top-level `tinyplot(..., width = )` arg. To ensure\n#' # correct arg passing, it's safer to use the formal `type_violin()` option.\n#' tinyplot(len ~ dose | supp, data = ToothGrowth, fill = 0.2,\n#' type = type_violin(width = 0.8))\n#' \n#' # reset theme\n#' tinytheme()\n#' \n#' @importFrom stats density weighted.mean\n#' @importFrom stats bw.SJ bw.bcv bw.nrd bw.nrd0 bw.ucv \n#' @export\ntype_violin = function(\n bw = \"nrd0\",\n joint.bw = c(\"mean\", \"full\", \"none\"),\n adjust = 1,\n kernel = c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"),\n n = 512,\n # more args from density here?\n trim = FALSE,\n width = 0.9\n ) {\n kernel = match.arg(kernel, c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"))\n if (is.logical(joint.bw)) {\n joint.bw = ifelse(joint.bw, \"mean\", \"none\")\n }\n joint.bw = match.arg(joint.bw, c(\"mean\", \"full\", \"none\"))\n out = list(\n data = data_violin(bw = bw, adjust = adjust, kernel = kernel, n = n,\n joint.bw = joint.bw, trim = trim, width = width),\n # draw = NULL,\n # name = \"polygon\"\n draw = draw_polygon(density = NULL),\n name = \"violin\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\ndata_violin = function(bw = \"nrd0\", adjust = 1, kernel = \"gaussian\", n = 512,\n joint.bw = \"none\", trim = FALSE, width = 0.9) {\n fun = function(datapoints, by, facet, ylab, col, bg, palette, log, null_by, null_facet, ...) {\n \n # Handle ordering based on by and facet variables\n ngrps = if (null_by) 1 else length(unique(datapoints$by))\n nfacets = if (null_facet) 1 else length(unique(datapoints$facet))\n \n # catch for special cases\n x_by = y_by = facet_by = FALSE\n if (!null_by) {\n x_by = identical(datapoints$x, datapoints$by)\n y_by = identical(datapoints$y, datapoints$by)\n if (!null_facet) facet_by = identical(datapoints$facet, datapoints$by)\n }\n \n # FIXME (once we add support for gradient fill to draw_polygon)\n if (y_by) {\n warning(\"\\n`y` == `by` is not currently supported for `type_violin`. We hope to support this in a future release, but for now `y` grouping will be turned off automatically.\\n\")\n by = NULL\n datapoints$by = \"\"\n ngrps = 1\n null_by = TRUE\n }\n \n # Convert x to factor if it's not already\n datapoints$x = as.factor(datapoints$x)\n if (x_by) datapoints$by = datapoints$x\n\n # Handle factor levels and maintain order\n xlvls = levels(datapoints$x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n # xlabs = levels(datapoints$x)\n datapoints$x = as.integer(datapoints$x)\n\n if (null_by && null_facet) {\n xord = order(datapoints$x)\n } else if (null_facet) {\n xord = order(datapoints$by, datapoints$x)\n } else if (null_by) {\n xord = order(datapoints$facet, datapoints$x)\n } else {\n xord = order(datapoints$by, datapoints$facet, datapoints$x)\n }\n\n if (length(unique(datapoints[[\"by\"]])) == 1 && is.null(palette)) {\n if (is.null(col)) col = par(\"fg\")\n if (is.null(bg)) bg = \"lightgray\"\n } else if (is.null(bg)) {\n bg = \"by\"\n }\n\n # Reorder x, y, ymin, and ymax based on the order determined\n datapoints = datapoints[xord,]\n\n \n datapoints = split(datapoints, list(datapoints$x, datapoints$by, datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n \n if (joint.bw == \"none\" || is.numeric(bw)) {\n dens_bw = bw\n } else {\n if (joint.bw == \"mean\") {\n # Use weighted mean of subgroup bandwidths\n bws = sapply(datapoints, function(dat) bw_fun(kernel = bw, dat$y))\n ws = sapply(datapoints, nrow)\n dens_bw = weighted.mean(bws, ws)\n } else if (joint.bw == \"full\") {\n dens_bw = bw_fun(kernel = bw, unlist(sapply(datapoints, `[[`, \"x\")))\n }\n }\n \n datapoints = lapply(seq_along(datapoints), function(d) {\n dat = datapoints[[d]]\n if (trim) {\n yrng = range(dat$y)\n dens = density(dat$y, bw = dens_bw, kernel = kernel, n = n, from = yrng[1], to = yrng[2])\n } else {\n dens = density(dat$y, bw = dens_bw, kernel = kernel, n = n)\n }\n \n x = dens$y\n y = dens$x\n \n \n if (log %in% c(\"y\", \"xy\")) {\n if (x[1] <= 0) {\n warning(\"\\nNon-positive density values have been trimmed as part of the logarthmic transformation.\\n\")\n xidx = x > 0\n x = x[xidx]\n y = y[xidx]\n } \n }\n \n x = c(x, rev(-x))\n y = c(y, rev(y))\n \n xwidth = xwidth_orig = width\n # dodge groups (if any)\n if ((ngrps > 1) && isFALSE(x_by) && isFALSE(facet_by)) {\n xwidth = xwidth_orig / ngrps - 0.01\n x = rescale_num(x, to = c(0, xwidth))\n x = x + as.numeric(sub(\"^([0-9]+)\\\\..*\", \"\\\\1\", names(datapoints)[d])) - xwidth/2\n x = x + seq(-((xwidth_orig - xwidth) / 2), ((xwidth_orig - xwidth) / 2), length.out = ngrps)[dat$by[1]]\n } else if (nfacets > 1) {\n x = rescale_num(x, to = c(0, xwidth))\n x = x + as.numeric(sub(\"^([0-9]+)\\\\..*\", \"\\\\1\", names(datapoints)[d])) - xwidth/2\n } else {\n x = rescale_num(x, to = c(0, xwidth))\n x = x + d - xwidth/2\n }\n \n x = c(x, NA)\n y = c(y, NA)\n \n out = data.frame(\n by = dat$by[1], # already split\n facet = dat$facet[1], # already split\n y = y,\n x = x\n )\n return(out)\n })\n datapoints = do.call(rbind, datapoints)\n datapoints = datapoints[1:(nrow(datapoints)-1), ]\n \n out = list(\n datapoints = datapoints,\n by = if (length(unique(datapoints$by)) == 1) by else datapoints$by, \n facet = if (length(unique(datapoints$facet)) == 1) facet else datapoints$facet,\n ylab = ylab,\n xlabs = xlabs,\n col = col,\n bg = bg\n )\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_spineplot.R", "#' Spineplot and spinogram types\n#'\n#' @description Type function(s) for producing spineplots and spinograms, which\n#' are modified versions of histograms or mosaic plots, and particularly\n#' useful for visualizing factor variables. Note that [`tinyplot`] defaults\n#' to `type_spineplot()` if `y` is a factor variable.\n#' @param xlevels,ylevels a character or numeric vector specifying the ordering of the\n#' levels of the `x` and `y` variables (if character) or the corresponding indexes\n#' (if numeric) for the plot.\n#' @inheritParams graphics::spineplot\n#' @examples\n#' # \"spineplot\" type convenience string\n#' tinyplot(Species ~ Sepal.Width, data = iris, type = \"spineplot\")\n#' \n#' # Aside: specifying the type is redundant for this example, since tinyplot()\n#' # defaults to \"spineplot\" if y is a factor (just like base plot).\n#' tinyplot(Species ~ Sepal.Width, data = iris)\n#' \n#' # Use `type_spineplot()` to pass extra arguments for customization\n#' tinyplot(Species ~ Sepal.Width, data = iris, type = type_spineplot(breaks = 4))\n#' \n#' p = palette.colors(3, \"Pastel 1\")\n#' tinyplot(Species ~ Sepal.Width, data = iris, type = type_spineplot(breaks = 4, col = p))\n#' rm(p)\n#' \n#' # More idiomatic tinyplot way of drawing the previous plot: use y == by\n#' tinyplot(\n#' Species ~ Sepal.Width | Species, data = iris, type = type_spineplot(breaks = 4),\n#' palette = \"Pastel 1\", legend = FALSE\n#' )\n#' \n#' # Grouped and faceted spineplots\n#' \n#' ttnc = as.data.frame(Titanic)\n#' \n#' tinyplot(\n#' Survived ~ Sex, facet = ~ Class, data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq)\n#' )\n#' \n#' # For grouped \"by\" spineplots, it's better visually to facet as well\n#' tinyplot(\n#' Survived ~ Sex | Class, facet = \"by\", data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq)\n#' )\n#' \n#' # Fancier version. Note the smart inheritance of spacing etc.\n#' tinyplot(\n#' Survived ~ Sex | Class, facet = \"by\", data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq),\n#' palette = \"Dark 2\", facet.args = list(nrow = 1), axes = \"t\"\n#' )\n#'\n#' # Reorder x and y variable categories either by their character levels or numeric indexes\n#' tinyplot(\n#' Survived ~ Sex, facet = ~ Class, data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq, xlevels = c(\"Female\", \"Male\"), ylevels = 2:1)\n#' )\n#'\n#' # Note: It's possible to use \"by\" on its own (without faceting), but the\n#' # overlaid result isn't great. We will likely overhaul this behaviour in a\n#' # future version of tinyplot...\n#' tinyplot(Survived ~ Sex | Class, data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq), alpha = 0.3\n#' )\n#' \n#' @export\ntype_spineplot = function(breaks = NULL, tol.ylab = 0.05, off = NULL, xlevels = NULL, ylevels = NULL, col = NULL, xaxlabels = NULL, yaxlabels = NULL, weights = NULL) {\n col = col\n out = list(\n data = data_spineplot(off = off, breaks = breaks, xlevels = xlevels, ylevels = ylevels, xaxlabels = xaxlabels, yaxlabels = yaxlabels, weights = weights),\n draw = draw_spineplot(tol.ylab = tol.ylab, off = off, col = col, xaxlabels = xaxlabels, yaxlabels = yaxlabels),\n name = \"spineplot\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n#' @importFrom grDevices nclass.Sturges\ndata_spineplot = function(off = NULL, breaks = NULL, xlevels = xlevels, ylevels = ylevels, xaxlabels = NULL, yaxlabels = NULL, weights = NULL) {\n fun = function(\n datapoints,\n by = NULL, col = NULL, bg = NULL, palette = NULL,\n facet = NULL, facet.args = NULL,\n xlim = NULL, ylim = NULL,\n axes = TRUE, xaxt = NULL, yaxt = NULL, xaxb = NULL, yaxb = NULL,\n null_by, null_facet, \n ...\n ) {\n \n ## process weights\n if (!is.null(weights)) {\n ny = length(datapoints$y)\n if (length(weights) != ny && length(weights) != 1L) {\n stop(sprintf(\"'weights' must have either length 1 or %s\", ny))\n }\n }\n datapoints$weights = weights\n \n ## process x variable\n if (is.factor(datapoints$x)) {\n breaks = NULL\n off = if(is.null(off)) 0.02 else off/100\n if (is.null(xlim)) xlim = c(0, 1 + (nlevels(datapoints$x) - 1L) * off)\n } else {\n off = 0\n if (is.null(xlim)) xlim = c(0, 1)\n \t x = as.numeric(datapoints$x)\n if (is.null(breaks)) {\n breaks = if (!is.null(xaxb)) xaxb else if (is.null(weights)) nclass.Sturges(x) else ceiling(log2(sum(weights)) + 1)\n\t }\n breaks = as.numeric(breaks)\n if (length(breaks) == 1L) {\n if (!is.numeric(breaks) || !is.finite(breaks) || breaks < 1L) stop(\"invalid number of 'breaks'\")\n if (breaks > 1e6) {\n warning(gettextf(\"'breaks = %g' is too large and set to 1e6\", breaks))\n breaks = 1000000L\n }\n rg = if (is.null(weights)) range(x, na.rm = TRUE) else range(x[weights > 0], na.rm = TRUE)\n breaks = pretty(rg, n = breaks, min.n = 1L) \n }\n }\n\n ## process y variable\n if (!is.factor(datapoints$y)) datapoints$y = factor(datapoints$y)\n if (is.null(ylim)) ylim = c(0, 1)\n\n ## adjust facet margins\n if (!is.null(facet) && is.null(facet.args[[\"fmar\"]])) {\n facet.args[[\"fmar\"]] = c(2, 2, 2, 2)\n }\n \n x_by = identical(datapoints$x, datapoints$by)\n y_by = identical(datapoints$y, datapoints$by)\n \n x.categorical = is.factor(datapoints$x)\n if (!is.null(xlevels) && x.categorical) {\n xlevels = if(is.numeric(xlevels)) levels(datapoints$x)[xlevels] else xlevels\n if (any(is.na(xlevels)) || !all(xlevels %in% levels(datapoints$x))) warning(\"not all 'xlevels' correspond to levels of 'x'\")\n datapoints$x = factor(datapoints$x, levels = xlevels)\n if (x_by) datapoints$by = datapoints$x\n }\n if (!is.null(ylevels)) {\n ylevels = if(is.numeric(ylevels)) levels(datapoints$y)[ylevels] else ylevels\n if (any(is.na(ylevels)) || !all(ylevels %in% levels(datapoints$y))) warning(\"not all 'ylevels' correspond to levels of 'y'\")\n datapoints$y = factor(datapoints$y, levels = ylevels)\n if (y_by) datapoints$by = datapoints$y\n }\n \n x = datapoints$x\n y = datapoints$y\n \n # if either x_by or y_by are TRUE, we'll only split by facets and then\n # use some simple logic to assign colouring on the backend\n if (isTRUE(x_by) || isTRUE(y_by)) {\n datapoints = split(datapoints, list(datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n } else {\n datapoints = split(datapoints, list(datapoints$by, datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n }\n \n # construct spineplot rectangles and breaks points for each by-facet combo\n datapoints = Map(function(dat, x.categorical, off) {\n ## set up frequency table\n x = dat$x\n if(!x.categorical) {\n x = cut(as.numeric(x), breaks = breaks, include.lowest = TRUE)\n }\n ## TODO: process by grouping via: interaction + spacing + labeling\n ## (for now just do interaction)\n ## FIXME: data_facet only contains the first by group?\n ## if (any(dat$by != \"\")) x = interaction(dat$by, x)\n if(is.null(dat$weights)) {\n tab = table(x, dat$y)\n } else {\n tab = as.table(tapply(dat$weights, list(x, dat$y), FUN = sum, na.rm = TRUE))\n tab[is.na(tab)] = 0\n }\n nx = nrow(tab)\n ny = ncol(tab)\n \n ## compute coordinates\n ## cumulative proportions of x (plus off) vs. conditional cumulative proportions of y\n yat = rbind(0, apply(proportions(tab[, ny:1L, drop = FALSE], 1L), 1L, cumsum))\n yat[is.na(yat)] = 1\n xat = c(0, cumsum(proportions(marginSums(tab, 1L)) + off))\n \n ybottom = as.vector(yat[-(ny + 1L),])\n ytop = as.vector(yat[-1L,])\n xleft = rep(xat[1L:nx], rep(ny, nx))\n xright = rep(xat[2L:(nx+1L)] - off, rep(ny, nx))\n \n out = data.frame(\n by = dat$by[1], # already split\n facet = dat$facet[1], # already split\n ymin = ybottom,\n ymax = ytop,\n xmin = xleft,\n xmax = xright\n )\n \n attr(out, \"nx\") = nx\n attr(out, \"ny\") = ny\n attr(out, \"xat\") = xat\n attr(out, \"yat\") = yat\n return(out)\n }, \n dat = datapoints,\n x.categorical = x.categorical,\n off = off\n )\n \n nx = attr(datapoints[[1]], \"nx\") ## should be the same for all by/facet groups\n ny = attr(datapoints[[1]], \"ny\") ## ditto\n xat = lapply(datapoints, attr, \"xat\")\n yat = lapply(datapoints, attr, \"yat\")\n datapoints = do.call(rbind, datapoints)\n \n if (is.null(yaxlabels)) yaxlabels = rev(levels(y))\n \n ## axis labels\n yaxlabels = if(is.null(yaxlabels)) levels(y) else rep_len(yaxlabels, ny)\n if (!is.null(yaxb)) {\n # yaxlabels = yaxlabels[yaxlabels %in% yaxb]\n ## rather use the \"\" assignment workaround below, since otherwise we \n ## get a mismatch between the label names and ticks \n yaxlabels[!(yaxlabels %in% yaxb)] = \"\"\n }\n if(x.categorical) {\n xaxlabels = if(is.null(xaxlabels)) {\n levels(x)\n } else {\n rep_len(xaxlabels, nx)\n }\n } else {\n xaxlabels = if(is.null(xaxlabels)) {\n if(is.numeric(x)) breaks else c(x[1L], x[c(diff(as.numeric(x)) > 0, TRUE)])\n } else {\n rep_len(xaxlabels, nx + 1L)\n }\n }\n \n # catch for x_by / y/by\n if (isTRUE(x_by)) datapoints$by = factor(rep(xaxlabels, each = ny)) # each x label extends over ny rows\n if (isTRUE(y_by)) datapoints$by = factor(rep(yaxlabels, length.out = nrow(datapoints)))\n \n ## grayscale flag\n grayscale = null_by && is.null(palette) && is.null(.tpar[[\"palette.qualitative\"]])\n \n out = list(\n x = c(datapoints$xmin, datapoints$xmax), \n y = c(datapoints$ymin, datapoints$ymax),\n ymin = datapoints$ymin, \n ymax = datapoints$ymax, \n xmin = datapoints$xmin, \n xmax = datapoints$xmax, \n col = col,\n bg = bg,\n datapoints = datapoints,\n by = if (null_by) by else datapoints$by, \n facet = if (null_facet) facet else datapoints$facet,\n axes = FALSE,\n frame.plot = FALSE,\n xaxt = \"n\",\n yaxt = \"n\",\n xaxs = \"i\",\n yaxs = \"i\",\n ylabs = yaxlabels,\n type_info = list(\n off = off,\n x.categorical = x.categorical,\n nx = nx,\n ny = ny,\n xat = xat,\n yat = yat,\n xaxlabels = xaxlabels,\n yaxlabels = yaxlabels,\n breaks = breaks,\n axes = axes,\n xaxt = xaxt, \n yaxt = yaxt,\n grayscale = grayscale,\n x_by = x_by,\n y_by = y_by\n ),\n facet.args = facet.args\n )\n \n return(out)\n \n }\n return(fun)\n}\n\n#' @importFrom grDevices gray.colors\ndraw_spineplot = function(tol.ylab = 0.05, off = NULL, col = NULL, xaxlabels = NULL, yaxlabels = NULL) {\n fun = function(ixmin, iymin, ixmax, iymax, ilty, ilwd, icol, ibg, \n flip,\n facet_window_args,\n type_info,\n ifacet,\n ...) {\n \n if (is.null(off)) off = type_info[[\"off\"]]\n if (is.null(xaxlabels)) xaxlabels = type_info[[\"xaxlabels\"]]\n if (is.null(yaxlabels)) yaxlabels = type_info[[\"yaxlabels\"]]\n xat = type_info[[\"xat\"]][[ifacet]]\n yat = type_info[[\"yat\"]][[ifacet]]\n nx = type_info[[\"nx\"]]\n ny = type_info[[\"ny\"]]\n x.categorical = type_info[[\"x.categorical\"]]\n grayscale = type_info[[\"grayscale\"]]\n x_by = type_info[[\"x_by\"]]\n y_by = type_info[[\"y_by\"]]\n \n ## graphical parameters\n if (is.null(col)) {\n if (is.null(ibg)) ibg = icol\n if (isFALSE(y_by)) {\n ibg = if (isTRUE(grayscale)) gray.colors(ny) else seq_palette(ibg, ny)\n }\n ibg = rep_len(ibg, ny)\n } else {\n ibg = col\n }\n \n if (type_info[[\"xaxt\"]] %in% c(\"l\", \"t\", \"n\") &&\n type_info[[\"yaxt\"]] %in% c(\"l\", \"t\", \"n\") &&\n !all(c(type_info[[\"xaxt\"]], type_info[[\"yaxt\"]]) == \"n\")) ilwd = 0\n \n rect(\n xleft = ixmin, ybottom = iymin, xright = ixmax, ytop = iymax,\n lty = ilty,\n lwd = ilwd,\n border = par(\"fg\"), #icol,\n col = ibg\n )\n \n ## axes\n ## - standard categorical axes (xaxt/yaxt == \"s\") _without_ ticks\n ## - never draw additional axis lines, box always for spinogram\n if(type_info[[\"axes\"]]) {\n if (x.categorical) {\n spine_axis(if (flip) 2 else 1, at = (xat[1L:nx] + xat[2L:(nx+1L)] - off)/2, labels = xaxlabels,\n type = type_info[[\"xaxt\"]], categorical = TRUE)\n } else {\n spine_axis(if (flip) 2 else 1, at = xat, labels = xaxlabels,\n type = type_info[[\"xaxt\"]], categorical = FALSE)\n }\n yat = yat[, if(flip) ncol(yat) else 1L]\n equidist = any(diff(yat) < tol.ylab)\n yat = if(equidist) seq.int(1/(2*ny), 1-1/(2*ny), by = 1/ny) else (yat[-1L] + yat[-length(yat)])/2\n spine_axis(if (flip) 3 else 2, at = yat, labels = yaxlabels,\n type = type_info[[\"yaxt\"]], categorical = TRUE)\n if (is_facet_position(if(flip) \"bottom\" else \"right\", ifacet, facet_window_args)) spine_axis(if (flip) 1 else 4,\n type = type_info[[\"yaxt\"]], categorical = FALSE)\n }\n if(!x.categorical && (is.null(ilwd) || ilwd > 0)) box()\n \n }\n return(fun)\n}\n\n\n\n\nspine_axis = function(side, ..., type = \"standard\", categorical = TRUE) {\n type = match.arg(type, c(\"standard\", \"none\", \"labels\", \"ticks\", \"axis\"))\n ## standard: with axis, ticks (unless categorical), and labels\n ## none: no axes\n ## labels: only labels without ticks and axis line\n ## ticks: only ticks and labels without axis line\n ## axis: only axis line and labels but no ticks\n\n if (type == \"none\") {\n invisible(numeric(0L))\n } else {\n args = list(side = side, ...)\n if (type == \"labels\") {\n args$tick = FALSE\n } else if (type == \"ticks\") {\n args$lwd = 0\n if (!(\"lwd.ticks\" %in% names(args))) args$lwd.ticks = if (categorical) 0 else 1\n } else if (type == \"axis\") {\n if (categorical) {\n args$tick = FALSE\n } else {\n args$lwd.ticks = 0\n }\n } else {\n args$tick = !categorical\n }\n do.call(\"axis\", args)\n }\n}\n\n#' @importFrom grDevices col2rgb convertColor hcl\nto_hcl = function(x) {\n x = t(col2rgb(x, alpha = TRUE)/255)\n alpha = x[, 4]\n x = x[, 1:3]\n x = convertColor(x, from = \"sRGB\", to = \"Luv\")\n x = cbind(H = atan2(x[, 3L], x[, 2L]) * 180/pi, C = sqrt(x[, 2L]^2 + x[, 3L]^2), L = x[, 1L])\n x[is.na(x[, 1L]), 1L] = 0\n x[x[, 1L] < 0, 1L] = x[x[, 1L] < 0, 1L] + 360\n attr(x, \"alpha\") = alpha\n return(x)\n}\n\nseq_palette = function(x, n, power = 1.5) {\n x = drop(to_hcl(x[1L]))\n alpha = attr(x, \"alpha\")\n hcl(\n h = x[1L],\n c = seq.int(from = x[2L]^(1/power), to = 0, length.out = n + 1)[1L:n]^power,\n l = 100 - seq.int(from = (100 - x[3L])^(1/power), to = pmin(8, (100 - x[3L])/2)^(1/power), length.out = n)^power,\n alpha = alpha\n )[1L:n]\n}\n"], ["/tinyplot/R/type_barplot.R", "#' Barplot type\n#'\n#' @description Type function for producing barplots. For formulas of type\n#' `~ x` (without left-hand side) the barplot visualizes the counts (absolute\n#' frequencies) of the levels of `x`. For formulas of type `y ~ x` the value\n#' of `y` within each level of `x` is visualized, if necessary aggregated\n#' using some function (default: mean).\n#'\n#' @param width numeric, optional vector of bar widths. (The distance between\n#' the midpoints of the bars is always 1.)\n#' @param beside logical. In case of a `by` grouping variable, should bars be\n#' juxtaposed? Default is to use stacked bars instead.\n#' @param center logical or numeric. In case of stacked barplots (`beside = FALSE`)\n#' should the bars be centered (or all start at zero, default)? If set to\n#' `TRUE` the center is at the mid-point of the middle category (in case of\n#' uneven number of categories) or between the two middle categories (in case\n#' of an even number). Additionally it is possible to set `center = 2` or\n#' `center = 2.5` to indicate that centering should be after the second category\n#' or the mid-way in the third category, respectively.\n#' @param FUN a function to compute the summary statistic for `y` within each\n#' group of `x` in case of using a two-sided formula `y ~ x` (default: mean).\n#' @param xlevels a character or numeric vector specifying the ordering of the\n#' levels of the `x` variable (if character) or the corresponding indexes\n#' (if numeric) for the plot.\n#' @param xaxlabels a character vector with the axis labels for the `x` variable,\n#' defaulting to the levels of `x`.\n#' @param drop.zeros logical. Should bars with zero height be dropped? If set\n#' to `FALSE` (default) a zero height bar is still drawn for which the border\n#' lines will still be visible.\n#'\n#' @examples\n#' # Basic examples of frequency tables (without y variable)\n#' tinyplot(~ cyl, data = mtcars, type = \"barplot\")\n#' tinyplot(~ cyl | vs, data = mtcars, type = \"barplot\")\n#' tinyplot(~ cyl | vs, data = mtcars, type = \"barplot\", beside = TRUE)\n#' tinyplot(~ cyl | vs, data = mtcars, type = \"barplot\", beside = TRUE, fill = 0.2)\n#' \n#' # Reorder x variable categories either by their character levels or numeric indexes\n#' tinyplot(~ cyl, data = mtcars, type = \"barplot\", xlevels = c(\"8\", \"6\", \"4\"))\n#' tinyplot(~ cyl, data = mtcars, type = \"barplot\", xlevels = 3:1)\n#' \n#' # Note: Above we used automatic argument passing for `beside`. But this\n#' # wouldn't work for `width`, since it would conflict with the top-level\n#' # `tinyplot(..., width = )` argument. It's safer to pass these args\n#' # through the `type_barplot()` functional equivalent.\n#' tinyplot(~ cyl | vs, data = mtcars, fill = 0.2,\n#' type = type_barplot(beside = TRUE, drop.zeros = TRUE, width = 0.65))\n#'\n#' tinytheme(\"clean2\")\n#' \n#' # Example for numeric y aggregated by x (default: FUN = mean) + facets\n#' tinyplot(extra ~ ID | group, facet = \"by\", data = sleep,\n#' type = \"barplot\", fill = 0.6)\n#' \n#' # Fancy frequency table:\n#' tinyplot(Freq ~ Sex | Survived, facet = ~ Class, data = as.data.frame(Titanic),\n#' type = \"barplot\", facet.args = list(nrow = 1), flip = TRUE, fill = 0.6)\n#'\n#' # Centered barplot for conditional proportions of hair color (black/brown vs.\n#' # red/blond) given eye color and sex\n#' tinytheme(\"clean2\", palette.qualitative = c(\"black\", \"sienna\", \"indianred\", \"goldenrod\"))\n#' hec = as.data.frame(proportions(HairEyeColor, 2:3))\n#' tinyplot(Freq ~ Eye | Hair, facet = ~ Sex, data = hec, type = \"barplot\",\n#' center = TRUE, flip = TRUE, facet.args = list(ncol = 1), yaxl = \"percent\")\n#'\n#' tinytheme()\n#' \n#' @export\ntype_barplot = function(width = 5/6, beside = FALSE, center = FALSE, FUN = NULL, xlevels = NULL, xaxlabels = NULL, drop.zeros = FALSE) {\n out = list(\n data = data_barplot(width = width, beside = beside, center = center, FUN = FUN, xlevels = xlevels, xaxlabels = xaxlabels, drop.zeros = drop.zeros),\n draw = draw_rect(),\n name = \"barplot\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n#' @importFrom stats aggregate\ndata_barplot = function(width = 5/6, beside = FALSE, center = FALSE, FUN = NULL, xlevels = NULL, xaxlabels = NULL, drop.zeros = FALSE) {\n fun = function(datapoints, col, bg, lty, lwd, palette, xlab = NULL, ylab = NULL, xlim = NULL, ylim = NULL, xaxt = NULL, yaxl = NULL, yaxt = NULL, axes = TRUE, null_by, facet_by, ...) {\n\n \n ## tabulate/aggregate datapoints\n if (is.null(datapoints$y)) {\n xlab = ylab\n ylab = \"Count\"\n \n datapoints$y = numeric(nrow(datapoints)) \n if (!is.null(FUN)) warning(\"without 'y' variable 'FUN' specification is ignored\")\n FUN = length\n } else {\n if (is.null(FUN)) FUN = function(x, ...) mean(x, ..., na.rm = TRUE)\n }\n if (!is.factor(datapoints$x)) datapoints$x = factor(datapoints$x)\n if (!is.null(xlevels)) {\n xlevels = if(is.numeric(xlevels)) levels(datapoints$x)[xlevels] else xlevels\n if (any(is.na(xlevels)) || !all(xlevels %in% levels(datapoints$x))) warning(\"not all 'xlevels' correspond to levels of 'x'\")\n datapoints$x = factor(datapoints$x, levels = xlevels)\n }\n if (!is.null(xaxlabels)) levels(datapoints$x) <- xaxlabels\n datapoints = aggregate(datapoints[, \"y\", drop = FALSE], datapoints[, c(\"x\", \"by\", \"facet\")], FUN = FUN, drop = FALSE)\n datapoints$y[is.na(datapoints$y)] = 0 #FIXME: always?#\n if (!is.factor(datapoints$by)) datapoints$by = factor(datapoints$by)\n if (!is.factor(datapoints$facet)) datapoints$facet = factor(datapoints$facet)\n \n if (isFALSE(null_by) && isFALSE(facet_by) && !beside && any(datapoints$y < 0)) {\n warning(\"'beside' must be TRUE if there are negative 'y' values\")\n beside = TRUE\n }\n if (beside & !isFALSE(center)) {\n warning(\"'center' is currently only supported for 'beside = FALSE'\")\n }\n offset_sum = function(z, center = TRUE, na.rm = TRUE) {\n n = length(z)\n if (isFALSE(center) || n < 1L) return(0)\n mid = if (isTRUE(center)) n/2 else center\n z[floor(mid) + 1L] = (mid - floor(mid)) * z[floor(mid) + 1L]\n sum(z[0L:floor(mid) + 1L], na.rm = TRUE)\n }\n if (is.null(xlim)) xlim = c(1, length(levels(datapoints$x))) + c(-0.5, 0.5) * width\n if (is.null(ylim)) ylim = if (beside || length(unique(datapoints$by)) == 1L) {\n c(pmin(0, min(datapoints$y, na.rm = TRUE) * 1.02), pmax(0, max(datapoints$y, na.rm = TRUE) * 1.02))\n } else {\n range(unlist(tapply(\n datapoints$y,\n interaction(datapoints$x, datapoints$facet),\n function(z) c(0, sum(z, na.rm = TRUE)) - offset_sum(z, center = center)\n ))) * 1.02\n }\n\n ## default color palette\n ngrps = length(unique(datapoints$by))\n if (ngrps == 1L && is.null(palette)) {\n if (is.null(col)) col = par(\"fg\")\n if (is.null(bg)) bg = \"grey\"\n } else {\n if (is.null(bg)) bg = \"by\"\n }\n\n ## calculate bar rectangles per facet \n sdat = split(datapoints, datapoints$facet)\n datapoints = lapply(sdat, function(df) {\n \n df = df[order(df$x), , drop = FALSE]\n nx = length(levels(df$x))\n nb = length(levels(df$by))\n \n if (beside) { \n xl = as.numeric(df$x) - width/2 + (as.numeric(df$by) - 1) * width/nb * as.numeric(!facet_by)\n xr = if (facet_by) xl + width else xl + width/nb\n yb = 0\n yt = df$y\n } else {\n cs = tapply(df$y, df$x, function(z) cumsum(c(0, z)) - offset_sum(z, center = center))\n xl = as.numeric(df$x) - width/2\n xr = xl + width\n yb = if (facet_by) 0 else unlist(lapply(cs, `[`, -(nb + 1L)))\n yt = if (facet_by) df$y else unlist(lapply(cs, `[`, -1L))\n }\n \n df$xmin = xl\n df$xmax = xr\n df$ymin = yb\n df$ymax = yt\n df$nx = nx\n \n if (drop.zeros) {\n yb = rep_len(yb, length(yt))\n yok = abs(yt - yb) > 0\n df = df[yok, , drop = FALSE]\n }\n \n return(df)\n })\n datapoints = do.call(\"rbind\", datapoints)\n nx = datapoints$nx[1]\n datapoints$nx = NULL\n xlabs = 1L:nx\n names(xlabs) = levels(datapoints$x)\n \n if (!isFALSE(center)) {\n if (is.null(yaxl)) {\n yaxl = abs\n } else if (is.character(yaxl)) {\n yaxl = paste0(\"abs_\", yaxl)\n }\n }\n \n out = list(\n datapoints = datapoints,\n xlab = xlab,\n ylab = ylab,\n xlim = xlim,\n ylim = ylim,\n axes = FALSE, #FIXME\n axes = TRUE,\n xlabs = xlabs, \n frame.plot = FALSE,\n xaxs = \"r\",\n xaxt = if (xaxt == \"s\") \"l\" else xaxt,\n yaxl = yaxl,\n yaxs = \"i\",\n col = col,\n bg = bg\n )\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_ridge.R", "#' Ridge plot type\n#'\n#' @description Type function for producing ridge plots (also known as joy plots),\n#' which display density distributions for multiple groups with vertical offsets.\n#' This function uses `tinyplot` scaffolding, which enables added functionality\n#' such as grouping and faceting.\n#'\n#' The line color is controlled by the `col` argument in the `tinyplot()` call.\n#' The fill color is controlled by the `bg` argument in the `tinyplot()` call.\n#'\n#' @param scale Numeric. Controls the scaling factor of each plot.\n#' Values greater than 1 means that plots overlap.\n#' @param joint.max character indicating how to scale the maximum of the densities:\n#' The default `\"all\"` indicates that all densities are scaled jointly relative to\n#' the same maximum so that the areas of all densities are comparable.\n#' Alternatively, `\"facet\"` indicates that the maximum is computed within\n#' each facet so that the areas of the densities are comparable within each\n#' facet but not necessarily across facets. Finally, `\"by\"` indicates that\n#' each row (in each facet) is scaled separately, so that the areas of the\n#' densities for `by` groups in the same row are comparable but not necessarily\n#' across rows.\n#' @param breaks Numeric. If a color gradient is used for shading, the\n#' breaks between the colors can be modified. The default is to use\n#' equidistant breaks spanning the range of the `x` variable.\n#' @param probs Numeric. Instead of specifying the same `breaks` on the\n#' x-axis for all groups, it is possible to specify group-specific quantiles\n#' at the specified `probs`. The quantiles are computed based on the density\n#' (rather than the raw original variable). Only one of `breaks` or\n#' `probs` must be specified.\n#' @param ylevels a character or numeric vector specifying in which order\n#' the levels of the y-variable should be plotted.\n#' @inheritParams stats::density\n#' @param kernel a character string giving the smoothing kernel to be used. This\n#' must partially match one of `\"gaussian\"`, `\"rectangular\"`, `\"triangular\"`,\n#' `\"epanechnikov\"`, `\"biweight\"`, `\"cosine\"` or `\"optcosine\"`, with default\n#' `\"gaussian\"`, and may be abbreviated to a unique prefix (single letter).\n#'\n#' `\"cosine\"` is smoother than `\"optcosine\"`, which is the usual 'cosine'\n#' kernel in the literature and almost MSE-efficient. However, `\"cosine\"` is\n#' the version used by S.\n#' @param joint.bw character string indicating whether (and how) the smoothing\n#' bandwidth should be computed from the joint data distribution. The default\n#' of `\"mean\"` will compute the joint bandwidth as the mean of the individual\n#' subgroup bandwidths (weighted by their number of observations). Choosing\n#' `\"full\"` will result in a joint bandwidth computed from the full\n#' distribution (merging all subgroups). For `\"none\"` the individual bandwidth\n#' will be computed independently for each subgroup. Also accepts a logical\n#' argument, where `TRUE` maps to `\"mean\"` and `FALSE` maps to `\"none\"`. See\n#' \\code{\\link{type_density}} for some discussion of practical considerations.\n#' @param gradient Logical or character. Should a gradient fill be used to\n#' shade the area under the density? If a character specification is used,\n#' then it can either be of length 1 and specify the palette to be used with\n#' `gradient = TRUE` corresponding to `gradient = \"viridis\"`. If a character\n#' vector of length greater than 1 is used, then it should specify the\n#' colors in the palette, e.g., `gradient = hcl.colors(512)`.\n#' @param raster Logical. Should the `gradient` fill be drawn using\n#' \\code{\\link[graphics]{rasterImage}}? Defaults to `FALSE`, in which case the\n#' `gradient` fill will instead be drawn using\n#' \\code{\\link[graphics]{polygon}}. See the `Technical note on gradient fills`\n#' section below.\n#' @param col Character string denoting the outline (border) color for all\n#' of the ridge densities. Note that a singular value is expected; if multiple\n#' colors are provided then only the first will be used. This argument is mostly\n#' useful for the aesthetic effect of drawing a common outline color in\n#' combination with gradient fills. See Examples.\n#' @param alpha Numeric in the range `[0,1]` for adjusting the alpha\n#' transparency of the density fills. In most cases, will default to a value of\n#' 1, i.e. fully opaque. But for some `by` grouped plots (excepting the special\n#' cases where `by==y` or `by==x`), will default to 0.6.\n#' \n#' @section Technical note on gradient fills:\n#' \n#' `tinyplot` uses two basic approaches for drawing gradient fills in ridge line\n#' plots, e.g., if `type_ridge(gradient = TRUE)`.\n#' \n#' The first (and default) polygon-based approach involves dividing up the main\n#' density region into many smaller polygons along the x-axis. Each of these\n#' smaller polygons inherits a different color \"segment\" from the underlying\n#' palette swatch, which in turn creates the effect of a continuous gradient\n#' when they are all plotted together. Internally, this polygon-based approach\n#' is vectorized (i.e., all of the sub-polygons are plotted simultaneously). It\n#' is thus efficient from a plotting perspective and generally also performs\n#' well from an aesthetic perspective. However, it can occasionally produce\n#' undesirable plotting artifacts on some graphics devices---e.g., thin but\n#' visible vertical lines---if alpha transparency is being used at the same \n#' time.\n#' \n#' For this reason, we also offer an alternative raster-based approach for\n#' gradient fills that users can invoke via\n#' `type_ridge(gradient = TRUE, raster = TRUE)`. The essential idea is that we\n#' coerce the density polygon into a raster representation (using\n#' \\code{\\link[graphics]{rasterImage}}) and achieve the gradient effect via\n#' color interpolation. The trade-off this time is potential smoothness\n#' artifacts around the top of the ridge densities at high resolutions, since we\n#' have converted a vector object into a raster object.\n#' \n#' Again, we expect that the choice between these two approaches will only\n#' matter for ridge plots that combine gradient fills with alpha transparency\n#' (and on certain graphics devices). We recommend that users experiment to\n#' determine which approach is optimal for their device.\n#'\n#' @examples\n#' aq = transform(\n#' airquality,\n#' Month = factor(month.abb[Month], levels = month.abb[5:9]),\n#' Month2 = factor(month.name[Month], levels = month.name[5:9]),\n#' Late = ifelse(Day > 15, \"Late\", \"Early\")\n#' )\n#' \n#' # default ridge plot (using the \"ridge\" convenience string)\n#' tinyplot(Month ~ Temp, data = aq, type = \"ridge\")\n#' \n#' # for ridge plots, we recommend pairing with the dedicated theme(s), which\n#' # facilitate nicer y-axis labels, grid lines, etc.\n#' \n#' tinytheme(\"ridge\")\n#' tinyplot(Month ~ Temp, data = aq, type = \"ridge\")\n#' \n#' tinytheme(\"ridge2\") # removes the plot frame (but keeps x-axis line)\n#' tinyplot(Month ~ Temp, data = aq, type = \"ridge\")\n#' \n#' # the \"ridge(2)\" themes are especially helpful for long y labels, due to\n#' # dyanmic plot adjustment\n#' tinyplot(Month2 ~ Temp, data = aq, type = \"ridge\")\n#' \n#' # pass customization arguments through type_ridge()... for example, use\n#' # the scale argument to change/avoid overlap of densities (more on scaling\n#' # further below)\n#' \n#' tinyplot(Month ~ Temp, data = aq, type = type_ridge(scale = 1))\n#' \n#' ## by grouping is also supported. two special cases of interest:\n#'\n#' # 1) by == y (color by y groups)\n#' tinyplot(Month ~ Temp | Month, data = aq, type = \"ridge\")\n#'\n#' # 2) by == x (gradient coloring along x)\n#' tinyplot(Month ~ Temp | Temp, data = aq, type = \"ridge\")\n#'\n#' # aside: pass explicit `type_ridge(col = )` arg to set a different\n#' # border color\n#' tinyplot(Month ~ Temp | Temp, data = aq, type = type_ridge(col = \"white\"))\n#'\n#' # gradient coloring along the x-axis can also be invoked manually without\n#' # a legend (the next two tinyplot calls are equivalent)\n#' \n#' # tinyplot(Month ~ Temp, data = aq, type = type_ridge(gradient = \"agsunset\"))\n#' tinyplot(Month ~ Temp, data = aq, type = type_ridge(gradient = TRUE))\n#' \n#' # aside: when combining gradient fill with alpha transparency, it may be\n#' # better to use the raster-based approach (test on your graphics device)\n#' \n#' tinyplot(Month ~ Temp, data = aq,\n#' type = type_ridge(gradient = TRUE, alpha = 0.5),\n#' main = \"polygon fill (default)\")\n#' tinyplot(Month ~ Temp, data = aq,\n#' type = type_ridge(gradient = TRUE, alpha = 0.5, raster = TRUE),\n#' main = \"raster fill\")\n#'\n#' # highlighting only the center 50% of the density (i.e., 25%-75% quantiles)\n#' tinyplot(Month ~ Temp, data = aq, type = type_ridge(\n#' gradient = hcl.colors(3, \"Dark Mint\")[c(2, 1, 2)],\n#' probs = c(0.25, 0.75), col = \"white\"))\n#'\n#' # highlighting the probability distribution by color gradient\n#' # (darkest point = median)\n#' tinyplot(Month ~ Temp, data = aq, type = type_ridge(\n#' gradient = hcl.colors(250, \"Dark Mint\")[c(250:1, 1:250)],\n#' probs = 0:500/500))\n#'\n#' # faceting also works, although we recommend switching (back) to the \"ridge\"\n#' # theme for faceted ridge plots\n#' \n#' tinytheme(\"ridge\")\n#' tinyplot(Month ~ Ozone, facet = ~ Late, data = aq,\n#' type = type_ridge(gradient = TRUE))\n#' \n#' ## use the joint.max argument to vary the maximum density used for\n#' ## determining relative scaling...\n#' \n#' # jointly across all densities (default) vs. per facet\n#' tinyplot(Month ~ Temp, facet = ~ Late, data = aq,\n#' type = type_ridge(scale = 1))\n#' tinyplot(Month ~ Temp, facet = ~ Late, data = aq,\n#' type = type_ridge(scale = 1, joint.max = \"facet\"))\n#' \n#' # jointly across all densities (default) vs. per by row\n#' tinyplot(Month ~ Temp | Late, data = aq,\n#' type = type_ridge(scale = 1))\n#' tinyplot(Month ~ Temp | Late, data = aq,\n#' type = type_ridge(scale = 1, joint.max = \"by\"))\n#' \n#' # restore the default theme\n#' tinytheme()\n#'\n#' @export\ntype_ridge = function(\n scale = 1.5,\n joint.max = c(\"all\", \"facet\", \"by\"),\n breaks = NULL,\n probs = NULL,\n ylevels = NULL,\n bw = \"nrd0\",\n joint.bw = c(\"mean\", \"full\", \"none\"),\n adjust = 1,\n kernel = c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"),\n n = 512,\n # more args from density here?\n gradient = FALSE,\n raster = FALSE,\n col = NULL,\n alpha = NULL\n ) {\n \n kernel = match.arg(kernel, c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"))\n if (is.logical(joint.bw)) {\n joint.bw = ifelse(joint.bw, \"mean\", \"none\")\n }\n joint.bw = match.arg(joint.bw, c(\"mean\", \"full\", \"none\"))\n\n out = list(\n draw = draw_ridge(),\n data = data_ridge(bw = bw, adjust = adjust, kernel = kernel, n = n,\n joint.bw = joint.bw,\n scale = scale,\n joint.max = joint.max,\n gradient = gradient,\n breaks = breaks,\n probs = probs,\n ylevels = ylevels,\n raster = raster,\n col = col,\n alpha = alpha\n ),\n name = \"ridge\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n#\n## Underlying data_ridge function\ndata_ridge = function(bw = \"nrd0\", adjust = 1, kernel = \"gaussian\", n = 512,\n joint.bw = \"mean\",\n scale = 1.5,\n joint.max = \"all\",\n gradient = FALSE,\n breaks = NULL,\n probs = NULL,\n ylevels = NULL,\n raster = FALSE,\n col = NULL,\n alpha = NULL\n ) {\n fun = function(datapoints, yaxt = NULL, null_by, ...) {\n # catch for special cases\n anyby = !null_by\n x_by = anyby && identical(datapoints$x, datapoints$by)\n y_by = anyby && identical(datapoints$y, datapoints$by)\n if (x_by) {\n gradient = TRUE\n datapoints$by = \"\"\n } else if (y_by) {\n datapoints$by = \"\"\n } else if (anyby && is.null(alpha)) {\n alpha = 0.6\n }\n # flag for (non-gradient) interior fill adjustment\n fill_by = anyby || y_by\n if (isTRUE(x_by)) fill_by = FALSE\n # if (isTRUE(anyby) && is.null(alpha)) alpha = 0.6\n\n ## reorder levels of y-variable if requested\n if (!is.null(ylevels)) {\n if (!is.factor(datapoints$y)) datapoints$y = factor(datapoints$y)\n datapoints$y = factor(datapoints$y, levels = if(is.numeric(ylevels)) levels(datapoints$y)[ylevels] else ylevels)\n if (y_by) datapoints$by = datapoints$y\n }\n\n ##\n datapoints = split(datapoints, list(datapoints$y, datapoints$by, datapoints$facet))\n\n if (joint.bw == \"none\" || is.numeric(bw)) {\n dens_bw = bw\n } else {\n if (joint.bw == \"mean\") {\n # Use weighted mean of subgroup bandwidths\n bws = sapply(datapoints, function(dat) bw_fun(kernel = bw, dat$x))\n ws = sapply(datapoints, nrow)\n dens_bw = weighted.mean(bws, ws)\n } else if (joint.bw == \"full\") {\n dens_bw = bw_fun(kernel = bw, unlist(sapply(datapoints, `[[`, \"x\")))\n }\n }\n\n datapoints = lapply(datapoints, function(dat) {\n dens = density(dat$x, bw = dens_bw, kernel = kernel, n = n)\n out = data.frame(\n by = dat$by[1], # already split\n facet = dat$facet[1], # already split\n x = dens$x,\n y = dat$y[1],\n ymin = 0L,\n ymax = dens$y\n )\n return(out)\n })\n datapoints = do.call(rbind, datapoints)\n\n if (is.character(joint.max)) {\n joint.max = match.arg(joint.max, c(\"all\", \"facet\", \"by\"))\n joint.max = switch(joint.max,\n \"all\" = rep.int(1, nrow(datapoints)),\n \"facet\" = datapoints$facet,\n \"by\" = interaction(datapoints$facet, datapoints$y)\n )\n joint.max = ave(datapoints$ymax, joint.max, FUN = max)\n }\n datapoints$ymax = datapoints$ymax / joint.max * scale\n\n datapoints = split(datapoints, datapoints$facet)\n offset_z = function(k) {\n ksplit = split(k, k$y)\n for (idx in seq_along(ksplit)) {\n ksplit[[idx]]$ymax = ksplit[[idx]]$ymax + idx - 1\n ksplit[[idx]]$ymin = ksplit[[idx]]$ymin + idx - 1\n }\n k = do.call(rbind, ksplit)\n return(k)\n }\n datapoints = do.call(rbind, lapply(datapoints, offset_z))\n\n if (y_by) {\n datapoints$y = factor(datapoints$y)\n datapoints$by = factor(datapoints$y, levels = rev(levels(datapoints$y)))\n } else if (x_by) {\n datapoints$by = datapoints$x\n }\n\n # Manual breaks flag. Only used if gradient is on\n manbreaks = !is.null(breaks) || !is.null(probs)\n\n ## use color gradient?\n xlim = range(datapoints$x, na.rm = TRUE)\n if (!is.null(probs)) {\n if (!is.null(breaks)) {\n warning(\"only one of 'breaks' and 'quantile' must be specified\")\n probs = NULL\n } else {\n if (probs[1L] > 0) probs = c(0, probs)\n if (probs[length(probs)] < 1) probs = c(probs, 1)\n }\n }\n if (!isFALSE(gradient)) {\n dotspal = list(...)[[\"palette\"]]\n palette = if (!is.null(dotspal)) dotspal else gradient\n gradient = TRUE\n if (isTRUE(palette)) {\n palette = if (!is.null(.tpar[[\"palette.sequential\"]])) .tpar[[\"palette.sequential\"]] else \"viridis\"\n }\n\n if (length(palette) > 1L || !is.character(palette)) {\n ## color vector already given\n if (is.null(breaks) && is.null(probs)) {\n breaks = seq(from = xlim[1L], to = xlim[2L], length.out = length(palette) + 1L)\n } else {\n npal = pmax(length(breaks), length(probs)) - 1L\n if (length(palette) != npal) {\n warning(\"length of 'palette' does not match 'breaks'/'probs'\")\n palette = rep_len(palette, npal)\n }\n if (isTRUE(raster)) raster = npal > 20L\n }\n } else {\n ## only palette name given\n npal = if (is.null(breaks) && is.null(probs)) 512L else pmax(length(breaks), length(probs)) - 1L\n palette = hcl.colors(npal, palette = palette)\n if (is.null(breaks) && is.null(probs)) breaks = seq(from = xlim[1L], to = xlim[2L], length.out = npal + 1L)\n if (isTRUE(raster)) raster = npal > 20L\n }\n } else {\n palette = NULL\n if (!is.null(breaks) || !is.null(probs)) gradient = TRUE\n }\n if (!is.null(breaks)) {\n breaks[1L] = pmin(breaks[1L], xlim[1L])\n breaks[length(breaks)] = pmax(breaks[length(breaks)], xlim[2L])\n }\n \n if (is.null(col) && (!anyby || x_by)) col = \"black\"\n\n out = list(\n datapoints = datapoints,\n yaxt = \"n\",\n ylim = c(min(datapoints$ymin), max(datapoints$ymax)),\n type_info = list(\n gradient = gradient,\n palette = palette,\n breaks = breaks,\n probs = probs,\n manbreaks = manbreaks,\n yaxt = yaxt,\n raster = raster,\n x_by = x_by,\n y_by = y_by,\n fill_by = fill_by,\n col = col,\n alpha = alpha\n )\n )\n return(out)\n }\n return(fun)\n}\n\n\n#\n## Underlying draw_ridge function\ndraw_ridge = function() {\n fun = function(ix, iy, iz, ibg, icol, iymin, iymax, type_info, ...) {\n ridge_theme = identical(.tpar[[\"tinytheme\"]], \"ridge\") || identical(.tpar[[\"tinytheme\"]], \"ridge2\")\n d = data.frame(x = ix, y = iy, ymin = iymin, ymax = iymax)\n dsplit = split(d, d$y)\n if (is.null(ibg)) {\n default_bg = if (!ridge_theme && !is.null(.tpar[[\"palette.qualitative\"]])) seq_palette(by_col(), n = 2)[2] else \"gray\"\n ibg = if (isTRUE(type_info[[\"fill_by\"]])) seq_palette(icol, n = 2)[2] else default_bg\n }\n if (!is.null(type_info[[\"alpha\"]]) && is.null(type_info[[\"palette\"]])) {\n ibg = adjustcolor(ibg, alpha.f = type_info[[\"alpha\"]])\n }\n if (!is.null(type_info[[\"col\"]])) icol = type_info[[\"col\"]]\n lab = if (is.factor(d$y)) levels(d$y) else unique(d$y)\n if (isTRUE(type_info[[\"y_by\"]])) {\n # avoid duplicating the y-axis labs for the special y==by case\n # val = match(lab, levels(d$y)) - 1\n val = match(d$y[1], levels(d$y))\n lab = lab[val]\n val = val - 1\n } else {\n val = cumsum(rep(1, length(lab))) - 1\n }\n if (ridge_theme) abline(h = val, col = .tpar[[\"grid.col\"]])\n draw_segments = if (type_info[[\"raster\"]]) segmented_raster else segmented_polygon\n for (i in rev(seq_along(dsplit))) {\n if (type_info[[\"gradient\"]]) {\n with(\n dsplit[[i]],\n draw_segments(\n x, ymax, ymin = ymin[1L],\n breaks = type_info[[\"breaks\"]],\n probs = type_info[[\"probs\"]],\n manbreaks = type_info[[\"manbreaks\"]],\n col = if (is.null(type_info[[\"palette\"]])) ibg else type_info[[\"palette\"]],\n # border = if (is.null(type_info[[\"palette\"]])) icol else \"transparent\",\n alpha = type_info[[\"alpha\"]]\n )\n )\n }\n with(dsplit[[i]], polygon(x, ymax, col = if (type_info[[\"gradient\"]]) \"transparent\" else ibg, border = NA))\n with(dsplit[[i]], lines(x, ymax, col = icol))\n }\n # tinyAxis(x = d$y, side = 2, at = val, labels = lab, type = type_info[[\"yaxt\"]], padj = padj)\n if (ridge_theme) {\n tinyAxis(x = d$y, side = 2, at = val, labels = lab, type = type_info[[\"yaxt\"]],\n padj = 0,\n mgp = c(3, 1, 0) - c(0.5, 0.5 + 0.3, 0),\n tcl = 0)\n if (identical(.tpar[[\"tinytheme\"]], \"ridge2\")) axis(1, labels = FALSE)\n } else {\n tinyAxis(x = d$y, side = 2, at = val, labels = lab, type = type_info[[\"yaxt\"]])\n }\n }\n return(fun)\n}\n\n\n#\n## Auxiliary functions\n\n## auxiliary function for drawing shaded segmented polygon\nsegmented_polygon = function(x, y, ymin = 0, breaks = range(x), probs = NULL, manbreaks = FALSE, col = \"lightgray\", border = \"transparent\", alpha = NULL) {\n\n if (!is.null(probs)) {\n ## map quantiles to breaks\n if (!(missing(breaks) || is.null(breaks))) stop(\"only one of 'breaks' and 'probs' must be specified\")\n breaks = quantile.density(list(x = x, y = y - ymin), probs = probs)\n }\n\n ## sanity check\n if (breaks[1L] > x[1L] || breaks[length(breaks)] < x[length(x)]) stop(\"'breaks' do no span range of 'x'\")\n\n # ## recycle color (if necessary) rather use colorRampPalette below\n # col = rep_len(col, length(breaks) - 1L)\n \n # Create individual polygons\n if (isFALSE(manbreaks)) {\n # Special case for length(breaks)==length(x). We can take a fully vectorised\n # shortcut\n xx = c(rbind(x[-length(x)], x[-1], x[-1], x[-length(x)], NA))\n yy = c(rbind(y[-length(y)], y[-1], ymin, ymin, NA))\n } else {\n # For other cases, we'll do a bit more work to make sure that the polygons\n # overlap\n bvals = do.call(c, sapply(seq_along(breaks[-1]), function(b) tail(x[x= xrange[1] & breaks < xrange[2])\n idx = c(idx, length(idx)+1)\n col = col[idx]\n col = colorRampPalette(col, alpha = TRUE)(length(x)) # support alpha?\n }\n } else if (isFALSE(manbreaks) || length(col) > length(x) || length(x) %% length(col) != 0) {\n xrange = range(xx, na.rm = TRUE)\n idx = which(breaks >= xrange[1] & breaks < xrange[2])\n idx = c(idx, length(idx)+1)\n col = col[idx]\n col = colorRampPalette(col, alpha = TRUE)(length(x)) # support alpha?\n }\n }\n border = if (is.null(alpha)) col else adjustcolor(col = col, alpha.f = alpha/2)\n \n ## draw all polygons\n polygon(xx, yy, col = col, border = border, lwd = 0.5)\n}\n\n#' @importFrom graphics rasterImage\n#' @importFrom grDevices as.raster\nsegmented_raster = function(x, y, ymin = 0, breaks = range(x), probs = NULL, manbreaks = FALSE, col = \"lightgray\", border = \"transparent\", alpha = NULL) {\n ## set up raster matrix on x-grid and 500 y-pixels \n n = length(x) - 1L\n m = 500L ## FIXME: hard-coded?\n r = matrix(1:n, ncol = n, nrow = m, byrow = TRUE)\n\n ## map quantiles to breaks\n if (!is.null(probs)) {\n if (!(missing(breaks) || is.null(breaks))) stop(\"only one of 'breaks' and 'probs' must be specified\")\n breaks = quantile.density(list(x = x, y = y - ymin), probs = probs)\n }\n\n if (!is.null(alpha)) col = adjustcolor(col, alpha.f = alpha)\n col = rev(col) ## uncomment to make extreme cols dark\n ## map colors to intervals and fill colors by column\n col = col[cut(x, breaks = breaks, include.lowest = TRUE)]\n r[] = col[r]\n\n ## clip raster pixels above density line\n ymax = max(y)\n ix = cbind(as.vector(row(r)), as.vector(col(r)))\n ix = ix[seq(from = ymax, to = ymin, length.out = m)[row(r)] > y[col(r)], , drop = FALSE]\n r[ix] = NA\n\n ## plot density and add raster gradient\n rasterImage(as.raster(r), min(x), ymin, max(x), ymax, interpolate = length(breaks) >= 20L) ## FIXME: improve quality for \"few\" breaks?\n}\n\n## auxiliary function for determining quantiles based on density function\n\n#' @importFrom stats median approx\nquantile.density = function(x, probs = seq(0, 1, 0.25), ...) {\n ## sanity check for probabilities\n if (any(probs < 0 | probs > 1)) stop(\"'probs' outside [0,1]\")\n\n ## probability density function, extrapolated to zero, use midpoints\n n = length(x$x)\n pdf = x$y\n pdf = c(0, pdf, 0)\n\n ## x variable, also extrapolated, use midpoints\n x = x$x\n delta = median(diff(x))\n x = c(x[1L] - delta, x, x[n] + delta)\n\n ## numerical integration of density\n cdf = c(0, cumsum(diff(x) * (pdf[-1L] + pdf[-(n + 2L)])/2))\n cdf = cdf/cdf[n + 2L]\n\n ## approximate quantiles\n approx(cdf, x, xout = probs, rule = 2)$y \n}\n"], ["/tinyplot/R/tinyplot.R", "#' @title Lightweight extension of the base R plotting function\n#'\n#' @description\n#' Enhances the base \\code{\\link[graphics]{plot}} function. Supported features\n#' include automatic legends and facets for grouped data, additional plot types,\n#' theme customization, and so on. Users can call either `tinyplot()`, or its\n#' shorthand alias `plt()`.\n#'\n#' @md\n#' @param x,y the x and y arguments provide the x and y coordinates for the\n#' plot. Any reasonable way of defining the coordinates is acceptable; most\n#' likely the names of existing vectors or columns of data frames. See the\n#' 'Examples' section below, or the function\n#' \\code{\\link[grDevices]{xy.coords}} for details. If supplied separately, `x`\n#' and `y` must be of the same length.\n#' @param xmin,xmax,ymin,ymax minimum and maximum coordinates of relevant area\n#' or interval plot types. Only used when the `type` argument is one of\n#' `\"rect\"` or `\"segments\"` (where all four min-max coordinates are required),\n#' or `\"pointrange\"`, `\"errorbar\"`, or `\"ribbon\"` (where only `ymin` and\n#' `ymax` required alongside `x`). In the formula method the arguments\n#' can be specified as `ymin = var` if `var` is a variable in `data`.\n#' @param by grouping variable(s). The default behaviour is for groups to be\n#' represented in the form of distinct colours, which will also trigger an\n#' automatic legend. (See `legend` below for customization options.) However,\n#' groups can also be presented through other plot parameters (e.g., `pch` or\n#' `lty`) by passing an appropriate \"by\" keyword; see Examples. Note that\n#' continuous (i.e., gradient) colour legends are also supported if the user\n#' passes a numeric or integer to `by`. To group by multiple variables, wrap\n#' them with \\code{\\link[base]{interaction}}.\n#' @param facet the faceting variable(s) that you want arrange separate plot\n#' windows by. Can be specified in various ways:\n#' - In \"atomic\" form, e.g. `facet = fvar`. To facet by multiple variables in\n#' atomic form, simply interact them, e.g.\n#' `interaction(fvar1, fvar2)` or `factor(fvar1):factor(fvar2)`.\n#' - As a one-sided formula, e.g. `facet = ~fvar`. Multiple variables can be\n#' specified in the formula RHS, e.g. `~fvar1 + fvar2` or `~fvar1:fvar2`. Note\n#' that these multi-variable cases are _all_ treated equivalently and\n#' converted to `interaction(fvar1, fvar2, ...)` internally. (No distinction\n#' is made between different types of binary operators, for example, and so\n#' `f1+f2` is treated the same as `f1:f2`, is treated the same as `f1*f2`,\n#' etc.)\n#' - As a two-side formula, e.g. `facet = fvar1 ~ fvar2`. In this case, the\n#' facet windows are arranged in a fixed grid layout, with the formula LHS\n#' defining the facet rows and the RHS defining the facet columns. At present\n#' only single variables on each side of the formula are well supported. (We\n#' don't recommend trying to use multiple variables on either the LHS or RHS\n#' of the two-sided formula case.)\n#' - As a special `\"by\"` convenience keyword, in which case facets will match\n#' the grouping variable(s) passed to `by` above.\n#' @param facet.args an optional list of arguments for controlling faceting\n#' behaviour. (Ignored if `facet` is NULL.) Supported arguments are as\n#' follows:\n#' - `nrow`, `ncol` for overriding the default \"square\" facet window\n#' arrangement. Only one of these should be specified, but `nrow` will take\n#' precedence if both are specified together. Ignored if a two-sided formula\n#' is passed to the main `facet` argument, since the layout is arranged in a\n#' fixed grid.\n#' - `free` a logical value indicating whether the axis limits (scales) for\n#' each individual facet should adjust independently to match the range of\n#' the data within that facet. Default is `FALSE`. Separate free scaling of\n#' the x- or y-axis (i.e., whilst holding the other axis fixed) is not\n#' currently supported.\n#' - `fmar` a vector of form `c(b,l,t,r)` for controlling the base margin\n#' between facets in terms of lines. Defaults to the value of `tpar(\"fmar\")`,\n#' which should be `c(1,1,1,1)`, i.e. a single line of padding around each\n#' individual facet, assuming it hasn't been overridden by the user as part\n#' their global \\code{\\link[tinyplot]{tpar}} settings. Note some automatic\n#' adjustments are made for certain layouts, and depending on whether the plot\n#' is framed or not, to reduce excess whitespace. See\n#' \\code{\\link[tinyplot]{tpar}} for more details.\n#' - `cex`, `font`, `col`, `bg`, `border` for adjusting the facet title text\n#' and background. Default values for these arguments are inherited from\n#' \\code{\\link[tinyplot]{tpar}} (where they take a \"facet.\" prefix, e.g.\n#' `tpar(\"facet.cex\")`). The latter function can also be used to set these\n#' features globally for all `tinyplot` plots.\n#' @param formula a \\code{\\link[stats]{formula}} that optionally includes\n#' grouping variable(s) after a vertical bar, e.g. `y ~ x | z`. One-sided\n#' formulae are also permitted, e.g. `~ y | z`. Only a single `y` and `x`\n#' variable (if any) must be specified but multiple grouping variables\n#' can be included in different ways, e.g. `y ~ x | z1:z2` or\n#' `y ~ x | z1 + z2`. (These two representations are treated as equivalent;\n#' both are parsed as `interaction(z1, z2)` internally.) If arithmetic\n#' operators are used for transforming variables, they should be wrapped in\n#' `I()`, e.g., `I(y1/y2) ~ x`. Note that the `formula` and `x` arguments\n#' should not be specified in the same call.\n#' @param data a data.frame (or list) from which the variables in formula\n#' should be taken. A matrix is converted to a data frame.\n#' @param type character string or call to a `type_*()` function giving the\n#' type of plot desired.\n#' - NULL (default): Choose a sensible type for the type of `x` and `y` inputs\n#' (i.e., usually `\"p\"`).\n#' - 1-character values supported by \\code{\\link[graphics]{plot}}:\n#' - `\"p\"` Points\n#' - `\"l\"` Lines\n#' - `\"b\"` Both points and lines\n#' - `\"c\"` Empty points joined by lines\n#' - `\"o\"` Overplotted points and lines\n#' - `\"s\"` Stair steps\n#' - `\"S\"` Stair steps\n#' - `\"h\"` Histogram-like vertical lines\n#' - `\"n\"` Empty plot over the extent of the data\n#' - `tinyplot`-specific types. These fall into several categories:\n#' - Shapes:\n#' - `\"area\"` / [`type_area()`]: Plots the area under the curve from `y` = 0 to `y` = f(`x`).\n#' - `\"errorbar\"` / [`type_errorbar()`]: Adds error bars to points; requires `ymin` and `ymax`.\n#' - `\"pointrange\"` / [`type_pointrange()`]: Combines points with error bars.\n#' - `\"polygon\"` / [`type_polygon()`]: Draws polygons.\n#' - `\"polypath\"` / [`type_polypath()`]: Draws a path whose vertices are given in `x` and `y`.\n#' - `\"rect\"` / [`type_rect()`]: Draws rectangles; requires `xmin`, `xmax`, `ymin`, and `ymax`.\n#' - `\"ribbon\"` / [`type_ribbon()`]: Creates a filled area between `ymin` and `ymax`.\n#' - `\"segments\"` / [`type_segments()`]: Draws line segments between pairs of points.\n#' - `\"text\"` / [`type_text()`]: Add text annotations.\n#' - Visualizations:\n#' - `\"barplot\"` / [`type_barplot()`]: Creates a bar plot.\n#' - `\"boxplot\"` / [`type_boxplot()`]: Creates a box-and-whisker plot.\n#' - `\"density\"` / [`type_density()`]: Plots the density estimate of a variable.\n#' - `\"histogram\"` / [`type_histogram()`]: Creates a histogram of a single variable.\n#' - `\"jitter\"` / [`type_jitter()`]: Jittered points.\n#' - `\"qq\"` / [`type_qq()`]: Creates a quantile-quantile plot.\n#' - `\"ridge\"` / [`type_ridge()`]: Creates a ridgeline (aka joy) plot.\n#' - `\"rug\"` / [`type_rug()`]: Adds a rug to an existing plot.\n#' - `\"spineplot\"` / [`type_spineplot()`]: Creates a spineplot or spinogram.\n#' - `\"violin\"` / [`type_violin()`]: Creates a violin plot.\n#' - Models:\n#' - `\"loess\"` / [`type_loess()`]: Local regression curve.\n#' - `\"lm\"` / [`type_lm()`]: Linear regression line.\n#' - `\"glm\"` / [`type_glm()`]: Generalized linear model fit.\n#' - `\"spline\"` / [`type_spline()`]: Cubic (or Hermite) spline interpolation.\n#' - Functions:\n#' - [`type_abline()`]: line(s) with intercept and slope.\n#' - [`type_hline()`]: horizontal line(s).\n#' - [`type_vline()`]: vertical line(s).\n#' - [`type_function()`]: arbitrary function.\n#' - [`type_summary()`]: summarize `y` by unique values of `x`.\n#' @param legend one of the following options:\n#' - NULL (default), in which case the legend will be determined by the\n#' grouping variable. If there is no group variable (i.e., `by` is NULL) then\n#' no legend is drawn. If a grouping variable is detected, then an automatic\n#' legend is drawn to the _outer_ right of the plotting area. Note that the\n#' legend title and categories will automatically be inferred from the `by`\n#' argument and underlying data.\n#' - A convenience string indicating the legend position. The string should\n#' correspond to one of the position keywords supported by the base `legend`\n#' function, e.g. \"right\", \"topleft\", \"bottom\", etc. In addition, `tinyplot`\n#' supports adding a trailing exclamation point to these keywords, e.g.\n#' \"right!\", \"topleft!\", or \"bottom!\". This will place the legend _outside_\n#' the plotting area and adjust the margins of the plot accordingly. Finally,\n#' users can also turn off any legend printing by specifying \"none\".\n#' - Logical value, where TRUE corresponds to the default case above (same\n#' effect as specifying NULL) and FALSE turns the legend off (same effect as\n#' specifying \"none\").\n#' - A list or, equivalently, a dedicated `legend()` function with supported\n#' legend arguments, e.g. \"bty\", \"horiz\", and so forth.\n#' @param main a main title for the plot, see also `title`.\n#' @param sub a subtitle for the plot.\n#' @param xlab a label for the x axis, defaults to a description of x.\n#' @param ylab a label for the y axis, defaults to a description of y.\n#' @param ann a logical value indicating whether the default annotation (title\n#' and x and y axis labels) should appear on the plot.\n#' @param xlim the x limits (x1, x2) of the plot. Note that x1 > x2 is allowed\n#' and leads to a ‘reversed axis’. The default value, NULL, indicates that\n#' the range of the `finite` values to be plotted should be used.\n#' @param ylim the y limits of the plot.\n#' @param axes logical or character. Should axes be drawn (`TRUE` or `FALSE`)?\n#' Or alternatively what type of axes should be drawn: `\"standard\"` (with\n#' axis, ticks, and labels; equivalent to `TRUE`), `\"none\"` (no axes;\n#' equivalent to `FALSE`), `\"ticks\"` (only ticks and labels without axis line),\n#' `\"labels\"` (only labels without ticks and axis line), `\"axis\"` (only axis\n#' line and labels but no ticks). To control this separately for the two\n#' axes, use the character specifications for `xaxt` and/or `yaxt`.\n#' @param xaxt,yaxt character specifying the type of x-axis and y-axis,\n#' respectively. See `axes` for the possible values.\n#' @param xaxs,yaxs character specifying the style of the interval calculation\n#' used for the x-axis and y-axis, respectively. See\n#' \\code{\\link[graphics]{par}} for the possible values.\n#' @param xaxb,yaxb numeric vector (or character vector, if appropriate) giving\n#' the break points at which the axis tick-marks are to be drawn. Break points\n#' outside the range of the data will be ignored if the associated axis\n#' variable is categorical, or an explicit `x/ylim` range is given.\n#' @param xaxl,yaxl a function or a character keyword specifying the format of\n#' the x- or y-axis tick labels. Note that this is a post-processing step that\n#' affects the _appearance_ of the tick labels only; use in conjunction with\n#' `x/yaxb` if you would like to adjust the position of the tick marks too. In\n#' addition to user-supplied formatting functions (e.g., [`format`],\n#' [`toupper`], [`abs`], or other custom function), several convenience\n#' keywords (or their symbol equivalents) are available for common formatting\n#' transformations: `\"percent\"` (`\"%\"`), `\"comma\"` (`\",\"`), `\"log\"` (`\"l\"`),\n#' `\"dollar\"` (`\"$\"`), `\"euro\"` (`\"€\"`), or `\"sterling\"` (`\"£\"`). See the\n#' [`tinylabel`] documentation for examples.\n#' @param log a character string which contains `\"x\"` if the x axis is to be\n#' logarithmic, `\"y\"` if the y axis is to be logarithmic and `\"xy\"` or `\"yx\"`\n#' if both axes are to be logarithmic.\n#' @param flip logical. Should the plot orientation be flipped, so that the\n#' y-axis is on the horizontal plane and the x-axis is on the vertical plane?\n#' Default is FALSE.\n#' @param frame.plot a logical indicating whether a box should be drawn around\n#' the plot. Can also use `frame` as an acceptable argument alias.\n#' The default is to draw a frame if both axis types (set via `axes`, `xaxt`,\n#' or `yaxt`) include axis lines.\n#' @param grid argument for plotting a background panel grid, one of either:\n#' - a logical (i.e., `TRUE` to draw the grid), or\n#' - a panel grid plotting function like `grid()`.\n#' Note that this argument replaces the `panel.first` and `panel.last`\n#' arguments from base `plot()` and tries to make the process more seamless\n#' with better default behaviour. The default behaviour is determined by (and\n#' can be set globally through) the value of `tpar(\"grid\")`.\n#' @param palette one of the following options:\n#' - NULL (default), in which case the palette will be chosen according to\n#' the class and cardinality of the \"by\" grouping variable. For non-ordered\n#' factors or strings with a reasonable number of groups, this will inherit\n#' directly from the user's default \\code{\\link[grDevices]{palette}} (e.g.,\n#' \"R4\"). In other cases, including ordered factors and high cardinality, the\n#' \"Viridis\" palette will be used instead. Note that a slightly restricted\n#' version of the \"Viridis\" palette---where extreme color values have been\n#' trimmed to improve visual perception---will be used for ordered factors\n#' and continuous variables. In the latter case of a continuous grouping\n#' variable, we also generate a gradient legend swatch.\n#' - A convenience string corresponding to one of the many palettes listed by\n#' either `palette.pals()` or `hcl.pals()`. Note that the string can be\n#' case-insensitive (e.g., \"Okabe-Ito\" and \"okabe-ito\" are both valid).\n#' - A palette-generating function. This can be \"bare\" (e.g.,\n#' `palette.colors`) or \"closed\" with a set of named arguments (e.g.,\n#' `palette.colors(palette = \"Okabe-Ito\", alpha = 0.5)`). Note that any\n#' unnamed arguments will be ignored and the key `n` argument, denoting the\n#' number of colours, will automatically be spliced in as the number of\n#' groups.\n#' - A vector or list of colours, e.g. `c(\"darkorange\", \"purple\", \"cyan4\")`.\n#' If too few colours are provided for a discrete (qualitative) set of\n#' groups, then the colours will be recycled with a warning. For continuous\n#' (sequential) groups, a gradient palette will be interpolated. \n#' @param col plotting color. Character, integer, or vector of length equal to\n#' the number of categories in the `by` variable. See `col`. Note that the\n#' default behaviour in `tinyplot` is to vary group colors along any variables\n#' declared in the `by` argument. Thus, specifying colors manually should not\n#' be necessary unless users wish to override the automatic colors produced by\n#' this grouping process. Typically, this would only be done if grouping\n#' features are deferred to some other graphical parameter (i.e., passing the\n#' \"by\" keyword to one of `pch`, `lty`, `lwd`, or `bg`; see below.)\n#' @param pch plotting \"character\", i.e., symbol to use. Character, integer, or\n#' vector of length equal to the number of categories in the `by` variable.\n#' See `pch`. In addition, users can supply a special `pch = \"by\"` convenience\n#' argument, in which case the characters will automatically loop over the\n#' number groups. This automatic looping will begin at the global character\n#' value (i.e., `par(\"pch\")`) and recycle as necessary.\n#' @param lty line type. Character, integer, or vector of length equal to the\n#' number of categories in the `by` variable. See `lty`. In addition, users\n#' can supply a special `lty = \"by\"` convenience argument, in which case the\n#' line type will automatically loop over the number groups. This automatic\n#' looping will begin at the global line type value (i.e., `par(\"lty\")`) and\n#' recycle as necessary.\n#' @param lwd line width. Numeric scalar or vector of length equal to the\n#' number of categories in the `by` variable. See `lwd`. In addition, users\n#' can supply a special `lwd = \"by\"` convenience argument, in which case the\n#' line width will automatically loop over the number of groups. This\n#' automatic looping will be centered at the global line width value (i.e.,\n# ` par(\"lwd\")`) and pad on either side of that.\n#' @param bg background fill color for the open plot symbols 21:25 (see\n#' `points.default`), as well as ribbon and area plot types.\n#' Users can also supply either one of two special convenience arguments that\n#' will cause the background fill to inherit the automatic grouped coloring\n#' behaviour of `col`:\n#'\n#' - `bg = \"by\"` will insert a background fill that inherits the main color\n#' mappings from `col`.\n#' - `by = ` (i.e., a numeric in the range `[0,1]`) will insert\n#' a background fill that inherits the main color mapping(s) from `col`, but\n#' with added alpha-transparency.\n#'\n#' For both of these convenience arguments, note that the (grouped) `bg`\n#' mappings will persist even if the (grouped) `col` defaults are themselves\n#' overridden. This can be useful if you want to preserve the grouped palette\n#' mappings by background fill but not boundary color, e.g. filled points. See\n#' examples.\n#' @param fill alias for `bg`. If non-NULL values for both `bg` and `fill` are\n#' provided, then the latter will be ignored in favour of the former.\n#' @param alpha a numeric in the range `[0,1]` for adjusting the alpha channel\n#' of the color palette, where 0 means transparent and 1 means opaque. Use\n#' fractional values, e.g. `0.5` for semi-transparency.\n#' @param cex character expansion. A numerical vector (can be a single value)\n#' giving the amount by which plotting characters and symbols should be scaled\n#' relative to the default. Note that NULL is equivalent to 1.0, while NA\n#' renders the characters invisible.\n#' @param subset,na.action,drop.unused.levels arguments passed to `model.frame`\n#' when extracting the data from `formula` and `data`.\n#' @param add logical. If TRUE, then elements are added to the current plot rather\n#' than drawing a new plot window. Note that the automatic legend for the\n#' added elements will be turned off. See also [tinyplot_add], which provides\n#' a convenient wrapper around this functionality for layering on top of an\n#' existing plot without having to repeat arguments.\n#' @param draw a function that draws directly on the plot canvas (before `x` and\n#' `y` are plotted). The `draw` argument is primarily useful for adding common\n#' elements to each facet of a faceted plot, e.g.\n#' \\code{\\link[graphics]{abline}} or \\code{\\link[graphics]{text}}. Note that\n#' this argument is somewhat experimental and that _no_ internal checking is\n#' done for correctness; the provided argument is simply captured and\n#' evaluated as-is. See Examples.\n#' @param restore.par a logical value indicating whether the\n#' \\code{\\link[graphics]{par}} settings prior to calling `tinyplot` should be\n#' restored on exit. Defaults to FALSE, which makes it possible to add\n#' elements to the plot after it has been drawn. However, note the the outer\n#' margins of the graphics device may have been altered to make space for the\n#' `tinyplot` legend. Users can opt out of this persistent behaviour by\n#' setting to TRUE instead. See also [get_saved_par] for another option to\n#' recover the original \\code{\\link[graphics]{par}} settings, as well as\n#' longer discussion about the trade-offs involved.\n#' @param empty logical indicating whether the interior plot region should be\n#' left empty. The default is `FALSE`. Setting to `TRUE` has a similar effect\n#' to invoking `type = \"n\"` above, except that any legend artifacts owing to a\n#' particular plot type (e.g., lines for `type = \"l\"` or squares for\n#' `type = \"area\"`) will still be drawn correctly alongside the empty plot. In\n#' contrast,`type = \"n\"` implicitly assumes a scatterplot and so any legend\n#' will only depict points.\n#' @param file character string giving the file path for writing a plot to disk.\n#' If specified, the plot will not be displayed interactively, but rather sent\n#' to the appropriate external graphics device (i.e.,\n#' \\code{\\link[grDevices]{png}}, \\code{\\link[grDevices]{jpeg}},\n#' \\code{\\link[grDevices]{pdf}}, or \\code{\\link[grDevices]{svg}}). As a point\n#' of convenience, note that any global parameters held in `(t)par` are\n#' automatically carried over to the external device and don't need to be\n#' reset (in contrast to the conventional base R approach that requires\n#' manually opening and closing the device). The device type is determined by\n#' the file extension at the end of the provided path, and must be one of\n#' \".png\", \".jpg\" (\".jpeg\"), \".pdf\", or \".svg\". (Other file types may be\n#' supported in the future.) The file dimensions can be controlled by the\n#' corresponding `width` and `height` arguments below, otherwise will fall\n#' back to the `\"file.width\"` and `\"file.height\"` values held in\n#' \\code{\\link[tinyplot]{tpar}} (i.e., both defaulting to 7 inches, and where\n#' the default resolution for bitmap files is also specified as 300\n#' DPI).\n#' @param width numeric giving the plot width in inches. Together with `height`,\n#' typically used in conjunction with the `file` argument above, overriding the\n#' default values held in `tpar(\"file.width\", \"file.height\")`. If either `width`\n#' or `height` is specified, but a corresponding `file` argument is not\n#' provided as well, then a new interactive graphics device dimensions will be\n#' opened along the given dimensions. Note that this interactive resizing may\n#' not work consistently from within an IDE like RStudio that has an integrated\n#' graphics windows.\n#' @param height numeric giving the plot height in inches. Same considerations as\n#' `width` (above) apply, e.g. will default to `tpar(\"file.height\")` if not\n#' specified.\n#' @param asp the y/xy/x aspect ratio, see `plot.window`.\n#' @param ... other graphical parameters. If `type` is a character specification\n#' (such as `\"hist\"`) then any argument names that match those from the corresponding\n#' `type_*()` function (such as \\code{\\link{type_hist}}) are passed on to that.\n#' All remaining arguments from `...` can be further graphical parameters, see\n#' \\code{\\link[graphics]{par}}).\n#'\n#' @returns No return value, called for side effect of producing a plot.\n#'\n#' @details\n#' Disregarding the enhancements that it supports, `tinyplot` tries as far as\n#' possible to mimic the behaviour and syntax logic of the original base\n#' \\code{\\link[graphics]{plot}} function. Users should therefore be able to swap\n#' out existing `plot` calls for `tinyplot` (or its shorthand alias `plt`),\n#' without causing unexpected changes to the output.\n#'\n#' @importFrom grDevices axisTicks adjustcolor cairo_pdf colorRampPalette extendrange palette palette.colors palette.pals hcl.colors hcl.pals xy.coords png jpeg pdf svg dev.off dev.new dev.list\n#' @importFrom graphics abline arrows axis Axis axTicks box boxplot grconvertX grconvertY hist lines mtext par plot.default plot.new plot.window points polygon polypath segments rect text title\n#' @importFrom utils modifyList head tail\n#' @importFrom stats na.omit\n#' @importFrom tools file_ext\n#'\n#' @examples\n#' aq = transform(\n#' airquality,\n#' Month = factor(Month, labels = month.abb[unique(Month)])\n#' )\n#'\n#' # In most cases, `tinyplot` should be a drop-in replacement for regular\n#' # `plot` calls. For example:\n#'\n#' op = tpar(mfrow = c(1, 2))\n#' plot(0:10, main = \"plot\")\n#' tinyplot(0:10, main = \"tinyplot\")\n#' tpar(op) # restore original layout\n#'\n#' # Aside: `tinyplot::tpar()` is a (near) drop-in replacement for `par()`\n#'\n#' # Unlike vanilla plot, however, tinyplot allows you to characterize groups\n#' # using either the `by` argument or equivalent `|` formula syntax.\n#'\n#' with(aq, tinyplot(Day, Temp, by = Month)) ## atomic method\n#' tinyplot(Temp ~ Day | Month, data = aq) ## formula method\n#'\n#' # (Notice that we also get an automatic legend.)\n#'\n#' # You can also use the equivalent shorthand `plt()` alias if you'd like to\n#' # save on a few keystrokes\n#'\n#' plt(Temp ~ Day | Month, data = aq) ## shorthand alias\n#'\n#' # Use standard base plotting arguments to adjust features of your plot.\n#' # For example, change `pch` (plot character) to get filled points and `cex`\n#' # (character expansion) to increase their size.\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' pch = 16,\n#' cex = 2\n#' )\n#'\n#' # We can add alpha transparency for overlapping points\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' pch = 16,\n#' cex = 2,\n#' alpha = 0.3\n#' )\n#'\n#' # To get filled points with a common solid background color, use an\n#' # appropriate plotting character (21:25) and combine with one of the special\n#' # `bg` convenience arguments.\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' pch = 21, # use filled circles\n#' cex = 2,\n#' bg = 0.3, # numeric in [0,1] adds a grouped background fill with transparency\n#' col = \"black\" # override default color mapping; give all points a black border\n#' )\n#'\n#' # Converting to a grouped line plot is a simple matter of adjusting the\n#' # `type` argument.\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' type = \"l\"\n#' )\n#'\n#' # Similarly for other plot types, including some additional ones provided\n#' # directly by tinyplot, e.g. density plots or internal plots (ribbons,\n#' # pointranges, etc.)\n#'\n#' tinyplot(\n#' ~ Temp | Month,\n#' data = aq,\n#' type = \"density\",\n#' fill = \"by\"\n#' )\n#'\n#' # Facet plots are supported too. Facets can be drawn on their own...\n#'\n#' tinyplot(\n#' Temp ~ Day,\n#' facet = ~Month,\n#' data = aq,\n#' type = \"area\",\n#' main = \"Temperatures by month\"\n#' )\n#'\n#' # ... or combined/contrasted with the by (colour) grouping.\n#'\n#' aq = transform(aq, Summer = Month %in% c(\"Jun\", \"Jul\", \"Aug\"))\n#' tinyplot(\n#' Temp ~ Day | Summer,\n#' facet = ~Month,\n#' data = aq,\n#' type = \"area\",\n#' palette = \"dark2\",\n#' main = \"Temperatures by month and season\"\n#' )\n#'\n#' # Users can override the default square window arrangement by passing `nrow`\n#' # or `ncol` to the helper facet.args argument. Note that we can also reduce\n#' # axis label repetition across facets by turning the plot frame off.\n#'\n#' tinyplot(\n#' Temp ~ Day | Summer,\n#' facet = ~Month, facet.args = list(nrow = 1),\n#' data = aq,\n#' type = \"area\",\n#' palette = \"dark2\",\n#' frame = FALSE,\n#' main = \"Temperatures by month and season\"\n#' )\n#'\n#' # Use a two-sided formula to arrange the facet windows in a fixed grid.\n#' # LHS -> facet rows; RHS -> facet columns\n#'\n#' aq$hot = ifelse(aq$Temp >= 75, \"hot\", \"cold\")\n#' aq$windy = ifelse(aq$Wind >= 15, \"windy\", \"calm\")\n#' tinyplot(\n#' Temp ~ Day,\n#' facet = windy ~ hot,\n#' data = aq\n#' )\n#'\n#' # To add common elements to each facet, use the `draw` argument\n#'\n#' tinyplot(\n#' Temp ~ Day,\n#' facet = windy ~ hot,\n#' data = aq,\n#' draw = abline(h = 75, lty = 2, col = \"hotpink\")\n#' )\n#'\n#' # The (automatic) legend position and look can be customized using\n#' # appropriate arguments. Note the trailing \"!\" in the `legend` position\n#' # argument below. This tells `tinyplot` to place the legend _outside_ the plot\n#' # area.\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' type = \"l\",\n#' legend = legend(\"bottom!\", title = \"Month of the year\", bty = \"o\")\n#' )\n#'\n#' # The default group colours are inherited from either the \"R4\" or \"Viridis\"\n#' # palettes, depending on the number of groups. However, all palettes listed\n#' # by `palette.pals()` and `hcl.pals()` are supported as convenience strings,\n#' # or users can supply a valid palette-generating function for finer control\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' type = \"l\",\n#' palette = \"tableau\"\n#' )\n#'\n#' # It's possible to customize the look of your plots by setting graphical\n#' # parameters (e.g., via `(t)par`)... But a more convenient way is to just use\n#' # built-in themes (see `?tinytheme`).\n#'\n#' tinytheme(\"clean2\")\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' type = \"b\",\n#' alpha = 0.5,\n#' main = \"Daily temperatures by month\",\n#' sub = \"Brought to you by tinyplot\"\n#' )\n#' # reset the theme\n#' tinytheme()\n#'\n#' # For more examples and a detailed walkthrough, please see the introductory\n#' # tinyplot tutorial available online:\n#' # https://grantmcdermott.com/tinyplot/vignettes/introduction.html\n#'\n#' @rdname tinyplot\n#' @export\ntinyplot =\n function(x, ...) {\n UseMethod(\"tinyplot\")\n }\n\n#' @rdname tinyplot\n#' @export\ntinyplot.default = function(\n x = NULL,\n y = NULL,\n xmin = NULL,\n xmax = NULL,\n ymin = NULL,\n ymax = NULL,\n by = NULL,\n facet = NULL,\n facet.args = NULL,\n data = NULL,\n type = NULL,\n legend = NULL,\n main = NULL,\n sub = NULL,\n xlab = NULL,\n ylab = NULL,\n ann = par(\"ann\"),\n xlim = NULL,\n ylim = NULL,\n axes = TRUE,\n xaxt = NULL,\n yaxt = NULL,\n xaxs = NULL,\n yaxs = NULL,\n xaxb = NULL,\n yaxb = NULL,\n xaxl = NULL,\n yaxl = NULL,\n log = \"\",\n flip = FALSE,\n frame.plot = NULL,\n grid = NULL,\n palette = NULL,\n pch = NULL,\n lty = NULL,\n lwd = NULL,\n col = NULL,\n bg = NULL,\n fill = NULL,\n alpha = NULL,\n cex = 1,\n add = FALSE,\n draw = NULL,\n empty = FALSE,\n restore.par = FALSE,\n file = NULL,\n width = NULL,\n height = NULL,\n asp = NA,\n ...) {\n\n par_first = get_saved_par(\"first\")\n if (is.null(par_first)) set_saved_par(\"first\", par())\n\n assert_logical(add)\n \n # save for tinyplot_add()\n if (!add) {\n calls = sys.calls()\n idx = grep(\"^tinyplot\", sapply(calls, function(k) k[[1]]))\n if (length(idx) > 0) {\n options(tinyplot_last_call = calls[[idx[1]]])\n }\n ## TODO: remove the global option above and move to this when density is refactored\n # cal = match.call(call = sys.call(sys.parent()), expand.dots = TRUE)\n # assign(\".last_call\", cal, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n }\n\n dots = list(...)\n\n if (add) legend = FALSE\n draw = substitute(draw)\n\n\n # sanitize arguments\n\n # type factories vs. strings\n type = sanitize_type(type, x, y, dots)\n if (\"dots\" %in% names(type)) dots = type$dots\n \n # retrieve type-specific data and drawing functions\n type_data = type$data\n type_draw = type$draw\n type = type$name\n \n # area flag (mostly for legend)\n was_area_type = identical(type, \"area\")\n # check flip flag is logical \n assert_flag(flip)\n\n palette = substitute(palette)\n\n # themes\n if (is.null(palette)) palette = get_tpar(\"palette\", default = NULL)\n if (is.null(pch)) pch = get_tpar(\"pch\", default = NULL)\n\n xlabs = ylabs = NULL\n\n # type_ridge()\n ygroup = NULL\n\n # will be overwritten by some type_data() functions and ignored by others\n ribbon.alpha = sanitize_ribbon.alpha(NULL)\n\n ## handle defaults of axes, xaxt, yaxt, frame.plot\n ## - convert axes to character if necessary\n ## - set defaults of xaxt/yaxt (if these are NULL) based on axes\n ## - set logical axes based on xaxt/yaxt\n ## - set frame.plot default based on xaxt/yaxt\n if (isFALSE(axes)) {\n axes = xaxt = yaxt = \"none\"\n } else if (isTRUE(axes)) {\n axes = \"standard\"\n if (is.null(xaxt)) xaxt = get_tpar(\"xaxt\", default = \"standard\")\n if (is.null(yaxt)) yaxt = get_tpar(\"yaxt\", default = \"standard\")\n } else {\n xaxt = yaxt = axes\n }\n axis_types = c(\"standard\", \"none\", \"labels\", \"ticks\", \"axis\")\n axes = match.arg(axes, axis_types)\n xaxt = match.arg(xaxt, axis_types)\n yaxt = match.arg(yaxt, axis_types)\n xaxt = substr(match.arg(xaxt, axis_types), 1L, 1L)\n yaxt = substr(match.arg(yaxt, axis_types), 1L, 1L)\n axes = any(c(xaxt, yaxt) != \"n\")\n if (is.null(frame.plot) || !is.logical(frame.plot)) frame.plot = all(c(xaxt, yaxt) %in% c(\"s\", \"a\"))\n\n # Write plot to output file or window with fixed dimensions\n setup_device(file = file, width = width, height = height)\n if (!is.null(file)) on.exit(dev.off(), add = TRUE)\n\n # Save current graphical parameters\n opar = par(no.readonly = TRUE)\n if (restore.par || !is.null(facet)) {\n if (!is.null(file) || !is.null(width) || !is.null(height)) {\n opar$new = FALSE # catch for some interfaces\n }\n on.exit(par(opar), add = TRUE)\n }\n # set_orig_par(opar)\n set_saved_par(when = \"before\", opar)\n\n # catch for adding to existing facet plot\n if (!is.null(facet) && add) {\n recordGraphics(\n par(get_saved_par(when = \"after\")),\n list = list(),\n env = getNamespace('tinyplot')\n )\n }\n\n # Capture deparsed expressions early, before x, y and by are evaluated\n x_dep = if (!is.null(x)) {\n deparse1(substitute(x))\n } else if (type %in% c(\"rect\", \"segments\")) {\n x = NULL\n NULL\n }\n y_dep = if (is.null(y)) {\n deparse1(substitute(x))\n } else {\n deparse1(substitute(y))\n }\n by_dep = deparse1(substitute(by))\n null_by = is.null(by)\n\n ## coerce character variables to factors\n if (!is.null(x) && is.character(x)) x = factor(x)\n if (!is.null(y) && is.character(y)) y = factor(y)\n if (!null_by && is.character(by)) by = factor(by)\n\n # flag if x==by (currently only used for \"boxplot\", \"spineplot\" and \"ridges\" types)\n x_by = identical(x, by)\n\n facet_dep = deparse1(substitute(facet))\n # flag if facet==by\n facet_by = FALSE\n if (!is.null(facet) && length(facet) == 1 && facet == \"by\") {\n by = as.factor(by) ## if by==facet, then both need to be factors\n facet = by\n facet_by = TRUE\n } else if (!is.null(facet) && inherits(facet, \"formula\")) {\n facet = get_facet_fml(facet, data = data)\n if (isTRUE(attr(facet, \"facet_grid\"))) {\n facet.args[[\"nrow\"]] = attr(facet, \"facet_nrow\")\n }\n }\n facet_attr = attributes(facet) ## TODO: better solution for restoring facet attributes?\n null_facet = is.null(facet)\n\n if (is.null(x)) {\n ## Special catch for rect and segment plots without a specified y-var\n if (type %in% c(\"rect\", \"segments\")) {\n xmin_dep = deparse(substitute(xmin))\n xmax_dep = deparse(substitute(xmax))\n x_dep = paste0(\"[\", xmin_dep, \", \", xmax_dep, \"]\")\n x = rep(NA, length(x))\n }\n }\n if (is.null(y)) {\n ## Special catch for area and interval plots without a specified y-var\n if (type %in% c(\"rect\", \"segments\", \"pointrange\", \"errorbar\", \"ribbon\")) {\n ymin_dep = deparse(substitute(ymin))\n ymax_dep = deparse(substitute(ymax))\n y_dep = paste0(\"[\", ymin_dep, \", \", ymax_dep, \"]\")\n y = rep(NA, length(x))\n } else if (type == \"density\") {\n if (is.null(ylab)) ylab = \"Density\"\n } else if (type == \"function\") {\n if (is.null(ylab)) ylab = \"Frequency\"\n } else if (!(type %in% c(\"histogram\", \"barplot\"))) {\n y = x\n x = seq_along(x)\n if (is.null(xlab)) xlab = \"Index\"\n }\n }\n\n if (is.null(xlab)) xlab = x_dep\n if (is.null(ylab) && type != \"histogram\") ylab = y_dep\n \n # flag(s) indicating whether x/ylim was set by the user (needed later for\n # special case where facets are free but still want to set x/ylim manually)\n xlim_user = !is.null(xlim)\n ylim_user = !is.null(ylim)\n\n # alias\n if (is.null(bg) && !is.null(fill)) bg = fill\n\n datapoints = list(x = x, y = y, xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, ygroup = ygroup)\n datapoints = Filter(function(z) length(z) > 0, datapoints)\n datapoints = data.frame(datapoints)\n if (nrow(datapoints) > 0) {\n datapoints[[\"rowid\"]] = seq_len(nrow(datapoints))\n datapoints[[\"facet\"]] = if (!is.null(facet)) facet else \"\"\n datapoints[[\"by\"]] = if (!null_by) by else \"\"\n }\n\n ## initialize empty list with information that type_data\n ## can overwrite in order to pass on to type_draw\n type_info = list()\n\n if (!is.null(type_data)) {\n fargs = list(\n datapoints = datapoints,\n bg = bg,\n by = by,\n col = col,\n log = log,\n lty = lty,\n lwd = lwd,\n facet = facet,\n facet_by = facet_by,\n facet.args = facet.args,\n null_by = null_by,\n null_facet = null_facet,\n palette = palette,\n ribbon.alpha = ribbon.alpha,\n xaxt = xaxt,\n xaxb = xaxb,\n xaxl = xaxl,\n xlab = xlab,\n xlabs = xlabs,\n xlim = xlim,\n yaxt = yaxt,\n yaxb = yaxb,\n yaxl = yaxl,\n ylab = ylab,\n ylim = ylim\n )\n fargs = c(fargs, dots)\n list2env(do.call(type_data, fargs), environment())\n }\n\n\n # swap x and y values if flip is TRUE\n assert_flag(flip)\n # extra catch for boxplots\n # now swap the values\n if (isTRUE(flip)) {\n if (type != \"boxplot\") {\n # limits, labs, etc.\n xlim_cp = xlim\n xlim = ylim\n ylim = xlim_cp\n xlab_cp = xlab\n xlab = ylab\n ylab = xlab_cp\n xlabs_cp = xlabs\n xlabs = ylabs\n ylabs = xlabs_cp\n xaxt_cp = xaxt\n xaxt = yaxt\n yaxt = xaxt_cp\n xaxs_cp = xaxs\n xaxs = yaxs\n yaxs = xaxs_cp\n xaxb_cp = xaxb\n xaxb = yaxb\n yaxb = xaxb_cp\n xaxl_cp = xaxl\n xaxl = yaxl\n yaxl = xaxl_cp\n if (!is.null(log)) {\n log = if (log == \"x\") \"y\" else if (log == \"y\") \"x\" else log\n }\n # x/y vars\n x_cp = datapoints[[\"x\"]]\n datapoints[[\"x\"]] = datapoints[[\"y\"]]\n datapoints[[\"y\"]] = x_cp\n # x/y min and max vars\n xmin_cp = if (!is.null(datapoints[[\"xmin\"]])) datapoints[[\"xmin\"]] else NULL\n datapoints[[\"xmin\"]] = if (!is.null(datapoints[[\"ymin\"]])) datapoints[[\"ymin\"]] else NULL\n datapoints[[\"ymin\"]] = if (!is.null(xmin_cp)) xmin_cp else NULL\n xmax_cp = if (!is.null(datapoints[[\"xmax\"]])) datapoints[[\"xmax\"]] else NULL\n datapoints[[\"xmax\"]] = if (!is.null(datapoints[[\"ymax\"]])) datapoints[[\"ymax\"]] else NULL\n datapoints[[\"ymax\"]] = if (!is.null(xmax_cp)) xmax_cp else NULL\n # clean up\n rm(xlim_cp, xlab_cp, xlabs_cp, xaxt_cp, xaxs_cp, xaxb_cp, xaxl_cp, x_cp, xmin_cp, xmax_cp)\n } else {\n # We'll let boxplot(..., horizontal = TRUE) handle most of the adjustments\n # and just catch a few elements that we draw beforehand.\n xlab_cp = xlab\n xlab = ylab\n ylab = xlab_cp\n rm(xlab_cp)\n }\n }\n \n # For cases where x/yaxb is provided and corresponding x/ylabs is not null...\n # We can subset these here to provide breaks\n if (!is.null(xaxb) && !is.null(xlabs)) {\n xlabs = xlabs[names(xlabs) %in% xaxb]\n xaxb = NULL # don't need this any more\n }\n if (!is.null(yaxb) && !is.null(ylabs)) {\n ylabs = ylabs[names(ylabs) %in% yaxb]\n yaxb = NULL # don't need this any more\n }\n \n # plot limits\n fargs = lim_args(\n datapoints = datapoints,\n xlim = xlim, ylim = ylim,\n xaxb = xaxb, yaxb = yaxb,\n xlim_user = xlim_user, ylim_user = ylim_user,\n type = type\n )\n list2env(fargs, environment())\n\n\n # split data\n by_ordered = FALSE\n by_continuous = !null_by && inherits(datapoints$by, c(\"numeric\", \"integer\"))\n if (isTRUE(by_continuous) && type %in% c(\"l\", \"b\", \"o\", \"ribbon\", \"polygon\", \"polypath\", \"boxplot\")) {\n warning(\"\\nContinuous legends not supported for this plot type. Reverting to discrete legend.\")\n by_continuous = FALSE\n } else if (!null_by) {\n by_ordered = is.ordered(by)\n }\n\n if (length(unique(datapoints$facet)) == 1) {\n datapoints[[\"facet\"]] = NULL\n }\n if (!is.null(datapoints$facet)) {\n split_data = split(datapoints, datapoints$facet)\n split_data = lapply(split_data, as.list)\n } else {\n split_data = list(as.list(datapoints))\n }\n\n # aesthetics by group: col, bg, etc.\n ngrps = if (null_by) 1L else if (is.factor(by)) length(levels(by)) else if (by_continuous) 100L else length(unique(by))\n pch = by_pch(ngrps = ngrps, type = type, pch = pch)\n lty = by_lty(ngrps = ngrps, type = type, lty = lty)\n lwd = by_lwd(ngrps = ngrps, type = type, lwd = lwd)\n col = by_col(\n ngrps = ngrps, col = col, palette = palette,\n gradient = by_continuous, ordered = by_ordered, alpha = alpha)\n bg = by_bg(\n adjustcolor = adjustcolor, alpha = alpha, bg = bg, by = by, by_continuous = by_continuous,\n by_ordered = by_ordered, col = col, fill = fill, palette = substitute(palette),\n ribbon.alpha = ribbon.alpha, ngrps = ngrps, type = type)\n \n ncolors = length(col)\n lgnd_labs = rep(NA, times = ncolors)\n if (isTRUE(by_continuous)) {\n ## Identify the pretty break points for our labels\n nlabs = 5\n ncolors = length(col)\n ubyvar = unique(by)\n byvar_range = range(ubyvar)\n pbyvar = pretty(byvar_range, n = nlabs)\n pbyvar = pbyvar[pbyvar >= byvar_range[1] & pbyvar <= byvar_range[2]]\n # optional thinning\n if (length(ubyvar) == 2 && all(ubyvar %in% pbyvar)) {\n pbyvar = ubyvar\n } else if (length(pbyvar) > nlabs) {\n pbyvar = pbyvar[seq_along(pbyvar) %% 2 == 0]\n }\n ## Find the (approximate) location of our pretty labels\n pidx = rescale_num(c(byvar_range, pbyvar), to = c(1, ncolors))[-c(1:2)]\n pidx = round(pidx)\n lgnd_labs[pidx] = pbyvar\n }\n\n # Determine the number and arrangement of facets.\n # Note: We're do this up front, so we can make some adjustments to legend cex\n # next (if there are facets). But the actual drawing of the facets will only\n # come later.\n attributes(datapoints$facet) = facet_attr ## TODO: better solution for restoring facet attributes?\n fargs = facet_layout(facet = datapoints$facet, facet.args = facet.args, add = add)\n list2env(fargs, environment())\n\n #\n ## Global plot elements (legend and titles)\n #\n\n # place and draw the legend\n has_legend = FALSE # simple indicator variable for later use\n\n if (!exists(\"legend_args\")) {\n legend_args = dots[[\"legend_args\"]]\n }\n if (is.null(legend_args)) legend_args = list(x = NULL)\n legend = substitute(legend)\n\n if (isFALSE(legend)) {\n legend = \"none\"\n } else if (isTRUE(legend)) {\n legend = NULL\n }\n if (!is.null(legend) && legend == \"none\") {\n legend_args[[\"x\"]] = \"none\"\n }\n\n if (null_by) {\n if (is.null(legend)) {\n legend = \"none\"\n legend_args[[\"x\"]] = \"none\"\n }\n }\n\n if ((is.null(legend) || legend != \"none\") && !add) {\n if (isFALSE(by_continuous)) {\n if (ngrps > 1) {\n lgnd_labs = if (is.factor(datapoints$by)) levels(datapoints$by) else unique(datapoints$by)\n } else {\n lgnd_labs = ylab\n }\n }\n\n has_sub = !is.null(sub)\n\n if (isTRUE(was_area_type) || isTRUE(type %in% c(\"area\", \"rect\", \"hist\", \"histogram\"))) {\n legend_args[[\"pt.lwd\"]] = par(\"lwd\")\n legend_args[[\"lty\"]] = 0\n }\n\n draw_legend(\n legend = legend,\n legend_args = legend_args,\n by_dep = by_dep,\n lgnd_labs = lgnd_labs,\n type = type,\n pch = pch,\n lty = lty,\n lwd = lwd,\n col = col,\n bg = bg,\n gradient = by_continuous,\n cex = cex * cex_fct_adj,\n has_sub = has_sub\n )\n\n has_legend = TRUE\n } else if (legend_args[[\"x\"]] == \"none\" && !add) {\n omar = par(\"mar\")\n ooma = par(\"oma\")\n topmar_epsilon = 0.1\n\n # Catch to avoid recursive offsets, e.g. repeated tinyplot calls with\n # \"bottom!\" legend position.\n\n ## restore inner margin defaults\n ## (in case the plot region/margins were affected by the preceding tinyplot call)\n if (any(ooma != 0)) {\n if (ooma[1] != 0 && omar[1] == par(\"mgp\")[1] + 1 * par(\"cex.lab\")) omar[1] = 5.1\n if (ooma[2] != 0 && omar[2] == par(\"mgp\")[1] + 1 * par(\"cex.lab\")) omar[2] = 4.1\n if (ooma[3] == topmar_epsilon && omar[3] != 4.1) omar[3] = 4.1\n if (ooma[4] != 0 && omar[4] == 0) omar[4] = 2.1\n par(mar = omar)\n }\n ## restore outer margin defaults (with a catch for custom mfrow plots)\n if (all(par(\"mfrow\") == c(1, 1))) {\n par(omd = c(0, 1, 0, 1))\n }\n\n # clean up for now\n rm(omar, ooma, topmar_epsilon)\n\n # Draw new plot\n plot.new()\n }\n\n # Titles. Only draw these if add = FALSE\n if (!add) {\n # main title\n # Note that we include a special catch for the main title if legend is\n # \"top!\" (and main is specified in the first place).\n legend_eval = tryCatch(eval(legend), error = function(e) NULL)\n # Extra bit of footwork if user passed legend = legend(...) instead of\n # legend = list(...), since the call environment is tricky\n if (is.null(legend_eval)) {\n legend_eval = tryCatch(paste0(legend)[[2]], error = function(e) NULL)\n }\n\n adj_title = !is.null(legend) && (legend == \"top!\" || (!is.null(legend_args[[\"x\"]]) && legend_args[[\"x\"]] == \"top!\") || (is.list(legend_eval) && legend_eval[[1]] == \"top!\"))\n\n # For the \"top!\" legend case, bump main title up to make space for the\n # legend beneath it: Take the normal main title line gap (i.e., 1.7 lines)\n # and add the difference between original top margin and new one (i.e.,\n # which should equal the height of the new legend). Note that we also\n # include a 0.1 epsilon bump, which we're using to reset the tinyplot\n # window in case of recursive \"top!\" calls. (See draw_legend code.)\n\n if (isTRUE(adj_title)) {\n line_main = par(\"mar\")[3] - opar[[\"mar\"]][3] + 1.7 + 0.1\n } else {\n line_main = NULL\n }\n\n if (!is.null(sub)) {\n if (isTRUE(get_tpar(\"side.sub\", 1) == 3)) {\n if (is.null(line_main)) line_main = par(\"mgp\")[3] + 1.7 - .1\n line_main = line_main + 1.2\n }\n if (isTRUE(get_tpar(\"side.sub\", 1) == 3)) {\n line_sub = get_tpar(\"line.sub\", 1.7)\n } else {\n line_sub = get_tpar(\"line.sub\", 4)\n }\n args = list(\n text = sub,\n line = line_sub,\n cex = get_tpar(\"cex.sub\", 1.2),\n col = get_tpar(\"col.sub\", \"black\"),\n adj = get_tpar(c(\"adj.sub\", \"adj\")),\n font = get_tpar(\"font.sub\", 1),\n side = get_tpar(\"side.sub\", 1),\n las = 1\n )\n args = Filter(function(x) !is.null(x), args)\n do.call(mtext, args)\n }\n\n if (!is.null(main)) {\n args = list(\n main = main,\n line = line_main,\n cex.main = get_tpar(\"cex.main\", 1.4),\n col.main = get_tpar(\"col.main\", \"black\"),\n font.main = get_tpar(\"font.main\", 2),\n adj = get_tpar(c(\"adj.main\", \"adj\"), 3))\n args = Filter(function(x) !is.null(x), args)\n do.call(title, args)\n }\n\n\n # Axis titles\n args = list(xlab = xlab)\n args[[\"adj\"]] = get_tpar(c(\"adj.xlab\", \"adj\"))\n do.call(title, args)\n args = list(ylab = ylab)\n args[[\"adj\"]] = get_tpar(c(\"adj.ylab\", \"adj\"))\n do.call(title, args)\n }\n\n #\n ## Exterior plot elements (plot and facet windows, axes, etc.)\n #\n\n omar = NULL # Placeholder variable for now, which we re-assign as part of facet margins\n\n # placeholders for facet_window_args() call\n facet_newlines = facet_text = facet_rect = facet_font = facet_col = facet_bg = facet_border = NULL\n\n if (!is.null(facet) && !add) {\n if (is.null(omar)) omar = par(\"mar\")\n\n # Grab some of the customizable facet args that we'll be using later\n facet_rect = FALSE\n facet_text = .tpar[[\"facet.cex\"]]\n facet_font = .tpar[[\"facet.font\"]]\n facet_col = .tpar[[\"facet.col\"]]\n facet_bg = .tpar[[\"facet.bg\"]]\n facet_border = .tpar[[\"facet.border\"]]\n if (!is.null(facet.args)) {\n if (!is.null(facet.args[[\"cex\"]])) facet_text = facet.args[[\"cex\"]]\n if (!is.null(facet.args[[\"col\"]])) facet_col = facet.args[[\"col\"]]\n if (!is.null(facet.args[[\"font\"]])) facet_font = facet.args[[\"font\"]]\n if (!is.null(facet.args[[\"bg\"]])) facet_bg = facet.args[[\"bg\"]]\n if (!is.null(facet.args[[\"border\"]])) facet_border = facet.args[[\"border\"]]\n }\n if (!is.null(facet_bg) || !is.null(facet_border)) facet_rect = TRUE\n\n # Need extra adjustment to top margin if facet titles have \"\\n\" newline\n # separator. (Note that we'll also need to take account for this in the\n # individual facet margins / gaps further below.)\n facet_newlines = lengths(gregexpr(\"\\n\", grep(\"\\\\n\", facets, value = TRUE)))\n # if (length(facet_newlines)==0) facet_newlines = 0\n # omar[3] = omar[3] + max(facet_newlines)\n facet_newlines = ifelse(length(facet_newlines) == 0, 0, max(facet_newlines))\n omar[3] = omar[3] + facet_newlines * facet_text / cex_fct_adj\n # apply the changes\n par(mar = omar)\n }\n\n # Now draw the individual facet windows (incl. axes, grid lines, and facet titles)\n # Will be skipped if adding to an existing plot; see ?facet\n\n facet_window_args = recordGraphics(\n draw_facet_window(\n add = add,\n # facet-specific args\n cex_fct_adj = cex_fct_adj,\n facet.args = facet.args,\n facet_newlines = facet_newlines, facet_font = facet_font,\n facet_rect = facet_rect, facet_text = facet_text,\n facet_col = facet_col, facet_bg = facet_bg, facet_border = facet_border,\n facet = facet,\n facets = facets, ifacet = ifacet,\n nfacets = nfacets, nfacet_cols = nfacet_cols, nfacet_rows = nfacet_rows,\n # axes args\n axes = axes, flip = flip, frame.plot = frame.plot,\n oxaxis = oxaxis, oyaxis = oyaxis,\n xlabs = xlabs, xlim = xlim, xlim_user = xlim_user, xaxt = xaxt, xaxs = xaxs, xaxb = xaxb, xaxl = xaxl,\n ylabs = ylabs, ylim = ylim, ylim_user = ylim_user, yaxt = yaxt, yaxs = yaxs, yaxb = yaxb, yaxl = yaxl,\n asp = asp, log = log,\n # other args (in approx. alphabetical + group ordering)\n dots = dots,\n draw = draw,\n grid = grid,\n has_legend = has_legend,\n type = type,\n x = x, xmax = xmax, xmin = xmin,\n y = y, ymax = ymax, ymin = ymin\n ),\n list = list(\n add = add,\n cex_fct_adj = cex_fct_adj,\n facet.args = facet.args,\n facet_newlines = facet_newlines, facet_font = facet_font,\n facet_rect = facet_rect, facet_text = facet_text,\n facet_col = facet_col, facet_bg = facet_bg, facet_border = facet_border,\n facet = datapoints$facet,\n facets = facets, ifacet = ifacet,\n nfacets = nfacets, nfacet_cols = nfacet_cols, nfacet_rows = nfacet_rows,\n axes = axes, flip = flip, frame.plot = frame.plot,\n oxaxis = oxaxis, oyaxis = oyaxis,\n xlabs = xlabs, xlim = xlim, xlim_user = xlim_user, xaxt = xaxt, xaxs = xaxs, xaxb = xaxb, xaxl = xaxl,\n ylabs = ylabs, ylim = ylim, ylim_user = ylim_user, yaxt = yaxt, yaxs = yaxs, yaxb = yaxb, yaxl = yaxl,\n asp = asp, log = log,\n dots = dots,\n draw = draw,\n grid = grid,\n has_legend = has_legend,\n type = type,\n x = datapoints$x, xmax = datapoints$xmax, xmin = datapoints$xmin,\n y = datapoints$y, ymax = datapoints$ymax, ymin = datapoints$ymin\n ),\n getNamespace(\"tinyplot\")\n )\n list2env(facet_window_args, environment())\n\n\n #\n ## Interior plot elements\n #\n\n # Finally, we can draw all of the plot elements (points, lines, etc.)\n # We'll do this via a nested loops:\n # 1) Outer loop over facets\n # 2) Inner loop over groups\n\n ## Outer loop over the facets\n for (i in seq_along(split_data)) {\n # Split group-level data again to grab any \"by\" groups\n idata = split_data[[i]]\n iby = idata[[\"by\"]]\n if (!null_by) { ## maybe all(iby==\"\")\n if (isTRUE(by_continuous)) {\n idata[[\"col\"]] = col[round(rescale_num(idata$by, from = range(datapoints$by), to = c(1, 100)))]\n idata[[\"bg\"]] = bg[round(rescale_num(idata$by, from = range(datapoints$by), to = c(1, 100)))]\n idata = list(idata)\n } else {\n idata = lapply(idata, split, iby)\n idata = do.call(function(...) Map(\"list\", ...), idata)\n }\n } else {\n idata = list(idata)\n if (isTRUE(by_continuous)) {\n if (length(col) != 1) {\n idata[[1]][[\"col\"]] = col[round(rescale_num(by, to = c(1, 100)))]\n } else {\n idata[[1]][[\"col\"]] = col\n }\n if (length(bg) != 1) {\n idata[[1]][[\"bg\"]] = bg[round(rescale_num(by, to = c(1, 100)))]\n } else {\n idata[[1]][[\"bg\"]] = bg\n }\n }\n }\n \n # Set the facet \"window\" manually\n # See: https://github.com/grantmcdermott/tinyplot/issues/65\n if (nfacets > 1) {\n mfgi = ceiling(i / nfacet_cols)\n mfgj = i %% nfacet_cols\n if (mfgj == 0) mfgj = nfacet_cols\n par(mfg = c(mfgi, mfgj))\n\n # For free facets, we need to reset par(usr) based extent of that\n # particular facet... which we calculated and saved to the .fusr env var\n # (list) back in draw_facet_window()\n if (isTRUE(facet.args[[\"free\"]])) {\n fusr = get(\".fusr\", envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n par(usr = fusr[[i]])\n }\n }\n\n\n ## Inner loop over the \"by\" groupings\n for (ii in seq_along(idata)) {\n icol = col[ii]\n ibg = bg[ii]\n ipch = pch[ii]\n ilty = lty[ii]\n ilwd = lwd[ii]\n \n ix = idata[[ii]][[\"x\"]]\n iy = idata[[ii]][[\"y\"]]\n iz = idata[[ii]][[\"z\"]]\n ixmin = idata[[ii]]$xmin\n ixmax = idata[[ii]]$xmax\n iymin = idata[[ii]]$ymin\n iymax = idata[[ii]]$ymax\n ilabels = idata[[ii]][[\"labels\"]]\n\n if (isTRUE(by_continuous)) {\n icol = idata[[ii]]$col\n ibg = idata[[ii]]$bg\n }\n\n # empty plot flag\n empty_plot = FALSE\n if (isTRUE(empty) || isTRUE(type == \"n\") || ((length(ix) == 0) && !(type %in% c(\"histogram\", \"hist\", \"rect\", \"segments\", \"spineplot\")))) {\n empty_plot = TRUE\n }\n\n # Draw the individual plot elements...\n if (!isTRUE(empty_plot)) {\n if (is.null(type_draw)) {\n type_draw = switch(type,\n \"ribbon\" = type_ribbon()$draw,\n \"polygon\" = type_polygon()$draw,\n \"rect\" = type_rect()$draw,\n \"p\" = ,\n \"points\" = type_points()$draw,\n \"l\" = ,\n \"o\" = ,\n \"b\" = ,\n \"c\" = ,\n \"h\" = ,\n \"s\" = ,\n \"S\" = type_lines(type = type)$draw\n )\n }\n type_draw(\n ibg = ibg,\n icol = icol,\n ilty = ilty,\n ilwd = ilwd,\n ipch = ipch,\n ix = ix,\n ixmax = ixmax,\n ixmin = ixmin,\n iy = iy,\n iymax = iymax,\n iymin = iymin,\n ilabels = ilabels,\n iz = iz,\n cex = cex,\n dots = dots,\n type = type,\n x_by = x_by,\n by_continuous = by_continuous,\n iby = ii,\n ifacet = i,\n facet_by = facet_by,\n data_facet = idata,\n ngrps = ngrps,\n nfacets = nfacets,\n flip = flip,\n type_info = type_info,\n facet_window_args = facet_window_args\n )\n }\n }\n }\n \n if (!add) {\n # save end pars for possible recall later\n recordGraphics(\n {\n apar = par(no.readonly = TRUE)\n set_saved_par(when = \"after\", apar)\n },\n list = list(), \n env = getNamespace('tinyplot')\n )\n }\n\n}\n\n\n\n\n#' @rdname tinyplot\n#' @importFrom stats as.formula model.frame terms\n#' @export\ntinyplot.formula = function(\n x = NULL,\n data = parent.frame(),\n facet = NULL,\n facet.args = NULL,\n type = NULL,\n xmin = NULL,\n xmax = NULL,\n ymin = NULL,\n ymax = NULL,\n xlim = NULL,\n ylim = NULL,\n # log = \"\",\n main = NULL,\n sub = NULL,\n xlab = NULL,\n ylab = NULL,\n ann = par(\"ann\"),\n axes = TRUE,\n frame.plot = NULL,\n asp = NA,\n grid = NULL,\n pch = NULL,\n col = NULL,\n lty = NULL,\n lwd = NULL,\n restore.par = FALSE,\n formula = NULL,\n subset = NULL,\n na.action = NULL,\n drop.unused.levels = TRUE,\n ...) {\n ## formula for variables must be specified through 'x' or 'formula' but not both\n if (is.null(x)) {\n if (missing(formula)) {\n stop(\"plot formula must be specified by either 'x' or 'formula' argument\")\n }\n } else {\n if (missing(formula)) {\n formula = x\n } else {\n warning(\"only one of the arguments 'x' and 'formula' should be specified, defaulting to the 'formula' argument\")\n }\n }\n\n ## placeholder for legend title\n legend_args = list(x = NULL)\n\n ## turn facet into a formula if it does not evaluate successfully\n if (inherits(try(facet, silent = TRUE), \"try-error\")) {\n facet = as.formula(paste(\"~\", deparse(substitute(facet))))\n environment(facet) = environment(formula)\n }\n\n ## process all formulas\n tf = tinyformula(formula, facet)\n\n ## set up model frame\n m = match.call(expand.dots = FALSE)\n m = m[c(1L, match(c(\"formula\", \"data\", \"subset\", \"na.action\", \"drop.unused.levels\", \"xmin\", \"xmax\", \"ymin\", \"ymax\"), names(m), 0L))]\n m$formula = tf$full\n ## need stats:: for non-standard evaluation\n m[[1L]] = quote(stats::model.frame)\n mf = eval.parent(m)\n\n ## extract x\n x = tinyframe(tf$x, mf)\n xnam = names(x)[[1L]]\n if (length(names(x)) != 1L) warning(\n paste(\"formula should specify exactly one x-variable, using:\", xnam),\n \"\\nif you want to use arithmetic operators, make sure to wrap them inside I()\")\n x = x[[xnam]]\n\n ## extract y (if any)\n y = tinyframe(tf$y, mf)\n if (!is.null(y)) {\n ynam = names(y)[[1L]]\n if (length(names(y)) > 1L) warning(paste(\"formula should specify at most one y-variable, using:\", ynam),\n \"\\nif you want to use arithmetic operators, make sure to wrap them inside I()\")\n y = y[[ynam]]\n }\n\n ## extract by (if any)\n by = tinyframe(tf$by, mf)\n if (!is.null(by)) {\n bynam = names(by)\n by = if (length(bynam) == 1L) by[[bynam]] else interaction(by, sep = \":\")\n }\n\n ## extract x/y facet (if formula)\n if (!is.null(tf$xfacet) || !is.null(tf$yfacet)) {\n xfacet = tinyframe(tf$xfacet, mf)\n yfacet = tinyframe(tf$yfacet, mf)\n if (!is.null(xfacet)) xfacet = if (ncol(xfacet) == 1L) xfacet[[1L]] else interaction(xfacet, sep = \":\")\n if (!is.null(yfacet)) yfacet = if (ncol(yfacet) == 1L) yfacet[[1L]] else interaction(yfacet, sep = \":\")\n if (is.null(yfacet)) {\n facet = xfacet\n } else {\n facet = interaction(xfacet, yfacet, sep = \"~\")\n attr(facet, \"facet_grid\") = TRUE\n attr(facet, \"facet_nrow\") = length(unique(yfacet))\n }\n }\n\n ## nice axis and legend labels\n dens_type = (is.atomic(type) && identical(type, \"density\")) || (!is.atomic(type) && identical(type$name, \"density\"))\n hist_type = (is.atomic(type) && type %in% c(\"hist\", \"histogram\")) || (!is.atomic(type) && identical(type$name, \"histogram\"))\n if (!is.null(type) && dens_type) {\n # if (is.null(ylab)) ylab = \"Density\" ## rather assign ylab as part of internal type_density() logic\n if (is.null(xlab)) xlab = xnam\n } else if (!is.null(type) && hist_type) {\n # if (is.null(ylab)) ylab = \"Frequency\" ## rather assign ylab as part of internal type_histogram() logic\n if (is.null(xlab)) xlab = xnam\n } else if (is.null(y)) {\n if (is.null(ylab)) ylab = xnam\n if (is.null(xlab)) xlab = \"Index\"\n } else {\n if (is.null(ylab)) ylab = ynam\n if (is.null(xlab)) xlab = xnam\n }\n if (!is.null(by)) {\n legend_args[[\"title\"]] = if (length(bynam) == 1L) bynam else sprintf(\"interaction(%s)\", paste(bynam, collapse = \", \"))\n }\n\n tinyplot.default(\n x = x, y = y, by = by,\n facet = facet, facet.args = facet.args,\n data = data,\n type = type,\n xmin = mf[[\"(xmin)\"]],\n xmax = mf[[\"(xmax)\"]],\n ymin = mf[[\"(ymin)\"]],\n ymax = mf[[\"(ymax)\"]],\n xlim = xlim,\n ylim = ylim,\n # log = \"\",\n main = main,\n sub = sub,\n xlab = xlab,\n ylab = ylab,\n ann = ann,\n axes = axes,\n frame.plot = frame.plot,\n asp = asp,\n grid = grid,\n legend_args = legend_args,\n pch = pch,\n col = col,\n lty = lty,\n lwd = lwd,\n restore.par = restore.par,\n ...\n )\n}\n\n#' @rdname tinyplot\n#' @export\ntinyplot.density = function(\n x = NULL,\n type = c(\"l\", \"area\"),\n ...) {\n \n dots = list(...)\n \n if (!is.null(dots[[\"by\"]]) || !is.null(dots[[\"facet\"]])) {\n stop(\n '\\nGrouped and/or faceted plots are no longer supported with the tinyplot.density() method. ',\n '\\nPlease use the dedicated type argument instead, e.g. `tinyplot(..., type = \"density\")`. See `?type_density` for details.',\n '\\n\\nThis breaking change was introduced in tinyplot v0.3.0.'\n )\n }\n \n type = match.arg(type)\n \n ## override if bg = \"by\"\n if (!is.null(dots[[\"bg\"]]) || !is.null(dots[[\"fill\"]])) type = \"area\"\n \n if (inherits(x, \"density\")) {\n object = x\n # legend_args = list(x = NULL)\n # # Grab by label to pass on legend title to tinyplot.default\n # legend_args[[\"title\"]] = deparse(substitute(by))\n } else {\n ## An internal catch for non-density objects that were forcibly\n ## passed to tinyplot.density (e.g., via a one-side formula)\n if (anyNA(x)) {\n x = na.omit(x)\n x = as.numeric(x)\n }\n object = density(x)\n }\n \n x = object$x\n y = object$y\n \n if (type == \"area\") {\n ymin = rep(0, length(y))\n ymax = y\n # # set extra legend params to get bordered boxes with fill\n # legend_args[[\"x.intersp\"]] = 1.25\n # legend_args[[\"lty\"]] = 0\n # legend_args[[\"pt.lwd\"]] = 1\n }\n \n # splice in change arguments\n dots[[\"x\"]] = x\n dots[[\"y\"]] = y\n dots[[\"type\"]] = type\n \n ## axes range\n if (is.null(dots[[\"xlim\"]])) dots[[\"xlim\"]] = range(x)\n if (is.null(dots[[\"ylim\"]])) dots[[\"ylim\"]] = range(y)\n \n ## nice labels and titles\n if (is.null(dots[[\"ylab\"]])) dots[[\"ylab\"]] = \"Density\"\n if (is.null(dots[[\"xlab\"]])) dots[[\"xlab\"]] = paste0(\"N = \", object$n, \" Bandwidth = \", sprintf(\"%.4g\", object$bw))\n if (is.null(dots[[\"main\"]])) dots[[\"main\"]] = paste0(paste(object$call, collapse = \"(x = \"), \")\")\n \n do.call(tinyplot.default, args = dots)\n \n}\n\n\n#' @export\n#' @name plt\n#' @rdname tinyplot\nplt = tinyplot\n"], ["/tinyplot/R/type_density.R", "#' Density plot type\n#' \n#' @md\n#' @description Type function for density plots.\n#' @inheritParams stats::density\n#' @param kernel a character string giving the smoothing kernel to be used. This\n#' must partially match one of `\"gaussian\"`, `\"rectangular\"`, `\"triangular\"`,\n#' `\"epanechnikov\"`, `\"biweight\"`, `\"cosine\"` or `\"optcosine\"`, with default\n#' `\"gaussian\"`, and may be abbreviated to a unique prefix (single letter).\n#'\n#' `\"cosine\"` is smoother than `\"optcosine\"`, which is the usual 'cosine'\n#' kernel in the literature and almost MSE-efficient. However, `\"cosine\"` is\n#' the version used by S.\n#' @inheritParams type_ribbon\n#' @param joint.bw character string indicating whether (and how) the smoothing\n#' bandwidth should be computed from the joint data distribution when there\n#' are multiple subgroups. The options are `\"mean\"` (the default), `\"full\"`,\n#' and `\"none\"`. Also accepts a logical argument, where `TRUE` maps to\n#' `\"mean\"` and `FALSE` maps to `\"none\"`. See the \"Bandwidth selection\"\n#' section below for a discussion of practical considerations.\n#' @inherit stats::density details\n#' @section Bandwidth selection: While the choice of smoothing bandwidth will\n#' always stand to affect a density visualization, it gains an added\n#' importance when multiple densities are drawn simultaneously (e.g., for\n#' subgroups with respect to `by` or `facet`). Allowing each subgroup to\n#' compute its own separate bandwidth independently offers greater flexibility\n#' in capturing the unique characteristics of each subgroup, particularly when\n#' distributions differ substantially in location and/or scale. However, this\n#' approach may overemphasize small random variations and make it harder to\n#' visually compare densities across subgroups. Hence, it is often useful to\n#' employ the same (\"joint\") bandwidth across all subgroups. The following\n#' strategies are available via the `joint.bw` argument:\n#' \n#' - The default `joint.bw = \"mean\"` first computes the individual bandwidths\n#' for each group but then computes their mean, weighted by the number of\n#' observations in each group. This will work well when all groups have\n#' similar amounts of scatter (similar variances), even when they have\n#' potentially rather different locations. The weighted averaging stabilizes\n#' potential fluctuations in the individual bandwidths, especially when some\n#' subgroups are rather small.\n#' \n#' - Alternatively, `joint.bw = \"full\"` can be used to compute the joint\n#' bandwidth from the full joint distribution (merging all groups). This will\n#' yield an even more robust bandwidth, especially when the groups overlap\n#' substantially (i.e., have similar locations and scales). However, it may\n#' lead to too large bandwidths and thus too much smoothing, especially when\n#' the locations of the groups differ substantially.\n#' \n#' - Finally, `joint.bw = \"none\"` disables the joint bandwidth so that each\n#' group just employs its individual bandwidth. This is often the best choice\n#' if the amounts of scatter differ substantially between the groups, thus\n#' necessitating different amounts of smoothing.\n#' @section Titles: This tinyplot method for density plots differs from the base\n#' \\code{\\link[stats]{plot.density}} function in its treatment of titles. The\n#' x-axis title displays only the variable name, omitting details about the\n#' number of observations and smoothing bandwidth. Additionally, the main\n#' title is left blank by default for a cleaner appearance.\n#' @examples\n#' # \"density\" type convenience string\n#' tinyplot(~Sepal.Length, data = iris, type = \"density\")\n#' \n#' # grouped density example\n#' tinyplot(~Sepal.Length | Species, data = iris, type = \"density\")\n#' \n#' # use `bg = \"by\"` (or, equivalent `fill = \"by\"`) to get filled densities\n#' tinyplot(~Sepal.Length | Species, data = iris, type = \"density\", fill = \"by\")\n#' \n#' # use `type_density()` to pass extra arguments for customization\n#' tinyplot(\n#' ~Sepal.Length | Species, data = iris,\n#' type = type_density(bw = \"SJ\"),\n#' main = \"Bandwidth computed using Sheather & Jones (1991)\"\n#' )\n#' \n#' # The default for grouped density plots is to use the mean of the\n#' # individual subgroup bandwidths (weighted by group size) as the\n#' # joint bandwidth. Alternatively, the bandwidth from the \"full\"\n#' # data or separate individual bandwidths (\"none\") can be used.\n#' tinyplot(~Sepal.Length | Species, data = iris,\n#' ylim = c(0, 1.25), type = \"density\") # mean (default)\n#' tinyplot_add(joint.bw = \"full\", lty = 2) # full data\n#' tinyplot_add(joint.bw = \"none\", lty = 3) # none (individual)\n#' legend(\"topright\", c(\"Mean\", \"Full\", \"None\"), lty = 1:3, bty = \"n\", title = \"Joint BW\")\n#' \n#' @importFrom stats density weighted.mean\n#' @importFrom stats bw.SJ bw.bcv bw.nrd bw.nrd0 bw.ucv \n#' @export\ntype_density = function(\n bw = \"nrd0\",\n joint.bw = c(\"mean\", \"full\", \"none\"),\n adjust = 1,\n kernel = c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"),\n n = 512,\n # more args from density here?\n alpha = NULL\n ) {\n kernel = match.arg(kernel, c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"))\n if (is.logical(joint.bw)) {\n joint.bw = ifelse(joint.bw, \"mean\", \"none\")\n }\n joint.bw = match.arg(joint.bw, c(\"mean\", \"full\", \"none\"))\n out = list(\n data = data_density(bw = bw, adjust = adjust, kernel = kernel, n = n,\n joint.bw = joint.bw, alpha = alpha),\n draw = NULL,\n name = \"density\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\ndata_density = function(bw = \"nrd0\", adjust = 1, kernel = \"gaussian\", n = 512,\n joint.bw = \"none\", alpha = NULL) {\n fun = function(by, facet, ylab, col, bg, ribbon.alpha, datapoints, ...) {\n \n ribbon.alpha = if (is.null(alpha)) .tpar[[\"ribbon.alpha\"]] else (alpha)\n \n if (is.null(ylab)) ylab = \"Density\"\n \n datapoints = split(datapoints, list(datapoints$by, datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n \n if (joint.bw == \"none\" || is.numeric(bw)) {\n dens_bw = bw\n } else {\n if (joint.bw == \"mean\") {\n # Use weighted mean of subgroup bandwidths\n bws = sapply(datapoints, function(dat) bw_fun(kernel = bw, dat$x))\n ws = sapply(datapoints, nrow)\n dens_bw = weighted.mean(bws, ws)\n } else if (joint.bw == \"full\") {\n dens_bw = bw_fun(kernel = bw, unlist(sapply(datapoints, `[[`, \"x\")))\n }\n }\n \n datapoints = lapply(datapoints, function(dat) {\n d = density(dat$x, bw = dens_bw, kernel = kernel, n = n)\n out = data.frame(\n by = dat$by[1], # already split\n facet = dat$facet[1], # already split\n y = d$y,\n x = d$x\n )\n return(out)\n })\n datapoints = do.call(rbind, datapoints)\n datapoints$ymax = datapoints$y\n datapoints$ymin = rep.int(0, nrow(datapoints))\n \n # flags for legend and fill\n dtype = if (!is.null(bg)) \"ribbon\" else \"l\"\n dwas_area_type = !is.null(bg)\n \n out = list(\n ylab = ylab,\n type = dtype,\n was_area_type = dwas_area_type,\n ribbon.alpha = ribbon.alpha,\n datapoints = datapoints,\n by = if (length(unique(datapoints$by)) == 1) by else datapoints$by, \n facet = if (length(unique(datapoints$facet)) == 1) facet else datapoints$facet\n )\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_histogram.R", "#' Histogram plot type\n#' \n#' @md\n#' @description Type function for histogram plots. `type_hist` is an alias for\n#' `type_histogram`.\n#' @param breaks Passed to \\code{\\link[graphics]{hist}}. One of:\n#' - a vector giving the breakpoints between histogram cells,\n#' - a function to compute the vector of breakpoints,\n#' - a single number giving the number of cells for the histogram,\n#' - a character string naming an algorithm to compute the number of cells (see ‘Details’ of \\code{\\link[graphics]{hist}}),\n#' - a function to compute the number of cells.\n#' In the last three cases the number is a suggestion only; as the breakpoints\n#' will be set to pretty values, the number is limited to 1e6 (with a warning if\n#' it was larger). If breaks is a function, the x vector is supplied to it as\n#' the only argument (and the number of breaks is only limited by the amount of\n#' available memory).\n#' @param free.breaks Logical indicating whether the breakpoints should be\n#' computed separately for each group or facet? Default is `FALSE`, meaning\n#' that the breakpoints are computed from the full dataset; thus ensuring\n#' common bin widths across each group/facet. Can also use `free` as an\n#' acceptable argument alias. Ignored if there are no groups and/or facets.\n#' @param drop.zeros Logical indicating whether bins with zero counts should be\n#' dropped before plotting. Default is `TRUE`. Note that switching to `FALSE`\n#' may interfere with faceted plot behaviour if `facet.args = list(free)`,\n#' since the `x` variable is effectively recorded over the full range of the\n#' x-axis (even if it does not extend over this range for every group).\n#' @inheritParams graphics::hist\n#' @examples\n#' # \"histogram\"/\"hist\" type convenience string(s)\n#' tinyplot(Nile, type = \"histogram\")\n#' \n#' # Use `type_histogram()` to pass extra arguments for customization\n#' tinyplot(Nile, type = type_histogram(breaks = 30))\n#' tinyplot(Nile, type = type_histogram(breaks = 30, freq = FALSE))\n#' # etc.\n#' \n#' # Grouped histogram example\n#' tinyplot(\n#' ~Petal.Width | Species,\n#' type = \"histogram\",\n#' data = iris\n#' )\n#' \n#' # Faceted version\n#' tinyplot(\n#' ~Petal.Width, facet = ~Species,\n#' type = \"histogram\",\n#' data = iris\n#' )\n#' \n#' # For visualizing faceted histograms across varying scales, you may also wish\n#' # to impose free histogram breaks too (i.e., calculate breaks separately for\n#' # each group). Compare:\n#' \n#' # free facet scales + shared histogram breaks, versus...\n#' tinyplot(\n#' ~Petal.Width, facet = ~Species,\n#' facet.args = list(free = TRUE),\n#' type = type_histogram(),\n#' data = iris\n#' )\n#' # ... free facet scales + free histogram breaks\n#' tinyplot(\n#' ~Petal.Width, facet = ~Species,\n#' facet.args = list(free = TRUE),\n#' type = type_histogram(free = TRUE),\n#' data = iris\n#' )\n#' \n#' @export\ntype_histogram = function(breaks = \"Sturges\",\n freq = NULL, right = TRUE,\n free.breaks = FALSE, drop.zeros = TRUE) {\n out = list(\n data = data_histogram(breaks = breaks,\n free.breaks = free.breaks, drop.zeros = drop.zeros,\n freq = freq, right = right),\n draw = draw_rect(),\n name = \"histogram\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n#' @export\n#' @name type_hist\n#' @rdname type_histogram\ntype_hist = type_histogram\n\n\ndata_histogram = function(breaks = \"Sturges\",\n free.breaks = FALSE, drop.zeros = TRUE,\n freq = NULL, right = TRUE) {\n \n hbreaks = breaks\n hfree.breaks = free.breaks\n hdrop.zeros = drop.zeros\n hfreq = freq\n hright = right\n \n fun = function(by, facet, ylab, col, bg, ribbon.alpha, datapoints, .breaks = hbreaks, .freebreaks = hfree.breaks, .freq = hfreq, .right = hright, .drop.zeros = hdrop.zeros, ...) {\n \n hbreaks = ifelse(!sapply(.breaks, is.null), .breaks, \"Sturges\")\n \n if (is.null(by) && is.null(palette)) {\n if (is.null(col)) col = par(\"fg\")\n if (is.null(bg)) bg = \"lightgray\"\n } else {\n if (is.null(bg)) bg = ribbon.alpha\n }\n\n if (!.freebreaks) xbreaks = hist(datapoints$x, breaks = hbreaks, right = .right, plot = FALSE)$breaks\n datapoints = split(datapoints, list(datapoints$by, datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n \n datapoints = lapply(datapoints, function(k) {\n if (.freebreaks) xbreaks = breaks\n h = hist(k$x, breaks = xbreaks, right = .right, plot = FALSE)\n # zero count cases\n if (.drop.zeros) {\n nzidx = which(h$counts > 0)\n h$density = h$density[nzidx]\n h$counts = h$counts[nzidx]\n h$breaks = h$breaks[c(1, nzidx+1)]\n h$mids = h$mids[nzidx]\n }\n freq = if(!is.null(.freq)) .freq else is.null(.freq) && h$equidist\n out = data.frame(\n by = k$by[1], # already split\n facet = k$facet[1], # already split\n ymin = 0,\n ymax = if (freq) h$counts else h$density,\n xmin = h$breaks[-1],\n xmax = h$mids + (h$mids - h$breaks[-1]),\n freq = freq\n )\n return(out)\n })\n datapoints = do.call(rbind, datapoints)\n \n if (is.null(ylab)) {\n ylab = ifelse(datapoints$freq[1], \"Frequency\", \"Density\")\n }\n\n out = list(\n x = c(datapoints$xmin, datapoints$xmax), \n y = c(datapoints$ymin, datapoints$ymax),\n ymin = datapoints$ymin, \n ymax = datapoints$ymax, \n xmin = datapoints$xmin, \n xmax = datapoints$xmax, \n ylab = ylab, \n col = col, \n bg = bg, \n datapoints = datapoints,\n by = if (length(unique(datapoints$by)) == 1) by else datapoints$by, \n facet = if (length(unique(datapoints$facet)) == 1) facet else datapoints$facet\n )\n return(out)\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_boxplot.R", "#' Boxplot type\n#' \n#' @description Type function for producing box-and-whisker plots.\n#' Arguments are passed to \\code{\\link[graphics]{boxplot}}, although `tinyplot`\n#' scaffolding allows added functionality such as grouping and faceting.\n#' Box-and-whisker plots are the default plot type if `x` is a factor and `y` is\n#' numeric.\n#'\n#' @inheritParams graphics::boxplot\n#' @examples\n#' # \"boxplot\" type convenience string\n#' tinyplot(count ~ spray, data = InsectSprays, type = \"boxplot\")\n#' \n#' # Note: Specifying the type here is redundant. Like base plot, tinyplot\n#' # automatically produces a boxplot if x is a factor and y is numeric\n#' tinyplot(count ~ spray, data = InsectSprays)\n#' \n#' # Grouped boxplot example\n#' tinyplot(len ~ dose | supp, data = ToothGrowth, type = \"boxplot\")\n#' \n#' # Use `type_boxplot()` to pass extra arguments for customization\n#' tinyplot(\n#' len ~ dose | supp, data = ToothGrowth, lty = 1,\n#' type = type_boxplot(boxwex = 0.3, staplewex = 0, outline = FALSE)\n#' )\n#' @export\ntype_boxplot = function(\n range = 1.5,\n width = NULL,\n varwidth = FALSE,\n notch = FALSE,\n outline = TRUE,\n boxwex = 0.8,\n staplewex = 0.5,\n outwex = 0.5) {\n out = list(\n draw = draw_boxplot(\n range = range,\n width = width,\n varwidth = varwidth,\n notch = notch,\n outline = outline,\n boxwex = boxwex,\n staplewex = staplewex,\n outwex = outwex),\n data = data_boxplot(),\n name = \"boxplot\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\n\ndraw_boxplot = function(range, width, varwidth, notch, outline, boxwex, staplewex, outwex) {\n fun = function(iby, ix, iy, ipch, ilty, icol, ibg, x_by = FALSE, facet_by = FALSE, ngrps = 1, flip, ...) {\n\n at_ix = unique(ix)\n if (isTRUE(x_by)) boxwex = boxwex * 2\n\n # Handle multiple groups\n if (ngrps > 1 && isFALSE(x_by) && isFALSE(facet_by)) {\n boxwex_orig = boxwex\n boxwex = boxwex / ngrps - 0.01\n at_ix = at_ix + seq(\n -((boxwex_orig - boxwex) / 2),\n ((boxwex_orig - boxwex) / 2),\n length.out = ngrps\n )[iby]\n }\n\n boxplot(\n formula = iy ~ ix,\n pch = ipch,\n lty = ilty,\n border = icol,\n col = ibg,\n horizontal = flip,\n add = TRUE, axes = FALSE,\n at = at_ix,\n range = range,\n width = width,\n varwidth = varwidth,\n notch = notch,\n outline = outline,\n boxwex = boxwex,\n staplewex = staplewex,\n outwex = outwex\n )\n }\n return(fun)\n}\n\n\n\ndata_boxplot = function() {\n fun = function(datapoints, bg, col, palette, null_by, null_facet, ...) {\n # Convert x to factor if it's not already\n datapoints$x = as.factor(datapoints$x)\n\n # Handle factor levels and maintain order\n xlvls = levels(datapoints$x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n datapoints$x = as.integer(datapoints$x)\n\n if (null_by && null_facet) {\n xord = order(datapoints$x)\n } else if (null_facet) {\n xord = order(datapoints$by, datapoints$x)\n } else if (null_by) {\n xord = order(datapoints$facet, datapoints$x)\n } else {\n xord = order(datapoints$by, datapoints$facet, datapoints$x)\n }\n\n if (length(unique(datapoints[[\"by\"]])) == 1 && is.null(palette)) {\n if (is.null(col)) col = par(\"fg\")\n if (is.null(bg)) bg = \"lightgray\"\n } else {\n bg = \"by\"\n }\n\n # Reorder x, y, ymin, and ymax based on the order determined\n datapoints = datapoints[xord,]\n\n # Return the result as a list called 'out'\n out = list(\n x = datapoints$x,\n y = datapoints$y,\n ymin = datapoints$ymin,\n ymax = datapoints$ymax,\n xlabs = xlabs,\n datapoints = datapoints,\n col = col,\n bg = bg)\n\n if (length(unique(datapoints$by)) > 1) out[[\"by\"]] = datapoints$by\n if (length(unique(datapoints$facet)) > 1) out[[\"facet\"]] = datapoints$facet\n\n return(out)\n }\n return(fun)\n}\n\n\n\n\n"], ["/tinyplot/R/type_summary.R", "#' Plot summary values of `y` at unique values of `x`\n#'\n#' @md\n#' @description\n#' Applies a summary function to `y` along unique values of `x`. For example,\n#' plot the mean `y` value for each `x` value. Internally,\n#' `type_summary()` applies a thin wrapper around \\code{\\link[stats]{ave}} and\n#' then passes the result to [`type_lines`] for drawing.\n#'\n#' @param fun summarizing function. Should be compatible with\n#' \\code{\\link[stats]{ave}}. Defaults to \\code{\\link[base]{mean}}.\n#' @param ... Additional arguments are passed to the `lines()` function,\n#' ex: `type=\"p\"`, `col=\"pink\"`.\n#' @seealso [`ave`] which performs the summarizing (averaging) behind the\n#' scenes.\n#' @examples\n#' # Plot the mean chick weight over time\n#' tinyplot(weight ~ Time, data = ChickWeight, type = \"summary\")\n#' \n#' # Note: \"mean\" is the default function, so these are also equivalent:\n#' # tinyplot(weight ~ Time, data = ChickWeight, type = type_summary())\n#' # tinyplot(weight ~ Time, data = ChickWeight, type = type_summary(mean))\n#' \n#' # Plot the median instead\n#' tinyplot(weight ~ Time, data = ChickWeight, type = type_summary(median))\n#' \n#' # Works with groups and/or facets too\n#' tinyplot(weight ~ Time | Diet, facet = \"by\", data = ChickWeight, type = \"summary\")\n#'\n#' # Custom/complex function example\n#' tinyplot(\n#' weight ~ Time | Diet, facet = \"by\", data = ChickWeight,\n#' type = type_summary(function(y) quantile(y, probs = 0.9)/max(y))\n#' )\n#' \n#' @importFrom stats ave\n#' @export\ntype_summary = function(fun = mean, ...) {\n assert_function(fun)\n lines_args = list(...)\n data_summary = function(fun) {\n funky = function(datapoints, ...) {\n datapoints = split(datapoints, list(datapoints$facet, datapoints$by), drop = TRUE)\n datapoints = lapply(datapoints, function(dat) {\n newy = ave(dat$y, dat$x, FUN = fun)\n dat$y = newy\n dat = dat[order(dat$x), ]\n return(dat)\n })\n datapoints = do.call(rbind, datapoints)\n out = list(datapoints = datapoints)\n return(out)\n }\n return(funky)\n }\n out = list(\n draw = draw_lines(...),\n data = data_summary(fun = fun),\n name = \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_ribbon.R", "#' Ribbon and area plot types\n#' \n#' @param alpha numeric value between 0 and 1 specifying the opacity of ribbon shading\n#' If no `alpha` value is provided, then will default to `tpar(\"ribbon.alpha\")` \n#' (i.e., probably `0.2` unless this has been overridden by the user in their global \n#' settings.)\n#'\n#' @description Type constructor functions for producing polygon ribbons, which \n#' define a `y` interval (usually spanning from `ymin` to `ymax`) for each\n#' `x` value. Area plots are a special case of ribbon plot where `ymin` is\n#' set to 0 and `ymax` is set to `y`.\n#' \n#' @examples\n#' x = 1:100/10\n#' y = sin(x)\n#' \n#' #\n#' ## Ribbon plots\n#' \n#' # \"ribbon\" convenience string\n#' tinyplot(x = x, ymin = y-1, ymax = y+1, type = \"ribbon\")\n\n#' # Same result with type_ribbon()\n#' tinyplot(x = x, ymin = y-1, ymax = y+1, type = type_ribbon())\n#' \n#' # y will be added as a line if it is specified\n#' tinyplot(x = x, y = y, ymin = y-1, ymax = y+1, type = \"ribbon\")\n#'\n#' #\n#' ## Area plots\n#' \n#' # \"area\" type convenience string\n#' tinyplot(x, y, type = \"area\")\n#' \n#' # Same result with type_area()\n#' tinyplot(x, y, type = type_area())\n#' \n#' # Area plots are often used for time series charts\n#' tinyplot(AirPassengers, type = \"area\")\n#' @export\ntype_ribbon = function(alpha = NULL) {\n out = list(\n draw = draw_ribbon(),\n data = data_ribbon(ribbon.alpha = alpha),\n name = \"ribbon\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_ribbon = function() {\n fun = function(ix, iy, ixmin, ixmax, iymin, iymax, ibg, ilty, ilwd, icol, ipch, i, flip = FALSE, ...) {\n polyg = type_polygon()$draw\n lin = type_lines()$draw\n if (isFALSE(flip)) {\n polyg(ix = c(ix, rev(ix)), iy = c(iymin, rev(iymax)), icol = NA, ibg = ibg)\n } else {\n polyg(c(ixmin, rev(ixmax)), iy = c(iy, rev(iy)), icol = NA, ibg = ibg)\n }\n lin(ix = ix, iy = iy, icol = icol, ipch = ipch, ibg = ibg, ilty = ilty, ilwd = ilwd, type = \"l\")\n }\n return(fun)\n}\n\n\ndata_ribbon = function(ribbon.alpha = NULL) {\n ribbon.alpha = sanitize_ribbon.alpha(ribbon.alpha)\n fun = function(datapoints, xlabs, null_by, null_facet, ...) {\n # Convert x to factor if it's not already\n if (is.character(datapoints$x)) {\n datapoints$x = as.factor(datapoints$x)\n }\n\n if (is.factor(datapoints$x)) {\n xlvls = levels(datapoints$x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n datapoints$x = as.integer(datapoints$x)\n } else {\n xlabs = NULL\n }\n\n if (null_by && null_facet) {\n xord = order(datapoints$x)\n } else if (null_facet) {\n xord = order(datapoints$by, datapoints$x)\n } else if (null_by) {\n xord = order(datapoints$facet, datapoints$x)\n } else {\n xord = order(datapoints$by, datapoints$facet, datapoints$x)\n }\n\n # Reorder x, y, ymin, and ymax based on the order determined\n datapoints = datapoints[xord,]\n\n # Catch for missing ymin and ymax \n if (is.null(datapoints$ymin)) datapoints$ymin = datapoints$y \n if (is.null(datapoints$ymax)) datapoints$ymax = datapoints$y\n\n out = list(\n x = datapoints$x,\n y = datapoints$y,\n ymin = datapoints$ymin,\n ymax = datapoints$ymax,\n xlabs = xlabs,\n datapoints = datapoints,\n ribbon.alpha = ribbon.alpha)\n\n if (length(unique(datapoints$by)) > 1) out[[\"by\"]] = datapoints$by\n if (length(unique(datapoints$facet)) > 1) out[[\"facet\"]] = datapoints$facet\n\n return(out)\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_jitter.R", "#' Jittered points plot type\n#'\n#' @description Type function for plotting jittered points.\n#' Arguments are passed to \\code{\\link[base]{jitter}}.\n#'\n#' @inheritParams base::jitter\n#' @inherit base::jitter details\n#' @examples\n#' # \"jitter\" type convenience string\n#' tinyplot(Sepal.Length ~ Species, data = iris, type = \"jitter\")\n#' \n#' # Use `type_jitter()` to pass extra arguments for customization\n#' tinyplot(Sepal.Length ~ Species, data = iris, type = type_jitter(factor = 0.5))\n#' @export\ntype_jitter = function(factor = 1, amount = NULL) {\n out = list(\n draw = draw_points(),\n data = data_jitter(factor = factor, amount = amount),\n name = \"p\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_jitter = function(factor, amount) {\n fun = function(datapoints, ...) {\n x = datapoints$x\n y = datapoints$y\n if (is.factor(x)) {\n xlvls = levels(x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n x = as.integer(x)\n } else {\n xlabs = NULL\n }\n if (is.factor(y)) {\n ylvls = levels(y)\n ylabs = seq_along(ylvls)\n names(ylabs) = ylvls\n y = as.integer(y)\n } else {\n ylabs = NULL\n }\n x = jitter(x, factor = factor, amount = amount)\n y = jitter(y, factor = factor, amount = amount)\n\n datapoints$x = x\n datapoints$y = y\n\n out = list(\n datapoints = datapoints,\n x = x,\n y = y,\n xlabs = xlabs,\n ylabs = ylabs\n )\n return(out)\n }\n}\n\n"], ["/tinyplot/R/tpar.R", "#' @title Set or query graphical parameters\n#'\n#' @description Extends \\code{\\link[graphics]{par}}, serving as a (near) drop-in\n#' replacement for setting or querying graphical parameters. The key\n#' differences is that, beyond supporting the standard group of R graphical\n#' parameters in \\code{\\link[graphics]{par}}, `tpar` also supports additional\n#' graphical parameters that are provided by `tinyplot`. Similar to\n#' \\code{\\link[graphics]{par}}, parameters are set by passing appropriate\n#' `key = value` argument pairs, and multiple parameters can be set or queried\n#' at the same time.\n#'\n#' @param ... arguments of the form `key = value`. This includes all of the\n#' parameters typically supported by \\code{\\link[graphics]{par}}, as well as\n#' the `tinyplot`-specific ones described in the 'Graphical Parameters'\n#' section below.\n#' @param hook Logical. If `TRUE`, base graphical parameters persist across \n#' plots via a hook applied before each new plot (see `?setHook`).\n#'\n#' @md\n#' @details The `tinyplot`-specific parameters are saved in an internal\n#' environment called `.tpar` for performance and safety reasons. However,\n#' they can also be set at package load time via \\code{\\link[base]{options}},\n#' which may prove convenient for users that want to enable different default\n#' behaviour at startup (e.g., through an `.Rprofile` file). These options all\n#' take a `tinyplot_*` prefix, e.g.\n#' `options(tinyplot_grid = TRUE, tinyplot_facet.bg = \"grey90\")`.\n#'\n#' For their part, any \"base\" graphical parameters are caught dynamically and\n#' passed on to \\code{\\link[graphics]{par}} as appropriate. Technically, only\n#' parameters that satisfy `par(..., no.readonly = TRUE)` are evaluated.\n#'\n#' However, note the important distinction: `tpar` only evaluates parameters\n#' from \\code{\\link[graphics]{par}} if they are passed _explicitly_ by the\n#' user. This means that `tpar` should not be used to capture the (invisible)\n#' state of a user's entire set of graphics parameters, i.e. `tpar()` !=\n#' `par()`. If you want to capture the _all_ existing graphics settings, then\n#' you should rather use `par()` instead.\n#'\n#' @returns When parameters are set, their previous values are returned in an\n#' invisible named list. Such a list can be passed as an argument to `tpar` to\n#' restore the parameter values.\n#'\n#' When just one parameter is queried, the value of that parameter is returned\n#' as (atomic) vector. When two or more parameters are queried, their values\n#' are returned in a list, with the list names giving the parameters.\n#'\n#' Note the inconsistency: setting one parameter returns a list, but querying\n#' one parameter returns a vector.\n#'\n#' @section Additional Graphical Parameters:\n#'\n#' * `adj.xlab`: Numeric value between 0 and 1 controlling the alignment of the x-axis label.\n#' * `adj.ylab`: Numeric value between 0 and 1 controlling the alignment of the y-axis label.\n#' * `cairo`: Logical indicating whether \\code{\\link[grDevices]{cairo_pdf}} should be used when writing plots to PDF. If `FALSE`, then \\code{\\link[grDevices]{pdf}} will be used instead, with implications for embedding (non-standard) fonts. Only used if `tinyplot(..., file = \".pdf\")` is called. Defaults to the value of `capabilities(\"cairo\")`.\n#' * `dynmar`: Logical indicating whether `tinyplot` should attempt dynamic adjustment of margins to reduce whitespace and/or account for spacing of text elements (e.g., long horizontal y-axis labels). Note that this parameter is tightly coupled to internal `tinythemes()` logic and should _not_ be adjusted manually unless you really know what you are doing or don't mind risking unintended consequences to your plot.\n#' * `facet.bg`: Character or integer specifying the facet background colour. If an integer, will correspond to the user's default colour palette (see `palette`). Passed to `rect`. Defaults to `NULL` (none).\n#' * `facet.border`: Character or integer specifying the facet border colour. If an integer, will correspond to the user's default colour palette (see `palette`). Passed to `rect`. Defaults to `NA` (none).\n#' * `facet.cex`: Expansion factor for facet titles. Defaults to `1`.\n#' * `facet.col`: Character or integer specifying the facet text colour. If an integer, will correspond to the user's default global colour palette (see `palette`). Defaults to `NULL`, which is equivalent to \"black\".\n#' * `facet.font`: An integer corresponding to the desired font face for facet titles. For most font families and graphics devices, one of four possible values: `1` (regular), `2` (bold), `3` (italic), or `4` (bold italic). Defaults to `NULL`, which is equivalent to `1` (i.e., regular).\n#' * `file.height`: Numeric specifying the height (in inches) of any plot that is written to disk using the `tinyplot(..., file = X)` argument. Defaults to `7`.\n#' * `file.res`: Numeric specifying the resolution (in dots per square inch) of any plot that is written to disk in bitmap format (i.e., PNG or JPEG) using the `tinyplot(..., file = X)` argument. Defaults to `300`.\n#' * `file.width`: Numeric specifying the width (in inches) of any plot that is written to disk using the `tinyplot(..., file = X)` argument. Defaults to `7`.\n#' * `fmar`: A numeric vector of form `c(b,l,t,r)` for controlling the (base) margin padding, in terms of lines, between the individual facets in a faceted plot. Defaults to `c(1,1,1,1)`. If more than three facets are detected, the `fmar` parameter is scaled by 0.75 to reduce excess whitespace. For 2x2 plots, the padding better matches the `cex` expansion logic of base graphics.\n#' * `grid.col`: Character or (integer) numeric that specifies the color of the panel grid lines. Defaults to `\"lightgray\"`.\n#' * `grid.lty`: Character or (integer) numeric that specifies the line type of the panel grid lines. Defaults to `\"dotted\"`.\n#' * `grid.lwd`: Non-negative numeric giving the line width of the panel grid lines. Defaults to `1`.\n#' * `grid`: Logical indicating whether a background panel grid should be added to plots automatically. Defaults to `NULL`, which is equivalent to `FALSE`.\n#' * `lmar`: A numeric vector of form `c(inner, outer)` that gives the margin padding, in terms of lines, around the automatic `tinyplot` legend. Defaults to `c(1.0, 0.1)`. The inner margin is the gap between the legend and the plot region, and the outer margin is the gap between the legend and the edge of the graphics device.\n#' * `palette.qualitative`: Palette for qualitative colors. See the `palette` argument in `?tinyplot`.\n#' * `palette.sequential`: Palette for sequential colors. See the `palette` argument in `?tinyplot`.\n#' * `ribbon.alpha`: Numeric factor in the range `[0,1]` for modifying the opacity alpha of \"ribbon\" and \"area\" type plots. Default value is `0.2`.\n#'\n#' @importFrom graphics par\n#' @importFrom utils modifyList\n#' \n#' @seealso [`graphics::par`] which `tpar` builds on top of. [`get_saved_par`]\n#' is a convenience function for retrieving graphical parameters at different\n#' stages of a `tinyplot` call (and used for internal accounting purposes).\n#' [`tinytheme`] allows users to easily set a group of graphics parameters\n#' in a single function call, according to a variety of predefined themes.\n#' \n#' @examples\n#' # Return a list of existing base and tinyplot graphic params\n#' tpar(\"las\", \"pch\", \"facet.bg\", \"facet.cex\", \"grid\")\n#'\n#' # Simple facet plot with these default values\n#' tinyplot(mpg ~ wt, data = mtcars, facet = ~am)\n#'\n#' # Set params to something new. Similar to graphics::par(), note that we save\n#' # the existing values at the same time by assigning to an object.\n#' op = tpar(\n#' las = 1,\n#' pch = 2,\n#' facet.bg = \"grey90\",\n#' facet.cex = 2,\n#' grid = TRUE\n#' )\n#'\n#' # Re-plot with these new params\n#' tinyplot(mpg ~ wt, data = mtcars, facet = ~am)\n#'\n#' # Reset back to original values\n#' tpar(op)\n#'\n#' # Important: tpar() only evalutes parameters that have been passed explicitly\n#' # by the user. So it it should not be used to query and set (restore)\n#' # parameters that weren't explicitly requested, i.e. tpar() != par().\n#'\n#' # Note: The tinyplot-specific parameters can also be be set via `options`\n#' # with a `tinyplot_*` prefix, which can be convenient for enabling\n#' # different default behaviour at startup time (e.g., via an .Rprofile\n#' # file). Example:\n#' # options(tinyplot_grid = TRUE, tinyplot_facet.bg = \"grey90\")\n#'\n#' @export\ntpar = function(..., hook = FALSE) {\n\n opts = list(...)\n if (length(opts) == 1 && is.null(names(opts))) {\n if (inherits(opts[[1]], \"list\") && !is.null(names(opts[[1]]))) {\n opts = opts[[1]]\n }\n }\n\n ###### Assign parameters\n\n # assign tinyplot-specific arguments with known names to .tpar\n assign_tpar(opts)\n\n # return informative error messages if the input is invalid\n assert_tpar(.tpar)\n\n # if tpar(...) includes arguments that are not known to be tinyplot-specific,\n # we set a hook to set them using par() when the graphic device is started\n nam = names(opts)\n if (!is.null(nam)) {\n base_par = setdiff(nam, known_tpar)\n base_par = opts[base_par]\n if (length(base_par) > 0) {\n if (isTRUE(hook)) {\n # append new hook to existing ones\n new_hooks = list(\"before.plot.new\" = function() par(base_par))\n set_hooks(new_hooks, action = \"append\")\n # save new hook to tinyplot environment for later removal\n old_hooks = get_environment_variable(\".tpar_hooks\")\n set_environment_variable(\".tpar_hooks\", c(old_hooks, new_hooks))\n } else {\n par_names = names(par(no.readonly = TRUE))\n base_par = base_par[names(base_par) %in% par_names]\n base_par_old = par(base_par)\n par(base_par)\n }\n }\n }\n\n\n ###### Retrieve parameters\n\n # User didn't assign any new values, but may have requested explicit (print\n # of) some existing value(s)\n tpar_old = as.list(.tpar)\n if (is.null(nam)) {\n known_par = names(par(no.readonly = TRUE))\n if (!is.null(nam)) {\n used_par = intersect(nam, known_par)\n } else {\n used_par = intersect(opts, known_par)\n }\n if (length(used_par)) {\n if (!is.null(nam)) used_par = opts[used_par]\n used_par_old = par(used_par)\n tpar_old = modifyList(as.list(.tpar), used_par_old, keep.null = TRUE)\n }\n if (!is.null(opts) && length(opts) != 0) {\n # specific values requested\n opts = Filter(is.character, opts)\n ret = (`names<-`(lapply(opts, function(x) .tpar[[x]]), opts))\n if (length(used_par)) {\n ret_par = par(used_par)\n ret = modifyList(ret, ret_par, keep.null = TRUE)\n }\n if (length(ret) == 1) ret = ret[[1]]\n return(ret)\n } else {\n # no specific request; return all existing values invisibly\n return(invisible(tpar_old))\n }\n # assign new values, but still return old values for saving existing settings\n # a la `oldpar = par(param = new_value)`\n } else {\n `names<-`(lapply(nam, function(x) .tpar[[x]]), nam)\n if (length(base_par) > 0 && isFALSE(hook)) tpar_old = modifyList(tpar_old, base_par_old, keep.null = TRUE)\n return(invisible(tpar_old))\n }\n}\n\n\n# Two levels of priority: .tpar[[\"name\"]] -> par(\"name\")\nget_tpar = function(opts, default = NULL) {\n # parameter priority\n # .tpar[[\"name\"]] -> par(\"name\")\n for (o in opts) {\n tp = .tpar[[o]]\n if (!is.null(tp)) {\n return(tp)\n } else {\n p = suppressWarnings(par(o))\n if (!is.null(p)) {\n return(p)\n }\n }\n\n }\n return(default)\n}\n\n\nknown_tpar = c(\n \"adj.main\",\n \"adj.sub\",\n \"adj.xlab\",\n \"adj.ylab\",\n \"cex.xlab\",\n \"cex.ylab\",\n \"col.xaxs\",\n \"col.yaxs\",\n \"cairo\",\n \"dynmar\",\n \"facet.bg\",\n \"facet.border\",\n \"facet.cex\",\n \"facet.col\",\n \"facet.font\",\n \"file.height\",\n \"file.res\",\n \"file.width\",\n \"fmar\",\n \"grid\",\n \"grid.bg\",\n \"grid.col\",\n \"grid.lty\",\n \"grid.lwd\",\n \"lmar\",\n \"lty.xaxs\",\n \"lty.yaxs\",\n \"lwd.xaxs\",\n \"lwd.yaxs\",\n \"lwd.axis\",\n \"pch\",\n \"palette.qualitative\",\n \"palette.sequential\",\n \"ribbon.alpha\",\n \"side.sub\",\n \"tinytheme\",\n \"xaxt\",\n \"yaxt\"\n)\n\n\nassign_tpar = function(opts) {\n for (n in intersect(names(opts), known_tpar)) {\n .tpar[[n]] = opts[[n]]\n }\n}\n\n\nassert_tpar = function(.tpar) {\n assert_numeric(.tpar[[\"adj.main\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"adj.main\")\n assert_numeric(.tpar[[\"adj.sub\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"adj.sub\")\n assert_numeric(.tpar[[\"adj.xlab\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"adj.xlab\")\n assert_numeric(.tpar[[\"adj.ylab\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"adj.ylab\")\n assert_flag(.tpar[[\"cairo\"]], name = \"cairo\")\n assert_flag(.tpar[[\"dynmar\"]], null.ok = FALSE, name = \"dynmar\")\n assert_numeric(.tpar[[\"lmar\"]], len = 2, null.ok = TRUE, name = \"lmar\")\n assert_numeric(.tpar[[\"ribbon.alpha\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"ribbon.alpha\")\n assert_numeric(.tpar[[\"grid.lwd\"]], len = 1, lower = 0, null.ok = TRUE, name = \"grid.lwd\")\n assert_flag(.tpar[[\"grid\"]], null.ok = TRUE, name = \"grid\")\n assert_numeric(.tpar[[\"file.res\"]], len = 1, lower = 0, null.ok = TRUE, name = \"file.res\")\n assert_numeric(.tpar[[\"file.height\"]], len = 1, lower = 0, null.ok = TRUE, name = \"file.height\")\n assert_numeric(.tpar[[\"file.width\"]], len = 1, lower = 0, null.ok = TRUE, name = \"file.width\")\n assert_numeric(.tpar[[\"facet.font\"]], len = 1, null.ok = TRUE, name = \"facet.font\")\n assert_numeric(.tpar[[\"facet.cex\"]], len = 1, null.ok = TRUE, name = \"facet.cex\")\n assert_numeric(.tpar[[\"side.sub\"]], len = 1, null.ok = TRUE, name = \"side.sub\")\n assert_string(.tpar[[\"grid.bg\"]], null.ok = TRUE, name = \"grid.bg\")\n assert_numeric(.tpar[[\"fmar\"]], len = 4, null.ok = TRUE, name = \"fmar\")\n\n facet.col = .tpar[[\"facet.col\"]]\n if (!is.null(facet.col)) {\n if (!is.null(facet.col) && !is.numeric(facet.col) && !is.character(facet.col)) {\n stop(\"facet.col needs to be NULL, or a numeric or character\", call. = FALSE)\n }\n assert_true(length(facet.col) == 1, name = \"length(facet.col)==1\")\n }\n\n facet.bg = .tpar$facet.bg\n if (!is.null(facet.bg)) {\n if (!is.numeric(facet.bg) && !is.character(facet.bg)) {\n stop(\"facet.bg needs to be NULL, or a numeric or character\", call. = FALSE)\n }\n assert_true(length(facet.bg) == 1, name = \"length(facet.bg)==1\")\n }\n\n facet.border = .tpar$facet.border\n if (!is.null(facet.border)) {\n if (!is.numeric(facet.border) && !is.character(facet.border) && !is.na(facet.border)) {\n stop(\"facet.border needs to be NULL, or a numeric, character, or NA\", call. = FALSE)\n }\n assert_true(length(facet.border) == 1, name = \"length(facet.border)==1\")\n }\n}\n\n\ninit_tpar = function(rm_hook = FALSE) {\n rm(list = names(.tpar), envir = .tpar)\n\n if (isTRUE(rm_hook)) {\n old_hooks = get_environment_variable(\".tpar_hooks\")\n if (length(old_hooks) > 0) {\n remove_hooks(old_hooks)\n set_environment_variable(\".tpar_hooks\", NULL)\n }\n }\n\n .tpar$cairo = if (is.null(getOption(\"tinyplot_cairo\"))) capabilities(\"cairo\") else as.logical(getOption(\"tinyplot_cairo\"))\n \n \n .tpar$dynmar = if (is.null(getOption(\"tinyplot_dynmar\"))) FALSE else as.logical(getOption(\"tinyplot_dynmar\"))\n \n # Figure output options if written to file\n .tpar$file.width = if (is.null(getOption(\"tinyplot_file.width\"))) 7 else as.numeric(getOption(\"tinyplot_file.width\"))\n .tpar$file.height = if (is.null(getOption(\"tinyplot_file.height\"))) 7 else as.numeric(getOption(\"tinyplot_file.height\"))\n .tpar$file.res = if (is.null(getOption(\"tinyplot_file.res\"))) 300 else as.numeric(getOption(\"tinyplot_file.res\"))\n\n # Facet margin, i.e. gap between the individual facet windows\n .tpar$fmar = if (is.null(getOption(\"tinyplot_fmar\"))) c(1, 1, 1, 1) else as.numeric(getOption(\"tinyplot_fmar\"))\n\n # Other facet options\n .tpar$facet.cex = if (is.null(getOption(\"tinyplot_facet.cex\"))) 1 else as.numeric(getOption(\"tinyplot_facet.cex\"))\n .tpar$facet.font = if (is.null(getOption(\"tinyplot_facet.font\"))) NULL else as.numeric(getOption(\"tinyplot_facet.font\"))\n .tpar$facet.col = if (is.null(getOption(\"tinyplot_facet.col\"))) NULL else getOption(\"tinyplot_facet.col\")\n .tpar$facet.bg = if (is.null(getOption(\"tinyplot_facet.bg\"))) NULL else getOption(\"tinyplot_facet.bg\")\n .tpar$facet.border = if (is.null(getOption(\"tinyplot_facet.border\"))) NA else getOption(\"tinyplot_facet.border\")\n\n # Plot grid\n .tpar$grid = if (is.null(getOption(\"tinyplot_grid\"))) FALSE else as.logical(getOption(\"tinyplot_grid\"))\n .tpar$grid.col = if (is.null(getOption(\"tinyplot_grid.col\"))) \"lightgray\" else getOption(\"tinyplot_grid.col\")\n .tpar$grid.lty = if (is.null(getOption(\"tinyplot_grid.lty\"))) \"dotted\" else getOption(\"tinyplot_grid.lty\")\n .tpar$grid.lwd = if (is.null(getOption(\"tinyplot_grid.lwd\"))) 1 else as.numeric(getOption(\"tinyplot_grid.lwd\"))\n\n # Legend margin, i.e. gap between the legend and the plot elements\n .tpar$lmar = if (is.null(getOption(\"tinyplot_lmar\"))) c(1.0, 0.1) else as.numeric(getOption(\"tinyplot_lmar\"))\n\n # Alpha fill (transparency) default for ribbon and area plots\n .tpar$ribbon.alpha = if (is.null(getOption(\"tinyplot_ribbon.alpha\"))) 0.2 else as.numeric(getOption(\"tinyplot_ribbon.alpha\"))\n}\n"], ["/tinyplot/R/draw_legend.R", "#' @title Calculate placement of legend and draw it\n#' \n#' @description Function used to calculate the placement of (including\n#' outside the plotting area) and drawing of legend.\n#' \n#' @md\n#' @param legend Legend placement keyword or list, passed down from [tinyplot].\n#' @param legend_args Additional legend arguments to be passed to\n#' \\code{\\link[graphics]{legend}}.\n#' @param by_dep The (deparsed) \"by\" grouping variable name.\n#' @param lgnd_labs The labels passed to `legend(legend = ...)`.\n#' @param type Plotting type(s), passed down from [tinyplot].\n#' @param pch Plotting character(s), passed down from [tinyplot].\n#' @param lty Plotting linetype(s), passed down from [tinyplot].\n#' @param lwd Plotting line width(s), passed down from [tinyplot].\n#' @param col Plotting colour(s), passed down from [tinyplot].\n#' @param bg Plotting character background fill colour(s), passed down from [tinyplot].\n#' @param cex Plotting character expansion(s), passed down from [tinyplot].\n#' @param gradient Logical indicating whether a continuous gradient swatch\n#' should be used to represent the colors.\n#' @param lmar Legend margins (in lines). Should be a numeric vector of the form\n#' `c(inner, outer)`, where the first number represents the \"inner\" margin\n#' between the legend and the plot, and the second number represents the\n#' \"outer\" margin between the legend and edge of the graphics device. If no\n#' explicit value is provided by the user, then reverts back to `tpar(\"lmar\")`\n#' for which the default values are `c(1.0, 0.1)`.\n#' @param has_sub Logical. Does the plot have a sub-caption. Only used if\n#' keyword position is \"bottom!\", in which case we need to bump the legend\n#' margin a bit further.\n#' @param new_plot Logical. Should we be calling plot.new internally?\n#' @param draw Logical. If `FALSE`, no legend is drawn but the sizes are\n#' returned. Note that a new (blank) plot frame will still need to be started\n#' in order to perform the calculations. \n#' \n#' @returns No return value, called for side effect of producing a(n empty) plot\n#' with a legend in the margin.\n#' \n#' @importFrom graphics grconvertX grconvertY rasterImage strwidth\n#' @importFrom grDevices as.raster recordGraphics\n#' @importFrom utils modifyList\n#' \n#' @examples\n#' oldmar = par(\"mar\")\n#' \n#' draw_legend(\n#' legend = \"right!\", ## default (other options incl, \"left(!)\", \"\"bottom(!)\", etc.)\n#' legend_args = list(title = \"Key\", bty = \"o\"),\n#' lgnd_labs = c(\"foo\", \"bar\"),\n#' type = \"p\",\n#' pch = 21:22,\n#' col = 1:2\n#' )\n#' \n#' # The legend is placed in the outer margin...\n#' box(\"figure\", col = \"cyan\", lty = 4)\n#' # ... and the plot is proportionally adjusted against the edge of this\n#' # margin.\n#' box(\"plot\")\n#' # You can add regular plot objects per normal now\n#' plot.window(xlim = c(1,10), ylim = c(1,10))\n#' points(1:10)\n#' points(10:1, pch = 22, col = \"red\")\n#' axis(1); axis(2)\n#' # etc.\n#' \n#' # Important: A side effect of draw_legend is that the inner margins have been\n#' # adjusted. (Here: The right margin, since we called \"right!\" above.)\n#' par(\"mar\")\n#' \n#' # To reset you should call `dev.off()` or just reset manually.\n#' par(mar = oldmar)\n#' \n#' # Note that the inner and outer margin of the legend itself can be set via\n#' # the `lmar` argument. (This can also be set globally via\n#' # `tpar(lmar = c(inner, outer))`.)\n#' draw_legend(\n#' legend_args = list(title = \"Key\", bty = \"o\"),\n#' lgnd_labs = c(\"foo\", \"bar\"),\n#' type = \"p\",\n#' pch = 21:22,\n#' col = 1:2,\n#' lmar = c(0, 0.1) ## set inner margin to zero\n#' )\n#' box(\"figure\", col = \"cyan\", lty = 4)\n#' \n#' par(mar = oldmar)\n#' \n#' # Continuous (gradient) legends are also supported\n#' draw_legend(\n#' legend = \"right!\",\n#' legend_args = list(title = \"Key\"),\n#' lgnd_labs = LETTERS[1:5],\n#' col = hcl.colors(5),\n#' gradient = TRUE ## enable gradient legend\n#' )\n#' \n#' par(mar = oldmar)\n#' \n#' @export\ndraw_legend = function(\n legend = NULL,\n legend_args = NULL,\n by_dep = NULL,\n lgnd_labs = NULL,\n type = NULL,\n pch = NULL,\n lty = NULL,\n lwd = NULL,\n col = NULL,\n bg = NULL,\n cex = NULL,\n gradient = FALSE,\n lmar = NULL,\n has_sub = FALSE,\n new_plot = TRUE,\n draw = TRUE\n) {\n \n if (is.null(lmar)) {\n lmar = tpar(\"lmar\")\n } else {\n if (!is.numeric(lmar) || length(lmar)!=2) stop (\"lmar must be a numeric of length 2.\")\n }\n \n assert_logical(gradient)\n assert_logical(has_sub)\n assert_logical(new_plot)\n assert_logical(draw)\n \n #\n ## legend args ----\n \n if (is.null(legend_args[[\"x\"]])) {\n if (is.null(legend)) {\n legend_args[[\"x\"]] = \"right!\"\n } else if (is.character(legend)) {\n legend_args = utils::modifyList(legend_args, list(x = legend))\n } else if (class(legend) %in% c(\"call\", \"name\")) {\n largs = as.list(legend)\n if (is.null(largs[[\"x\"]])) {\n lnms = names(largs)\n # check second position b/c first will be a symbol \n if (is.null(lnms)) {\n largs = stats::setNames(largs, c(\"\", \"x\"))\n } else if (length(largs)>=2 && lnms[2] == \"\") {\n lnms[2] = \"x\"\n largs = stats::setNames(largs, lnms)\n } else {\n largs[[\"x\"]] = \"right!\"\n }\n }\n # Finally, combine with any pre-existing legend args (e.g., title from the by label)\n legend_args = utils::modifyList(legend_args, largs, keep.null = TRUE)\n }\n }\n \n ## Use `!exists` rather than `is.null` for title in case user specified no title\n if (!exists(\"title\", where = legend_args)) legend_args[[\"title\"]] = by_dep\n \n legend_args[[\"pch\"]] = legend_args[[\"pch\"]] %||% pch\n legend_args[[\"lty\"]] = legend_args[[\"lty\"]] %||% lty\n legend_args[[\"col\"]] = legend_args[[\"col\"]] %||% col\n legend_args[[\"bty\"]] = legend_args[[\"bty\"]] %||% \"n\"\n legend_args[[\"horiz\"]] = legend_args[[\"horiz\"]] %||% FALSE\n legend_args[[\"xpd\"]] = legend_args[[\"xpd\"]] %||% NA\n \n if (!isTRUE(type %in% c(\"p\", \"ribbon\", \"polygon\", \"polypath\"))) {\n legend_args[[\"lwd\"]] = legend_args[[\"lwd\"]] %||% lwd\n }\n \n if (isTRUE(type %in% c(\"p\", \"pointrange\", \"errorbar\")) && (length(col) == 1 || length(cex) == 1)) {\n legend_args[[\"pt.cex\"]] = legend_args[[\"pt.cex\"]] %||% cex\n }\n \n # turn off inner line for \"barplot\" type\n if (identical(type, \"barplot\")) {\n legend_args[[\"lty\"]] = 0\n }\n \n if (isTRUE(type %in% c(\"rect\", \"ribbon\", \"polygon\", \"polypath\", \"boxplot\", \"hist\", \"histogram\", \"spineplot\", \"ridge\", \"barplot\", \"violin\")) || gradient) {\n legend_args[[\"pch\"]] = 22\n legend_args[[\"pt.cex\"]] = legend_args[[\"pt.cex\"]] %||% 3.5\n legend_args[[\"y.intersp\"]] = legend_args[[\"y.intersp\"]] %||% 1.25\n legend_args[[\"seg.len\"]] = legend_args[[\"seg.len\"]] %||% 1.25\n }\n \n if (isTRUE(type %in% c(\"ribbon\", \"hist\", \"histogram\", \"spineplot\"))) {\n legend_args[[\"pt.lwd\"]] = legend_args[[\"pt.lwd\"]] %||% 0\n }\n \n if (identical(type, \"p\")) {\n legend_args[[\"pt.lwd\"]] = legend_args[[\"pt.lwd\"]] %||% lwd\n }\n \n if (identical(type, \"n\") && isFALSE(gradient)) {\n legend_args[[\"pch\"]] = legend_args[[\"pch\"]] %||% par(\"pch\")\n }\n \n if (identical(type, \"spineplot\")) {\n legend_args[[\"pt.bg\"]] = legend_args[[\"pt.bg\"]] %||% legend_args[[\"col\"]]\n }\n \n if (identical(type, \"ridge\") && isFALSE(gradient)) {\n legend_args[[\"pt.bg\"]] = legend_args[[\"pt.bg\"]] %||% sapply(legend_args[[\"col\"]], function(ccol) seq_palette(ccol, n = 2)[2])\n }\n \n legend_args[[\"pt.bg\"]] = legend_args[[\"pt.bg\"]] %||% bg\n \n legend_args[[\"legend\"]] = legend_args[[\"legend\"]] %||% lgnd_labs\n if (length(lgnd_labs) != length(eval(legend_args[[\"legend\"]]))) {\n warning(\n \"\\nUser-supplied legend labels do not match the number of groups.\\n\",\n \"Defaulting to automatic labels determined by the group splits in `by`,\\n\"\n )\n legend_args[[\"legend\"]] = lgnd_labs\n }\n \n if (isTRUE(gradient)) {\n legend_args[[\"ncol\"]] = NULL\n }\n \n #\n ## legend placement ----\n \n # Note: \"side\" = left/right ; \"end\" = top/bottom\n outer_side = outer_end = outer_right = outer_bottom = FALSE ## placeholders\n \n ooma = par(\"oma\")\n omar = par(\"mar\")\n topmar_epsilon = 0.1\n \n # Catch to avoid recursive offsets, e.g. repeated tinyplot calls with\n # \"bottom!\" legend position.\n \n ## restore inner margin defaults\n ## (in case the plot region/margins were affected by the preceding tinyplot call)\n dynmar = isTRUE(.tpar[[\"dynmar\"]])\n if (any(ooma != 0) && !dynmar) {\n if ( ooma[1] != 0 & omar[1] == par(\"mgp\")[1] + 1*par(\"cex.lab\") ) omar[1] = 5.1\n if ( ooma[2] != 0 & omar[2] == par(\"mgp\")[1] + 1*par(\"cex.lab\") ) omar[2] = 4.1\n if ( ooma[3] == topmar_epsilon & omar[3] != 4.1 ) omar[3] = 4.1\n if ( ooma[4] != 0 & omar[4] == 0 ) omar[4] = 2.1\n par(mar = omar)\n }\n ## restore outer margin defaults\n par(omd = c(0,1,0,1))\n ooma = par(\"oma\")\n \n ## Legend to outer side (either right or left) of plot\n if (grepl(\"right!$|left!$\", legend_args[[\"x\"]])) {\n \n outer_side = TRUE\n outer_right = grepl(\"right!$\", legend_args[[\"x\"]])\n \n # extra bump for spineplot if outer_right legend (to accommodate secondary y-axis)\n if (identical(type, \"spineplot\")) lmar[1] = lmar[1] + 1.1\n \n ## Switch position anchor (we'll adjust relative to the _opposite_ side below)\n if (outer_right) legend_args[[\"x\"]] = gsub(\"right!$\", \"left\", legend_args[[\"x\"]])\n if (!outer_right) legend_args[[\"x\"]] = gsub(\"left!$\", \"right\", legend_args[[\"x\"]])\n \n ## We have to set the inner margins of the plot before the (fake) legend is\n ## drawn, otherwise the inset calculation---which is based in the legend\n ## width---will be off the first time.\n if (outer_right) {\n omar[4] = 0\n } else {\n # For outer left we have to account for the y-axis label too, which\n # requires additional space\n omar[2] = par(\"mgp\")[1] + 1*par(\"cex.lab\")\n }\n par(mar = omar)\n \n if (new_plot && draw) {\n plot.new()\n # For themed + dynamic plots, we need to make sure the adjusted plot\n # margins for the legend are reinstated (after being overwritten by\n # the before.plot.new hook.\n if (dynmar) {\n omar = par(\"mar\")\n if (outer_right) {\n omar[4] = 0\n } else {\n omar[2] = par(\"mgp\")[1] + 1*par(\"cex.lab\")\n }\n par(mar = omar)\n }\n }\n \n legend_args[[\"horiz\"]] = FALSE\n \n ## Legend at the outer top or bottom of plot\n } else if (grepl(\"bottom!$|top!$\", legend_args[[\"x\"]])) {\n\n outer_end = TRUE\n outer_bottom = grepl(\"bottom!$\", legend_args[[\"x\"]])\n\n ## Switch position anchor (we'll adjust relative to the _opposite_ side below)\n if (outer_bottom) legend_args[[\"x\"]] = gsub(\"bottom!$\", \"top\", legend_args[[\"x\"]])\n if (!outer_bottom) legend_args[[\"x\"]] = gsub(\"top!$\", \"bottom\", legend_args[[\"x\"]])\n\n ## We have to set the inner margins of the plot before the (fake) legend is\n ## drawn, otherwise the inset calculation---which is based in the legend\n ## width---will be off the first time.\n if (outer_bottom) {\n omar[1] = par(\"mgp\")[1] + 1*par(\"cex.lab\")\n if (has_sub && (is.null(.tpar[[\"side.sub\"]]) || .tpar[[\"side.sub\"]]==1)) omar[1] = omar[1] + 1*par(\"cex.sub\")\n } else {\n ## For \"top!\", the logic is slightly different: We don't expand the outer\n ## margin b/c we need the legend to come underneath the main title. So\n ## we rather expand the existing inner margin.\n ooma[3] = ooma[3] + topmar_epsilon\n par(oma = ooma)\n }\n par(mar = omar)\n\n if (new_plot && draw) {\n plot.new()\n # For themed + dynamic plots, we need to make sure the adjusted plot\n # margins for the legend are reinstated (after being overwritten by\n # the before.plot.new hook.\n if (dynmar) {\n omar = par(\"mar\")\n if (outer_bottom) {\n # omar[1] = par(\"mgp\")[1] + 1*par(\"cex.lab\")\n omar[1] = theme_clean$mgp[1] + 1*par(\"cex.lab\") ## bit of a hack\n if (has_sub && (is.null(.tpar[[\"side.sub\"]]) || .tpar[[\"side.sub\"]]==1)) omar[1] = omar[1] + 1*par(\"cex.sub\")\n } else {\n ooma[3] = ooma[3] + topmar_epsilon\n par(oma = ooma)\n }\n par(mar = omar)\n }\n }\n\n # enforce horizontal legend if user hasn't specified ncol arg\n # (exception: gradient legends at bottom/top are always horizontal)\n if (is.null(legend_args[[\"ncol\"]]) || gradient) legend_args[[\"horiz\"]] = TRUE\n\n } else {\n \n legend_args[[\"inset\"]] = 0\n if (new_plot && draw) plot.new()\n \n }\n \n # Additional tweaks for horiz and/or multi-column legends\n if (isTRUE(legend_args[[\"horiz\"]]) || !is.null(legend_args[[\"ncol\"]])) {\n # tighter horizontal labelling\n # See: https://github.com/grantmcdermott/tinyplot/issues/434\n if (!gradient) {\n legend_args[[\"text.width\"]] = NA\n # Add a space to all labs except the outer most right ones\n nlabs = length(legend_args[[\"legend\"]])\n nidx = nlabs\n if (!is.null(legend_args[[\"ncol\"]])) nidx = tail(1:nlabs, (nlabs %/% legend_args[[\"ncol\"]]))\n legend_args[[\"legend\"]][-nidx] = paste(legend_args[[\"legend\"]][-nidx], \" \")\n }\n # catch for horizontal ribbon legend spacing\n if (type==\"ribbon\") {\n if (legend_args[[\"pt.lwd\"]] == 1) {\n legend_args[[\"x.intersp\"]] = 1\n } else {\n legend_args[[\"x.intersp\"]] = 0.5\n }\n } else if (gradient) {\n legend_args[[\"x.intersp\"]] = 0.5\n }\n }\n \n #\n ## draw the legend ----\n \n # Legend drawing is handled by the internal `tinylegend()` function, which:\n # 1. calculates appropriate insets for \"outer\" legend placement\n # 2. can draw gradient legends (via `gradient_legend()` below)\n #\n # Note: We wrap everything in `recordGraphics()` to preserve legend spacing\n # if the plot is resized (also necessary for Positron graphics logic regardless)\n recordGraphics(\n tinylegend(\n legend_args = legend_args,\n ooma = ooma,\n omar = omar,\n lmar = lmar,\n topmar_epsilon = topmar_epsilon,\n outer_side = outer_side,\n outer_right = outer_right,\n outer_end = outer_end,\n outer_bottom = outer_bottom,\n gradient = gradient,\n draw = draw\n ),\n list = list(\n legend_args = legend_args,\n ooma = ooma,\n omar = omar,\n lmar = lmar,\n topmar_epsilon = topmar_epsilon,\n outer_side = outer_side,\n outer_right = outer_right,\n outer_end = outer_end,\n outer_bottom = outer_bottom,\n gradient = gradient,\n draw = draw\n ),\n env = getNamespace(\"tinyplot\")\n )\n \n}\n\n\n# tinylegend ----\n\n## Internal workhorse function that draws the legend, given a set of legend\n## arguments and other graphical parameters. It does this in three steps:\n## 1) draw a fake legend, 2) calculate the associated inset and adjust the plot\n## margins accordingly, 3) draw the real legend\n\ntinylegend = function(\n legend_args,\n ooma, omar, lmar, topmar_epsilon,\n outer_side, outer_right, outer_end, outer_bottom,\n gradient,\n draw\n) {\n \n #\n ## Step 1: \"draw\" fake legend\n \n fklgnd.args = modifyList(\n legend_args,\n list(plot = FALSE),\n keep.null = TRUE\n )\n \n if (gradient) {\n lgnd_labs_tmp = na.omit(fklgnd.args[[\"legend\"]])\n if (length(lgnd_labs_tmp) < 5L) {\n nmore = 5L - length(lgnd_labs_tmp)\n lgnd_labs_tmp = c(lgnd_labs_tmp, rep(\"\", nmore))\n }\n fklgnd.args = modifyList(\n fklgnd.args,\n list(legend = lgnd_labs_tmp),\n keep.null = TRUE\n )\n if (outer_end) fklgnd.args = modifyList(fklgnd.args, list(title = NULL), keep.null = TRUE)\n }\n \n if (draw) {\n fklgnd = do.call(\"legend\", fklgnd.args)\n } else {\n plot.new()\n fklgnd = do.call(\"legend\", fklgnd.args)\n return(fklgnd)\n }\n \n #\n ## Step 2: Calculate legend inset (for outer placement in plot region)\n \n # calculate outer margin width in lines\n soma = 0\n if (outer_side) {\n soma = grconvertX(fklgnd$rect$w, to=\"lines\") - grconvertX(0, to=\"lines\")\n } else if (outer_end) {\n soma = grconvertY(fklgnd$rect$h, to=\"lines\") - grconvertY(0, to=\"lines\")\n }\n # Add legend margins to the outer margin\n soma = soma + sum(lmar)\n \n ## differing outer margin adjustments depending on side\n if (outer_side) {\n if (outer_right) {\n ooma[4] = soma\n } else {\n ooma[2] = soma\n }\n } else if (outer_end) {\n if (outer_bottom) {\n ooma[1] = soma\n } else {\n omar[3] = omar[3] + soma - topmar_epsilon\n par(mar = omar)\n }\n }\n par(oma = ooma)\n \n # determine legend inset\n inset = 0\n if (outer_side) {\n inset = grconvertX(lmar[1], from=\"lines\", to=\"npc\") - grconvertX(0, from = \"lines\", to = \"npc\")\n # extra space needed for \"left!\" b/c of lhs inner margin\n if (!outer_right) {\n inset_bump = grconvertX(par(\"mar\")[2], from = \"lines\", to = \"npc\") - grconvertX(0, from = \"lines\", to = \"npc\")\n inset = inset + inset_bump\n }\n inset = c(1+inset, 0)\n } else if (outer_end) {\n inset = grconvertY(lmar[1], from=\"lines\", to=\"npc\") - grconvertY(0, from=\"lines\", to=\"npc\")\n if (outer_bottom) {\n # extra space needed for \"bottom!\" b/c of lhs inner margin\n inset_bump = grconvertY(par(\"mar\")[1], from=\"lines\", to=\"npc\") - grconvertY(0, from=\"lines\", to=\"npc\")\n inset = inset + inset_bump\n } else {\n epsilon_bump = grconvertY(topmar_epsilon, from=\"lines\", to=\"npc\") - grconvertY(0, from=\"lines\", to=\"npc\")\n inset = inset + epsilon_bump\n }\n inset = c(0, 1+inset)\n }\n \n # GM: The legend inset spacing only works _exactly_ if we refresh the plot\n # area. I'm not sure why (and it works properly if we use the same\n # parameters manually while debugging), but this hack seems to work.\n ## v0.3.0 update: Using (temporary) hook instead of direct par(new = TRUE)\n ## assignment to play nice with tinytheme logic.\n oldhook = getHook(\"before.plot.new\")\n setHook(\"before.plot.new\", function() par(new = TRUE), action = \"append\")\n setHook(\"before.plot.new\", function() par(mar = omar), action = \"append\")\n plot.new()\n setHook(\"before.plot.new\", oldhook, action = \"replace\")\n \n # Finally, set the inset as part of the legend args.\n legend_args[[\"inset\"]] = inset\n \n #\n ## Step 3: Draw the legend\n\n if (gradient) {\n if (!more_than_n_unique(legend_args[[\"col\"]], 1)) {\n if (!is.null(legend_args[[\"pt.bg\"]]) && length(legend_args[[\"pt.bg\"]])==100) {\n legend_args[[\"col\"]] = legend_args[[\"pt.bg\"]]\n }\n }\n gradient_legend(\n legend_args = legend_args,\n fklgnd = fklgnd,\n lmar = lmar,\n outer_side = outer_side,\n outer_end = outer_end,\n outer_right = outer_right,\n outer_bottom = outer_bottom\n )\n } else {\n do.call(\"legend\", legend_args)\n }\n \n}\n\n\n# gradient legend ----\n\n# For gradient (i.e., continuous color) legends, we'll role our own bespoke\n# legend function based on grDevices::as.raster\n\ngradient_legend = function(legend_args, fklgnd, lmar, outer_side, outer_end, outer_right, outer_bottom) {\n pal = legend_args[[\"col\"]]\n lgnd_labs = legend_args[[\"legend\"]]\n if (!is.null(legend_args[[\"horiz\"]])) horiz = legend_args[[\"horiz\"]] else horiz = FALSE\n if (isTRUE(horiz)) {\n rasterlgd = as.raster(matrix(pal, nrow = 1))\n } else {\n rasterlgd = as.raster(matrix(rev(pal), ncol = 1))\n }\n \n corners = par(\"usr\")\n rasterbox = rep(NA_real_, 4)\n \n inner = !any(c(outer_side, outer_end))\n inner_right = inner_bottom = FALSE\n if (inner) {\n if (!is.null(legend_args[[\"x\"]]) && grepl(\"left$|right$\", legend_args[[\"x\"]])) {\n inner_right = grepl(\"right$\", legend_args[[\"x\"]])\n }\n if (!is.null(legend_args[[\"x\"]]) && grepl(\"^bottoml|^top\", legend_args[[\"x\"]])) {\n inner_bottom = grepl(\"^bottom\", legend_args[[\"x\"]])\n }\n }\n \n if (inner) {\n \n fklgnd$rect$h = fklgnd$rect$h - (grconvertY(1.5 + 0.4, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\"))\n \n rasterbox[1] = fklgnd$rect$left\n if (isFALSE(inner_right)) rasterbox[1] = rasterbox[1] + (grconvertX(0.2, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\"))\n rasterbox[2] = fklgnd$rect$top - fklgnd$rect$h - (grconvertY(1.5 + 0.2, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\"))\n rasterbox[3] = rasterbox[1] + (grconvertX(1.25, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\"))\n rasterbox[4] = rasterbox[2] + fklgnd$rect$h\n \n } else if (outer_side) {\n \n rb1_adj = grconvertX(lmar[1] + 0.2, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\")\n rb3_adj = grconvertX(1.25, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\")\n rb2_adj = (corners[4] - corners[3] - (grconvertY(5+1 + 2.5, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\"))) / 2\n # override if top or bottom\n if (!is.null(legend_args[[\"x\"]])) {\n if (grepl(\"^bottom\", legend_args[[\"x\"]])) {\n rb2_adj = corners[3]\n }\n if (grepl(\"^top\", legend_args[[\"x\"]])) {\n rb2_adj = corners[4] - (grconvertY(5+1 + 2.5, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\"))\n }\n }\n rb4_adj = grconvertY(5+1, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n \n if (outer_right) {\n rasterbox[1] = corners[2] + rb1_adj\n rasterbox[2] = rb2_adj \n rasterbox[3] = rasterbox[1] + rb3_adj\n rasterbox[4] = rasterbox[2] + rb4_adj\n } else {\n rb1_adj = rb1_adj + grconvertX(par(\"mar\")[2] + 1, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\")\n rasterbox[1] = corners[1] - rb1_adj\n rasterbox[2] = rb2_adj \n rasterbox[3] = rasterbox[1] - rb3_adj\n rasterbox[4] = rasterbox[2] + rb4_adj\n }\n \n } else if (outer_end) {\n \n rb1_adj = (corners[2] - corners[1] - (grconvertX(5+1, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\"))) / 2\n rb3_adj = grconvertX(5+1, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\")\n rb2_adj = grconvertY(lmar[1], from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n rb4_adj = grconvertY(1.25, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n \n if (outer_bottom) {\n rb2_adj = rb2_adj + grconvertY(par(\"mar\")[2], from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n rasterbox[1] = rb1_adj\n rasterbox[2] = corners[3] - rb2_adj \n rasterbox[3] = rasterbox[1] + rb3_adj\n rasterbox[4] = rasterbox[2] - rb4_adj\n } else {\n rb2_adj = rb2_adj + grconvertY(1.25 + 1, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n rasterbox[1] = rb1_adj\n rasterbox[2] = corners[4] + rb2_adj \n rasterbox[3] = rasterbox[1] + rb3_adj\n rasterbox[4] = rasterbox[2] - rb4_adj\n }\n \n }\n \n #\n ## Draw the gradient swatch\n \n rasterImage(\n rasterlgd,\n rasterbox[1], #x1\n rasterbox[2], #y1\n rasterbox[3], #x2\n rasterbox[4], #y2\n xpd = NA\n ) \n \n #\n ## Add the labels, tick marks, and title \n \n if (isFALSE(horiz)) {\n labs_idx = !is.na(lgnd_labs)\n lgnd_labs[labs_idx] = paste0(\" \", format(lgnd_labs[labs_idx]))\n lbl_x_anchor = rasterbox[3]\n ttl_x_anchor = rasterbox[1]\n lbl_adj = c(0, 0.5)\n tck_adj = c(1, 0.5)\n ttl_adj = c(0, 0)\n if (!inner && !outer_right) {\n lbl_x_anchor = rasterbox[1]\n ttl_x_anchor = ttl_x_anchor + max(strwidth(lgnd_labs[labs_idx]))\n ttl_adj = c(1, 0)\n }\n text(\n x = lbl_x_anchor,\n y = seq(rasterbox[2], rasterbox[4], length.out = length(lgnd_labs)),\n labels = lgnd_labs,\n xpd = NA, \n adj = lbl_adj\n )\n # legend tick marks\n lgnd_ticks = lgnd_labs\n lgnd_ticks[labs_idx] = \"- -\"\n text(\n x = lbl_x_anchor,\n y = seq(rasterbox[2], rasterbox[4], length.out = length(lgnd_labs)),\n labels = lgnd_ticks, col = \"white\",\n xpd = NA, adj = tck_adj\n )\n # legend title\n text(\n x = ttl_x_anchor,\n y = rasterbox[4] + grconvertY(1, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\"),\n labels = legend_args[[\"title\"]],\n xpd = NA, adj = ttl_adj\n )\n } else {\n lbl_y_anchor = rasterbox[4]\n ttl_y_anchor = rasterbox[4]\n lbl_adj = c(0.5, 1.25)\n tck_adj = c(0, 0.5)\n ttl_adj = c(1, -0.5)\n # legend labs\n text(\n x = seq(rasterbox[1], rasterbox[3], length.out = length(lgnd_labs)),\n y = lbl_y_anchor,\n labels = lgnd_labs,\n xpd = NA, adj = lbl_adj\n )\n # legend tick marks\n lgnd_ticks = lgnd_labs\n lgnd_ticks[!is.na(lgnd_ticks)] = \"- -\"\n text(\n x = seq(rasterbox[1], rasterbox[3], length.out = length(lgnd_labs)),\n y = lbl_y_anchor,\n labels = lgnd_ticks, col = \"white\",\n xpd = NA, adj = tck_adj, srt = 90\n )\n # legend title\n text(\n x = rasterbox[1],\n y = ttl_y_anchor,\n labels = paste0(legend_args[[\"title\"]], \" \"),\n xpd = NA, adj = ttl_adj\n )\n }\n}\n\n\n"], ["/tinyplot/R/facet.R", "#' Draw facet windows\n#' \n#' @description Internal functions called from `tinyplot` in order to draw the\n#' plot window with different facets, grids, axes, etc. \n#' \n#' `facet_layout` determines the layout of the facets, based on a set of inputs.\n#' \n#' `draw_facet_window` is the main workhorse function for setting the exterior\n#' plot elements as part of a `tinyplot` call, including adjustment of margins\n#' for dynamic themes, etc.\n#' \n#' @keywords internal\n#' @rdname facet\ndraw_facet_window = function(\n # add arg first, since that determines what happens (if at all)\n add,\n # facet-specific args\n cex_fct_adj,\n facet.args,\n facet_newlines, facet_font, facet_rect, facet_text,\n facet_col, facet_bg, facet_border,\n facet, facets, ifacet,\n nfacets, nfacet_cols, nfacet_rows,\n # axes args\n axes, flip, frame.plot, oxaxis, oyaxis,\n xlabs, xlim, xlim_user, xaxt, xaxs, xaxb, xaxl,\n ylabs, ylim, ylim_user, yaxt, yaxs, yaxb, yaxl,\n asp, log,\n # other args (in approx. alphabetical + group ordering)\n dots,\n draw,\n grid,\n has_legend,\n type,\n x, xmax, xmin,\n y, ymax, ymin\n ) {\n \n # if add is TRUE, just return inputs without any calculations\n if (isTRUE(add)) {\n return(as.list(environment()))\n }\n \n # if breaks are provided use these (but only if x/ylabs are null)\n if (!is.null(xaxb) && !is.null(xlabs)) xlabs = xaxb\n if (!is.null(yaxb) && !is.null(ylabs)) ylabs = yaxb\n \n # draw background color only in the grid rectangle\n grid.bg = get_tpar(\"grid.bg\")\n if (!is.null(grid.bg)) {\n corners = par(\"usr\")\n rect(corners[1], corners[3], corners[2], corners[4], col = grid.bg, border = NA)\n }\n\n ## dynamic margins flag\n dynmar = isTRUE(.tpar[[\"dynmar\"]])\n \n ## optionally allow to modify the style of axis interval calculation\n if (!is.null(xaxs)) par(xaxs = xaxs)\n if (!is.null(yaxs)) par(yaxs = yaxs)\n\n if (nfacets > 1) {\n # Set facet margins (i.e., gaps between facets)\n if (is.null(facet.args[[\"fmar\"]])) {\n fmar = tpar(\"fmar\")\n } else {\n if (length(facet.args[[\"fmar\"]]) != 4) {\n warning(\n \"`fmar` has to be a vector of length four, e.g.\",\n \"`facet.args = list(fmar = c(b,l,t,r))`.\",\n \"\\n\",\n \"Resetting to fmar = c(1,1,1,1) default.\",\n \"\\n\"\n )\n fmar = tpar(\"fmar\")\n } else {\n fmar = facet.args[[\"fmar\"]]\n }\n }\n # We need to adjust for n>=3 facet cases for correct spacing...\n if (nfacets >= 3) {\n ## ... exception for 2x2 cases\n if (!(nfacet_rows == 2 && nfacet_cols == 2)) fmar = fmar * .75\n }\n # Extra reduction if no plot frame to reduce whitespace\n if (isFALSE(frame.plot) && !isTRUE(facet.args[[\"free\"]])) {\n fmar = fmar - 0.5\n }\n\n ooma = par(\"oma\")\n\n # Bump top margin down for facet titles\n fmar[3] = fmar[3] + 1\n if (isTRUE(attr(facet, \"facet_grid\"))) {\n fmar[3] = max(0, fmar[3] - 1)\n # Indent for RHS facet_grid title strip if \"right!\" legend\n if (has_legend && ooma[4] > 0) ooma[4] = ooma[4] + 1\n }\n fmar[3] = fmar[3] + facet_newlines * facet_text / cex_fct_adj\n\n omar = par(\"mar\")\n \n ## Dynamic plot margin adjustments\n if (dynmar) {\n if (par(\"las\") %in% 1:2) {\n # extra whitespace bump on the y axis\n ## overrides for ridge and some types that use integer spacing with (named) axis labels ## FXIME\n if (type == \"ridge\") {\n yaxlabs = levels(y)\n } else if (!is.null(ylabs)) {\n yaxlabs = if (!is.null(names(ylabs))) names(ylabs) else ylabs \n } else if (type == \"boxplot\" && isTRUE(flip) && !is.null(xlabs)) {\n yaxlabs = if (!is.null(names(xlabs))) names(xlabs) else xlabs \n } else {\n # yaxl = axTicks(2)\n yaxlabs = axisTicks(usr = extendrange(ylim, f = 0.04), log = par(\"ylog\"))\n }\n if (!is.null(yaxl)) yaxlabs = tinylabel(yaxlabs, yaxl)\n # whtsbp = grconvertX(max(strwidth(yaxl, \"figure\")), from = \"nfc\", to = \"lines\") - 1\n whtsbp = grconvertX(max(strwidth(yaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - grconvertX(0, from = \"nfc\", to = \"lines\") - 1\n if (whtsbp > 0) {\n omar = omar + c(0, whtsbp, 0, 0) * cex_fct_adj\n fmar[2] = fmar[2] + whtsbp * cex_fct_adj\n }\n # Extra reduction if no plot frame to reduce whitespace\n if (isFALSE(frame.plot) && !isTRUE(facet.args[[\"free\"]])) {\n fmar[2] = fmar[2] - (whtsbp * cex_fct_adj)\n }\n }\n if (par(\"las\") %in% 2:3) {\n # extra whitespace bump on the x axis\n # xaxlabs = axTicks(1)\n xaxlabs = if (is.null(xlabs)) axisTicks(usr = extendrange(xlim, f = 0.04), log = par(\"xlog\")) else \n if (!is.null(names(xlabs))) names(xlabs) else xlabs\n if (!is.null(xaxl)) xaxlabs = tinylabel(xaxlabs, xaxl)\n whtsbp = grconvertX(max(strwidth(xaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - 1\n if (whtsbp > 0) {\n omar = omar + c(whtsbp, 0, 0, 0) * cex_fct_adj\n fmar[1] = fmar[1] + whtsbp * cex_fct_adj\n }\n # Extra reduction if no plot frame to reduce whitespace\n if (isFALSE(frame.plot) && !isTRUE(facet.args[[\"free\"]])) {\n fmar[1] = fmar[1] - (whtsbp * cex_fct_adj)\n }\n }\n # FIXME: Is this causing issues for lhs legends with facet_grid?\n # catch for missing rhs legend\n if (isTRUE(attr(facet, \"facet_grid\")) && !has_legend) {\n omar[4] = omar[4] + 1\n }\n }\n\n # Now we set the margins. The trick here is that we simultaneously adjust\n # inner (mar) and outer (oma) margins by the same amount, but in opposite\n # directions, to preserve the overall facet and plot centroids.\n nmar = (fmar + .1) / cex_fct_adj\n noma = (ooma + omar - fmar - .1) / cex_fct_adj\n # Catch in case of negative oma values. (Probably only occurs with some\n # user-supplied tpar(lmar) values and a \"left!\" positioned legend.)\n if (any(noma < 0)) {\n noma_orig = noma\n noma[noma < 0] = 0\n # noma_diff = noma-noma_orig\n # nmar = nmar + noma_diff\n }\n # apply changes\n par(oma = noma)\n par(mar = nmar)\n\n # Now that the margins have been set, arrange facet rows and columns based\n # on our earlier calculations.\n par(mfrow = c(nfacet_rows, nfacet_cols))\n } else if (dynmar) {\n # Dynamic plot margin adjustments\n omar = par(\"mar\")\n omar = omar - c(0, 0, 1, 0) # reduce top whitespace since no facet (title)\n if (type == \"spineplot\") omar[4] = 2.1 # FIXME catch for spineplot RHS axis labs\n if (par(\"las\") %in% 1:2) {\n # extra whitespace bump on the y axis\n ## overrides for ridge and some types that use integer spacing with (named) axis labels ## FXIME\n if (type == \"ridge\") {\n yaxlabs = levels(y)\n } else if (!is.null(ylabs)) {\n yaxlabs = if (!is.null(names(ylabs))) names(ylabs) else ylabs \n } else if (type == \"boxplot\" && isTRUE(flip) && !is.null(xlabs)) {\n yaxlabs = if (!is.null(names(xlabs))) names(xlabs) else xlabs \n } else {\n # yaxl = axTicks(2)\n yaxlabs = axisTicks(usr = extendrange(ylim, f = 0.04), log = par(\"ylog\"))\n }\n if (!is.null(yaxl)) yaxlabs = tinylabel(yaxlabs, yaxl)\n # whtsbp = grconvertX(max(strwidth(yaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - 1\n whtsbp = grconvertX(max(strwidth(yaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - grconvertX(0, from = \"nfc\", to = \"lines\") - 1\n if (whtsbp > 0) {\n omar[2] = omar[2] + whtsbp\n }\n }\n if (par(\"las\") %in% 2:3) {\n # extra whitespace bump on the x axis\n # xaxl = axTicks(1)\n xaxlabs = if (is.null(xlabs)) axisTicks(usr = extendrange(xlim, f = 0.04), log = par(\"xlog\")) else \n if (!is.null(names(xlabs))) names(xlabs) else xlabs\n if (!is.null(xaxl)) xaxlabs = tinylabel(xaxlabs, xaxl)\n whtsbp = grconvertX(max(strwidth(xaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - 1\n if (whtsbp > 0) {\n omar[1] = omar[1] + whtsbp\n }\n }\n par(mar = omar)\n }\n\n ## Loop over the individual facet windows and draw the plot region\n ## components (axes, titles, box, grid, etc.)\n for (ii in ifacet) {\n # See: https://github.com/grantmcdermott/tinyplot/issues/65\n if (nfacets > 1) {\n mfgi = ceiling(ii / nfacet_cols)\n mfgj = ii %% nfacet_cols\n if (mfgj == 0) mfgj = nfacet_cols\n par(mfg = c(mfgi, mfgj))\n }\n\n ## Set the plot window\n ## Problem: Passing extra args through ... (e.g., legend_args) to plot.window\n ## triggers an annoying warning about unrecognized graphical params.\n # plot.window(\n # xlim = xlim, ylim = ylim,\n # asp = asp, log = log,\n # # ...\n # )\n ## Solution: Only pass on relevant args using name checking and do.call.\n ## Idea borrowed from here: https://stackoverflow.com/a/4128401/4115816\n pdots = dots[names(dots) %in% names(formals(plot.default))]\n ## catch for flipped boxplots...\n if (type == \"boxplot\" && isTRUE(flip)) {\n log_flip = log\n if (!is.null(log)) {\n if (log == \"x\") log_flip = \"y\"\n if (log == \"y\") log_flip = \"x\"\n }\n do.call(\n \"plot.window\",\n c(list(xlim = ylim, ylim = xlim, asp = asp, log = log_flip), pdots)\n )\n xside = 2\n yside = 1\n } else {\n ## ... standard plot window for all other cases\n do.call(\n \"plot.window\",\n c(list(xlim = xlim, ylim = ylim, asp = asp, log = log), pdots)\n )\n xside = 1\n yside = 2\n }\n\n\n # axes, frame.plot and grid\n if (isTRUE(axes) || isTRUE(facet.args[[\"free\"]])) {\n args_x = list(x,\n side = xside,\n type = xaxt,\n labeller = xaxl,\n cex = get_tpar(c(\"cex.xaxs\", \"cex.axis\"), 0.8),\n lwd = get_tpar(c(\"lwd.xaxs\", \"lwd.axis\"), 1),\n lty = get_tpar(c(\"lty.xaxs\", \"lty.axis\"), 1)\n )\n args_y = list(y,\n side = yside,\n type = yaxt,\n labeller = yaxl,\n cex = get_tpar(c(\"cex.yaxs\", \"cex.axis\"), 0.8),\n lwd = get_tpar(c(\"lwd.yaxs\", \"lwd.axis\"), 1),\n lty = get_tpar(c(\"lty.yaxs\", \"lty.axis\"), 1)\n )\n if (!is.null(xaxb)) args_x$at = xaxb\n if (!is.null(yaxb)) args_y$at = yaxb\n type_range_x = type %in% c(\"barplot\", \"pointrange\", \"errorbar\", \"ribbon\", \"boxplot\", \"p\", \"violin\") && !is.null(xlabs)\n type_range_y = !is.null(ylabs) && (type == \"p\" || (isTRUE(flip) && type %in% c(\"barplot\", \"pointrange\", \"errorbar\", \"ribbon\", \"boxplot\", \"violin\")))\n if (type_range_x) {\n args_x = modifyList(args_x, list(at = xlabs, labels = names(xlabs)))\n }\n if (type_range_y) {\n args_y = modifyList(args_y, list(at = ylabs, labels = names(ylabs)))\n }\n\n if (isTRUE(facet.args[[\"free\"]]) && (par(\"xlog\") || par(\"ylog\"))) {\n warning(\n \"\\nFree scale axes for faceted plots are currently not supported if the axes are logged. Reverting back to fixed scales.\",\n \"\\nIf support for this feature is important to you, please raise an issue on our GitHub repo:\",\n \"\\nhttps://github.com/grantmcdermott/tinyplot/issues\\n\"\n )\n facet.args[[\"free\"]] = FALSE\n }\n\n # Special logic if facets are free...\n if (isTRUE(facet.args[[\"free\"]])) {\n # First, we need to calculate the plot extent and axes range of each\n # individual facet.\n xfree = split(c(x, xmin, xmax), facet)[[ii]]\n yfree = split(c(y, ymin, ymax), facet)[[ii]]\n if (!xlim_user) xlim = range(xfree, na.rm = TRUE)\n if (!ylim_user) ylim = range(yfree, na.rm = TRUE)\n xext = extendrange(xlim, f = 0.04)\n yext = extendrange(ylim, f = 0.04)\n # We'll save this in a special .fusr env var (list) that we'll re-use\n # when it comes to plotting the actual elements later\n if (ii == 1) {\n fusr = replicate(4, vector(\"double\", length = nfacets), simplify = FALSE)\n assign(\".fusr\", fusr, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n }\n fusr = get(\".fusr\", envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n fusr[[ii]] = c(xext, yext)\n assign(\".fusr\", fusr, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n # Explicitly set (override) the current facet extent\n par(usr = fusr[[ii]])\n # if plot frame is true then print axes per normal...\n if (type %in% c(\"barplot\", \"pointrange\", \"errorbar\", \"ribbon\", \"boxplot\", \"p\", \"violin\") && !is.null(xlabs)) {\n tinyAxis(xfree, side = xside, at = xlabs, labels = names(xlabs), type = xaxt, labeller = xaxl)\n } else {\n tinyAxis(xfree, side = xside, type = xaxt, labeller = xaxl)\n }\n if (isTRUE(flip) && type %in% c(\"barplot\", \"pointrange\", \"errorbar\", \"ribbon\", \"boxplot\", \"p\", \"violin\") && !is.null(ylabs)) {\n tinyAxis(yfree, side = yside, at = ylabs, labels = names(ylabs), type = yaxt, labeller = yaxl)\n } else {\n tinyAxis(yfree, side = yside, type = yaxt, labeller = yaxl)\n }\n\n # For fixed facets we can just reuse the same plot extent and axes limits\n } else if (isTRUE(frame.plot)) {\n # if plot frame is true then print axes per normal...\n do.call(tinyAxis, args_x)\n do.call(tinyAxis, args_y)\n } else {\n # ... else only print the \"outside\" axes.\n if (ii %in% oxaxis) do.call(tinyAxis, args_x)\n if (ii %in% oyaxis) do.call(tinyAxis, args_y)\n }\n }\n\n # facet titles\n ## Note: facet titles could be done more simply with mtext... but then we\n ## couldn't adjust background features (e.g., fill), or rotate the rhs\n ## facet grid text. So we're rolling our own \"manual\" versions with text\n ## and rect.\n if (!is.null(facet)) {\n # Get the four corners of plot area (x1, x2, y1, y2)\n corners = par(\"usr\")\n # catch for logged axes\n xlog = isTRUE(par(\"xlog\"))\n ylog = isTRUE(par(\"ylog\"))\n if (xlog) corners[1:2] = 10^(corners[1:2])\n if (ylog) corners[3:4] = 10^(corners[3:4])\n # special logic for facet grids\n if (is.null(facet_newlines) || facet_newlines == 0) {\n facet_title_lines = 1\n } else {\n facet_title_lines = 1 + facet_newlines\n }\n # different logic for facet grids versus regular facets\n if (isTRUE(attr(facet, \"facet_grid\"))) {\n ## top facet strips\n if (ii %in% 1:nfacet_cols) {\n if (isTRUE(facet_rect)) {\n line_height = (facet_title_lines + .1) * facet_text / cex_fct_adj\n if (ylog) {\n line_height = grconvertY(line_height, from = \"lines\", to = \"user\") / grconvertY(0, from = \"lines\", to = \"user\")\n rect_height = corners[4] * line_height\n } else {\n line_height = grconvertY(line_height, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\")\n rect_height = corners[4] + line_height\n }\n rect(\n corners[1], corners[4], corners[2], rect_height,\n col = facet_bg, border = facet_border,\n xpd = NA\n )\n }\n xpos = if (xlog) 10^(mean(log10(corners[1:2]))) else mean(corners[1:2])\n if (ylog) {\n ypos = grconvertY(0.4, from = \"lines\", to = \"user\") / grconvertY(0, from = \"lines\", to = \"user\")\n ypos = corners[4] * ypos\n } else {\n ypos = grconvertY(0.4, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\")\n ypos = corners[4] + ypos\n }\n text(\n x = xpos,\n y = ypos,\n labels = sub(\"^(.*?)~.*\", \"\\\\1\", facets[[ii]]),\n adj = c(0.5, 0),\n cex = facet_text / cex_fct_adj,\n col = facet_col,\n font = facet_font,\n xpd = NA,\n )\n }\n ## right facet strips\n if (ii %% nfacet_cols == 0 || ii == nfacets) {\n if (isTRUE(facet_rect)) {\n line_height = (facet_title_lines + .1) * facet_text / cex_fct_adj\n if (xlog) {\n line_height = grconvertX(line_height, from = \"lines\", to = \"user\") / grconvertX(0, from = \"lines\", to = \"user\")\n rect_width = corners[2] * line_height\n } else {\n line_height = grconvertX(line_height, from = \"lines\", to = \"user\") - grconvertX(0, from = \"lines\", to = \"user\")\n rect_width = corners[2] + line_height\n }\n rect(\n corners[2], corners[3], rect_width, corners[4],\n col = facet_bg, border = facet_border,\n xpd = NA\n )\n }\n if (xlog) {\n xpos = grconvertX(0.4, from = \"lines\", to = \"user\") / grconvertX(0, from = \"lines\", to = \"user\")\n xpos = corners[2] * xpos\n } else {\n xpos = grconvertX(0.4, from = \"lines\", to = \"user\") - grconvertX(0, from = \"lines\", to = \"user\")\n xpos = corners[2] + xpos\n }\n ypos = if (ylog) 10^(mean(log10(corners[3:4]))) else mean(corners[3:4])\n text(\n x = xpos,\n y = ypos,\n labels = sub(\"^.*?~(.*)\", \"\\\\1\", facets[[ii]]),\n srt = 270,\n adj = c(0.5, 0),\n cex = facet_text / cex_fct_adj,\n col = facet_col,\n font = facet_font,\n xpd = NA\n )\n }\n } else {\n if (isTRUE(facet_rect)) {\n line_height = (facet_title_lines + .1) * facet_text / cex_fct_adj\n if (ylog) {\n line_height = grconvertY(line_height, from = \"lines\", to = \"user\") / grconvertY(0, from = \"lines\", to = \"user\")\n rect_height = corners[4] * line_height\n } else {\n line_height = grconvertY(line_height, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\")\n rect_height = corners[4] + line_height\n }\n rect(\n corners[1], corners[4], corners[2], rect_height,\n col = facet_bg, border = facet_border,\n xpd = NA\n )\n }\n xpos = if (xlog) 10^(mean(log10(corners[1:2]))) else mean(corners[1:2])\n if (ylog) {\n ypos = grconvertY(0.4, from = \"lines\", to = \"user\") / grconvertY(0, from = \"lines\", to = \"user\")\n ypos = corners[4] * ypos\n } else {\n ypos = grconvertY(0.4, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\")\n ypos = corners[4] + ypos\n }\n text(\n x = xpos,\n y = ypos,\n labels = paste(facets[[ii]]),\n adj = c(0.5, 0),\n cex = facet_text / cex_fct_adj,\n col = facet_col,\n font = facet_font,\n xpd = NA\n )\n }\n }\n\n # plot frame\n if (frame.plot) box()\n\n # panel grid lines\n if (is.null(grid)) grid = .tpar[[\"grid\"]]\n if (!is.null(grid)) {\n if (is.logical(grid)) {\n ## If grid is TRUE create a default grid. Rather than just calling the default grid()\n ## abline(... = pretty(extendrange(...)), ...) is used. Reason: pretty() is generic\n ## and works better for axes based on date/time classes. Exception: For axes in logs,\n ## resort to using grid() which is likely better handled there.\n if (isTRUE(grid)) {\n gnx = gny = NULL\n if (!is.null(xaxb)) {\n abline(v = xaxb, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n gnx = NA\n } else if (!any(c(par(\"xlog\"), type == \"boxplot\"))) {\n xg = if (!inherits(x, c(\"POSIXt\", \"Date\"))) axTicks(side = 1) else axTicksDateTime(side = 1, x = x)\n abline(v = xg, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n gnx = NA\n }\n if (!is.null(yaxb)) {\n abline(h = yaxb, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n gny = NA\n } else if (!any(c(par(\"ylog\"), type == \"boxplot\"))) {\n yg = if (!inherits(y, c(\"POSIXt\", \"Date\"))) axTicks(side = 2) else axTicksDateTime(side = 2, x = x)\n abline(h = yg, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n gny = NA\n }\n grid(nx = gnx, ny = gny, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n }\n } else {\n grid\n }\n }\n\n # add any drawn elements\n if (!is.null(draw)) eval(draw)\n } # end of ii facet loop\n\n return(as.list(environment()))\n}\n\n\n#' @rdname facet\n#' @keywords internal\nfacet_layout = function(facet, add = FALSE, facet.args = list()) {\n nfacet_rows = 1\n nfacet_cols = 1\n if (!is.null(facet)) {\n facets = if (is.factor(facet)) levels(facet) else sort(unique(facet))\n ifacet = seq_along(facets)\n nfacets = length(facets)\n if (isTRUE(add)) {\n omfrow = par(\"mfrow\")\n nfacet_rows = omfrow[1]\n nfacet_cols = omfrow[2]\n } else {\n if (isTRUE(attr(facet, \"facet_grid\"))) {\n facet.args[[\"nrow\"]] = attr(facet, \"facet_nrow\")\n }\n if (!is.null(facet.args[[\"nrow\"]])) {\n nfacet_rows = facet.args[[\"nrow\"]]\n nfacet_cols = ceiling(nfacets / nfacet_rows)\n } else if (!is.null(facet.args[[\"ncol\"]])) {\n nfacet_cols = facet.args[[\"ncol\"]]\n nfacet_rows = ceiling(nfacets / nfacet_cols)\n } else {\n if (nfacets > 3) {\n nfacet_cols = ceiling(sqrt(nfacets))\n nfacet_rows = ceiling(nfacets / nfacet_cols)\n } else {\n nfacet_rows = 1L\n nfacet_cols = nfacets\n }\n }\n }\n\n oxaxis = tail(ifacet, nfacet_cols)\n oyaxis = seq(1, nfacets, by = nfacet_cols)\n\n if (nfacet_rows >= 3 || nfacet_cols >= 3) {\n cex_fct_adj = 0.66\n } else if (nfacet_rows == 2 && nfacet_cols == 2) {\n cex_fct_adj = 0.83\n } else {\n cex_fct_adj = 1\n }\n } else {\n facets = ifacet = nfacets = oxaxis = oyaxis = 1\n cex_fct_adj = 1\n }\n\n list(\n facets = facets,\n ifacet = ifacet,\n nfacets = nfacets,\n nfacet_rows = nfacet_rows,\n nfacet_cols = nfacet_cols,\n oxaxis = oxaxis,\n oyaxis = oyaxis,\n cex_fct_adj = cex_fct_adj\n )\n}\n\n\n\n#\n# helper functions\n#\n\n\n# utility function for converting facet formulas into variables\nget_facet_fml = function(formula, data = NULL) {\n xfacet = yfacet = NULL\n\n ## catch one-sided formula ~ x or ~ x | z with no \"y\" variable\n if (!inherits(formula, \"formula\")) formula = as.formula(formula)\n no_yfacet = length(formula) == 2L\n fml_rhs = if (no_yfacet) 2L else 3L\n\n ## set up model frame\n m = match.call(expand.dots = FALSE)\n\n if (!is.null(data)) {\n m = m[c(1L, match(c(\"formula\", \"data\", \"subset\", \"na.action\", \"drop.unused.levels\"), names(m), 0L))]\n }\n\n m$formula = formula\n ## need stats:: for non-standard evaluation\n m[[1L]] = quote(stats::model.frame)\n mf = eval.parent(m)\n\n ## extract variables: x, y (if any)\n if (no_yfacet) {\n yfacet_loc = NULL\n xfacet_loc = 1L\n } else {\n yfacet_loc = 1L\n xfacet_loc = 2L\n }\n if (NCOL(mf) < xfacet_loc) stop(\"formula should specify at least one variable on the right-hand side\")\n yfacet = if (no_yfacet) NULL else mf[, yfacet_loc]\n xfacet = mf[, xfacet_loc:NCOL(mf)]\n\n ## return object\n xfacet = interaction(xfacet, sep = \":\")\n if (no_yfacet) {\n ret = xfacet\n } else {\n # yfacet = interaction(yfacet, sep = \":\")\n ## NOTE: We \"swap\" the formula LHS and RHS since mfrow plots rowwise\n ret = interaction(xfacet, yfacet, sep = \"~\")\n attr(ret, \"facet_grid\") = TRUE\n attr(ret, \"facet_nrow\") = length(unique(yfacet))\n }\n\n return(ret)\n}\n\n\n## internal convenience function to determine whether the current facet panel\n## has the position \"left\", \"right\", \"top\", or \"bottom\" in the facet grid\nis_facet_position = function(position, ifacet, facet_window_args) {\n id = facet_window_args$ifacet\n nc = facet_window_args$nfacet_cols\n ni = tail(id, 1L)\n switch(position,\n \"left\" = ifacet %in% seq(1L, ni, by = nc),\n \"right\" = ifacet %in% pmin(ni, seq(1L, ni, by = nc) + nc - 1L),\n \"top\" = ifacet %in% head(id, nc),\n \"bottom\" = ifacet %in% tail(id, nc),\n NA\n )\n}\n"], ["/tinyplot/R/type_qq.R", "#' Quantile-Quantile plot (QQ)\n#'\n#' @description Plots the theoretical quantiles of `x` on the horizontal axis\n#' against observed values of `x` on the vertical axis.\n#'\n#' @param distribution Distribution function to use.\n#' @examples\n#' tinyplot(~mpg, data = mtcars, type = type_qq())\n#'\n#' # suppress the line\n#' tinyplot(~mpg, data = mtcars, lty = 0, type = type_qq())\n#' @importFrom stats qnorm ppoints quantile\n#' @export\ntype_qq = function(distribution = qnorm) {\n data_qq = function(distribution) {\n fun = function(datapoints, ...) {\n y = sort(datapoints$y)\n x = datapoints$x\n x = distribution(ppoints(x))\n datapoints$x = x\n datapoints$y = y\n out = list(datapoints = datapoints)\n return(out)\n }\n }\n\n draw_qq = function() {\n fun = function(ix, iy, icol, ibg, ipch, ilwd, ilty, cex, xlab, ...) {\n points(\n x = ix,\n y = iy,\n col = icol,\n bg = ibg,\n type = \"p\",\n pch = ipch,\n lwd = ilwd,\n cex = cex\n )\n\n if (!is.null(ilty)) {\n iy <- quantile(iy, c(0.25, 0.75))\n ix <- quantile(ix, c(0.25, 0.75))\n slope <- diff(iy) / diff(ix)\n intercept <- iy[1] - slope * ix[1]\n abline(a = intercept, b = slope, lty = ilty, col = icol, lwd = ilwd)\n }\n }\n return(fun)\n }\n\n out = list(\n draw = draw_qq(),\n data = data_qq(distribution = distribution),\n name = \"qq\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_function.R", "#' Plot a function\n#'\n#' @details\n#' When using `type_function()` in a `tinyplot()` call, the `x` value indicates\n#' the range of values to plot on the x-axis.\n#'\n#' @param fun Function of `x` to plot. Defaults to \\code{\\link[stats]{dnorm}}.\n#' @param args List of additional arguments to be passed to `fun`.\n#' @param n Number of points to interpolate on the x axis.\n#' @param ... Additional arguments are passed to the `lines()` function,\n#' ex: `type=\"p\"`, `col=\"pink\"`.\n#' @importFrom stats dnorm\n#' \n#' @examples\n#' # Plot the normal density (default function)\n#' tinyplot(x = -4:4, type = \"function\")\n#' # tinyplot(x = -4:4, type = type_function()) # same\n#'\n#' # Customize by passing explicit arguments to your function\n#' tinyplot(x = -1:10, type = type_function(\n#' fun = dnorm, args = list(mean = 3)\n#' ))\n#'\n#' # Additional arguments are passed to the `lines()` function.\n#' tinyplot(x = -4:4, type = type_function(\n#' fun = dnorm,\n#' col = \"pink\", type = \"p\", pch = 3\n#' ))\n#' \n#' # Custom function example\n#' ## (Here using `function(x)`, but you could also use the shorter `\\(x)`\n#' ## anonymous function syntax introduced in R 4.1.0)\n#' tinyplot(x = -4:4, type = type_function(fun = function(x) 0.5 * exp(-abs(x))))\n#'\n#' @export\ntype_function = function(fun = dnorm, args = list(), n = 101, ...) {\n assert_function(fun)\n lines_args = list(...)\n data_function = function(args, fun) {\n funky = function(xlim, ylim, datapoints, ...) {\n if (nrow(datapoints) == 0 || !\"x\" %in% names(datapoints)) {\n stop(\"Need to provide x values to plot the function.\", call. = FALSE)\n }\n if (is.null(xlim)) {\n xlim = range(datapoints[[\"x\"]])\n }\n if (is.null(ylim)) {\n tmp = c(list(datapoints[[\"x\"]]), args)\n tmp = range(tmp)\n tmp = seq(tmp[1], tmp[2], length.out = n)\n tmp = c(list(tmp), args)\n tmp = do.call(fun, tmp)\n ylim = c(min(tmp), max(tmp))\n }\n out = list(xlim = xlim, ylim = ylim)\n return(out)\n }\n }\n draw_function = function() {\n funky = function(ifacet, data_facet, ...) {\n xrange = range(data_facet[[ifacet]][[\"x\"]])\n x = seq(xrange[1], xrange[2], length.out = n)\n y = do.call(fun, c(list(x), args))\n tmp = c(list(x, y), lines_args)\n do.call(lines, tmp)\n }\n return(funky)\n }\n out = list(\n draw = draw_function(),\n data = data_function(args = args, fun = fun),\n name = \"function\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_points.R", "#' Points plot type\n#'\n#' @description Type function for plotting points, i.e. a scatter plot.\n#' \n#' @examples\n#' # \"p\" type convenience character string\n#' tinyplot(Sepal.Length ~ Petal.Length, data = iris, type = \"p\")\n#' \n#' # Same result with type_points()\n#' tinyplot(Sepal.Length ~ Petal.Length, data = iris, type = type_points())\n#' \n#' # Note: Specifying the type here is redundant. Like base plot, tinyplot\n#' # automatically produces a scatter plot if x and y are numeric\n#' tinyplot(Sepal.Length ~ Petal.Length, data = iris)\n#' \n#' # Grouped scatter plot example\n#' tinyplot(Sepal.Length ~ Petal.Length | Species, data = iris)\n#' \n#' # Continuous grouping (with gradient legend)\n#' tinyplot(Sepal.Length ~ Petal.Length | Sepal.Width, data = iris, pch = 19)\n#' \n#' @export\ntype_points = function() {\n out = list(\n draw = draw_points(),\n data = data_points(),\n name = \"p\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\ndata_points = function() {\n fun = function(datapoints, ...) {\n # catch for factors (we should still be able to \"force\" plot these with points)\n if (is.factor(datapoints$x)) {\n xlvls = levels(datapoints$x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n datapoints$x = as.integer(datapoints$x)\n } else {\n xlabs = NULL\n }\n if (is.factor(datapoints$y)) {\n ylvls = levels(datapoints$y)\n ylabs = seq_along(ylvls)\n names(ylabs) = ylvls\n datapoints$y = as.integer(datapoints$y)\n } else {\n ylabs = NULL\n }\n \n out = list(\n datapoints = datapoints,\n xlabs = xlabs,\n ylabs = ylabs\n )\n return(out)\n }\n}\n\ndraw_points = function() {\n fun = function(ix, iy, icol, ibg, ipch, ilwd, cex, ...) {\n points(\n x = ix,\n y = iy,\n col = icol,\n bg = ibg,\n type = \"p\",\n pch = ipch,\n lwd = ilwd,\n cex = cex\n )\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_rug.R", "#' Add a rug to a plot\n#' \n#' @description\n#' Adds a rug representation (1-d plot) of the data to the plot.\n#' \n#' @details\n#' This function should only be used as part of [`tinyplot_add()`], i.e. adding\n#' to an existing plot.\n#' \n#' In most cases, determining which variable receives the rug representation\n#' will be based on the `side` argument (i.e., x-variable if side is 1 or 3, and\n#' y-variable if side is 2 or 4). An exception is if the preceding plot type was\n#' either `\"density\"` or `\"histogram\"`; for these latter cases, the x-variable\n#' will always be used. See Examples.\n#' \n#' @inheritParams graphics::rug\n#' @param jitter Logical. Add jittering to separate ties? Default is `FALSE`.\n#' @param amount Numeric. Amount of jittering (see \\code{\\link[base]{jitter}}).\n#' Only used if `jitter` is `TRUE`.\n#' @examples\n#' tinyplot(~wt | am, data = mtcars, type = \"density\", facet = \"by\", fill = \"by\")\n#' tinyplot_add(type = \"rug\")\n#' # use type_rug() to pass extra options\n#' tinyplot_add(type = type_rug(side = 3, ticksize = 0.05))\n#' \n#' # For ties, use jittering\n#' tinyplot(eruptions ~ waiting, data = faithful, type = \"lm\")\n#' tinyplot_add(type = type_rug(jitter = TRUE, amount = 0.3))\n#' tinyplot_add(type = type_rug(jitter = TRUE, amount = 0.1, side = 2))\n#' # Add original points just for reference\n#' tinyplot_add(type = \"p\")\n#' \n#' @importFrom graphics rug\n#' @export\ntype_rug = function(ticksize = 0.03, side = 1, quiet = getOption(\"warn\") < 0, jitter = FALSE, amount = NULL) {\n data_rug = function(datapoints, ...) {\n if (nrow(datapoints) == 0) {\n msg = \"`type_rug() only works on existing plots with x and y data points.\"\n stop(msg, call. = FALSE)\n }\n return(datapoints)\n }\n draw_rug = function(.ticksize = ticksize, .side = side, .quiet = quiet, .jitter = jitter, .amount = amount) {\n fun = function(ix, iy, icol, ilwd, ...) {\n lc = getOption(\"tinyplot_last_call\", default = NULL)\n swapy = !is.null(lc$type) && lc$type %in% c(\"density\", \"hist\", \"histogram\")\n rugx = if (swapy) iy else if (side %in% c(1, 3)) ix else iy\n if (isTRUE(jitter)) rugx = jitter(rugx, amount = .amount)\n rug(\n x = rugx,\n col = icol,\n lwd = ilwd,\n ticksize = .ticksize,\n side = .side,\n quiet = .quiet\n )\n }\n return(fun)\n }\n\n out = list(\n draw = draw_rug(),\n data = data_rug,\n name = \"rug\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_abline.R", "#' Add straight lines to a plot\n#' @description\n#' These functions add straight line(s) through the current plot.\n#' @details\n#' While `type_abline`, `type_hline`, and `type_vline` can be called in a base\n#' plot layer, we expect that they will typically be called as subsequent\n#' layers via [`tinyplot_add`].\n#' @section Recycling logic: \n#' The recycling behaviour of the line parameters (i.e., `a`, `b`, `h`, or `v`)\n#' is adaptive, depending on whether `by` or `facet` grouping is detected. While\n#' this leads to different recycling scenarios, the underlying code logic\n#' follows sensible heuristics designed to match user expectations.\n#' \n#' Parameter lengths must equal one of four options:\n#' \n#' 1. Single value (i.e., length = 1), i.e. simplest case where the same line is\n#' applied uniformly across all groups and facets. Uses the default user colour\n#' (e.g. `\"black\"`, or `tpar(\"palette.qualitative\")[1]` if a theme is set).\n#' 2. Number of `by` groups, i.e. one parameter per group. For example,\n#' `tinyplot(mpg ~ wt | factor(cyl), data = mtcars, type = type_hline(h = 21:23))`\n#' will give three horizontal lines, with colours matching the user's qualitative\n#' palette.\n#' 3. Number of `facet` groups, i.e. one parameter per facet panel. For example:\n#' `tinyplot(mpg ~ wt, facet = ~am, data = mtcars, type = type_hline(h = c(20,30)))`\n#' would give separate horizontal lines per facet, but both using the same\n#' default color.\n#' 4. Product of `by` and `facet` groups, i.e. one parameter for each unique\n#' by-facet combination. Orders over facets first and then, within that, by\n#' group. For example:\n#' `tinyplot(mpg ~ wt | factor(cyl), facet = ~am, data = mtcars, type = type_hline(h = 21:26))`\n#' will give six separate lines, with the first three (`21:23`) coloured by\n#' group in the first facet, and second three (`24:26`) coloured by by group\n#' in the second facet.\n#' \n#' Alongside these general rules, we also try to accomodate special cases when\n#' other aesthetic parameters like `lwd` or `lty` are invoked by the user. See\n#' Examples.\n#' \n#' @param a,b the intercept (default: `a` = 0) and slope (default: `b` = 1)\n#' terms. Numerics of length 1, or equal to the number of groups or number of\n#' facets (or the product thereof).\n#' @examples\n#' #\n#' ## abline\n#' \n#' tinyplot(x = -10:10, y = rnorm(21) + -10:10, grid = TRUE)\n#' tinyplot_add(type = \"abline\")\n#' # same as...\n#' # tinyplot_add(type = type_abline(a = 0, b = 1))\n#' \n#' # customize by passing bespoke intercept and slope values\n#' tinyplot_add(type = type_abline(a = -1, b = -0.5))\n#' \n#' # note that calling as abline & co. as a base plot layer will still lead to\n#' # axes limits that respect the range of the data\n#' tinyplot(x = -10:10, y = -10:10, grid = TRUE, type = \"abline\")\n#' \n#' #\n#' ## hline and vline\n#'\n#' # Base plot layer\n#' tinyplot(mpg ~ hp | cyl, facet = \"by\", data = mtcars, ylim = c(0, 40))\n#' \n#' # Add horizontal lines at the (default) 0 y-intercept\n#' tinyplot_add(type = \"hline\", col = \"grey\")\n#' \n#' # Note that group+facet aesthetics will be inherited. We can use this to\n#' # add customized lines (here: the mean `mpg` for each `cyl` group) \n#' tinyplot_add(type = type_hline(with(mtcars, tapply(mpg, cyl, mean))), lty = 2)\n#' \n#' # Similar idea for vline\n#' tinyplot_add(type = type_vline(with(mtcars, tapply(hp, cyl, mean))), lty = 2)\n#' \n#' #\n#' ## Recycling logic\n#' \n#' # length(h) == no. of groups\n#' tinyplot(mpg ~ wt | factor(cyl), data = mtcars, type = type_hline(h = 21:23))\n#' \n#' # length(h) == no. of facets\n#' tinyplot(mpg ~ wt, facet = ~am, data = mtcars, type = type_hline(h = c(20, 30)))\n#' \n#' # length(h) == no. of groups x no. of facets\n#' tinyplot(mpg ~ wt | factor(cyl), facet = ~am, data = mtcars,\n#' type = type_hline(h = 21:26))\n#' \n#' # special adjustment case (here: lwd by group)\n#' tinyplot(mpg ~ wt | factor(cyl), facet = ~am, data = mtcars,\n#' type = type_hline(c(20, 30)), lwd = c(21, 14, 7))\n#' \n#' @export\ntype_abline = function(a = 0, b = 1) {\n data_abline = function(datapoints, lwd, lty, col, ...) {\n if (nrow(datapoints) == 0) {\n msg = \"`type_abline() only works on existing plots with x and y data points.\"\n stop(msg, call. = FALSE)\n }\n # keep track of unique lty and lwd (needed for group catch / escape hatch\n # later in draw_hline)\n ul_lwd = length(unique(lwd))\n ul_lty = length(unique(lty))\n ul_col = length(unique(col))\n return(list(type_info = list(ul_lty = ul_lty, ul_lwd = ul_lwd, ul_col = ul_col)))\n }\n draw_abline = function() {\n fun = function(\n ifacet, iby, data_facet, icol, ilty, ilwd,\n ngrps, nfacets, by_continuous, facet_by,\n type_info,\n ...\n ) {\n \n # flag for aesthetics by groups\n grp_aes = type_info[[\"ul_col\"]] == 1 || type_info[[\"ul_lty\"]] == ngrps || type_info[[\"ul_lwd\"]] == ngrps\n \n if (length(a) != 1) {\n if (!length(a) %in% c(ngrps, nfacets, ngrps*nfacets)) {\n msg = \"Length of 'a' must be 1, or equal to the number of facets or number of groups (or product thereof).\"\n stop(msg, call. = FALSE)\n }\n if (!facet_by && length(a) == nfacets) {\n a = a[ifacet]\n if (!grp_aes && type_info[[\"ul_col\"]]!=ngrps) {\n icol = 1\n } else if (by_continuous) {\n icol = 1\n }\n } else if (!by_continuous && length(a) == ngrps * nfacets) {\n a = a[ifacet * ngrps - c(ngrps - iby)]\n } else if (!by_continuous) {\n a = a[iby]\n }\n } else if (!grp_aes) {\n icol = 1\n }\n \n if (length(b) != 1) {\n if (!length(b) %in% c(ngrps, nfacets, ngrps*nfacets)) {\n msg = \"Length of 'b' must be 1, or equal to the number of facets or number of groups (or product thereof).\"\n stop(msg, call. = FALSE)\n }\n if (!facet_by && length(b) == nfacets) {\n b = b[ifacet]\n if (!grp_aes && type_info[[\"ul_col\"]]!=ngrps) {\n icol = 1\n } else if (by_continuous) {\n icol = 1\n }\n } else if (!by_continuous && length(b) == ngrps * nfacets) {\n b = b[ifacet * ngrps - c(ngrps - iby)]\n } else if (!by_continuous) {\n b = b[iby]\n }\n } else if (!grp_aes) {\n icol = 1\n }\n \n if (type_info[[\"ul_col\"]]!=1 && !(type_info[[\"ul_lty\"]]==ngrps || type_info[[\"ul_lwd\"]]==ngrps)) {\n icol = 1\n }\n\n abline(a = a, b = b, col = icol, lty = ilty, lwd = ilwd)\n }\n return(fun)\n }\n out = list(\n draw = draw_abline(),\n data = data_abline,\n name = \"abline\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_errorbar.R", "#' Error bar and pointrange plot types\n#' \n#' @description Type function(s) for producing error bar and pointrange plots.\n#' \n#' @inheritParams graphics::arrows\n#' @examples\n#' mod = lm(mpg ~ wt * factor(am), mtcars)\n#' coefs = data.frame(names(coef(mod)), coef(mod), confint(mod))\n#' colnames(coefs) = c(\"term\", \"est\", \"lwr\", \"upr\")\n#' \n#' op = tpar(pch = 19)\n#' \n#' # \"errorbar\" and \"pointrange\" type convenience strings\n#' tinyplot(est ~ term, ymin = lwr, ymax = upr, data = coefs, type = \"errorbar\")\n#' tinyplot(est ~ term, ymin = lwr, ymax = upr, data = coefs, type = \"pointrange\")\n#' \n#' # Use `type_errorbar()` to pass extra arguments for customization\n#' tinyplot(est ~ term, ymin = lwr, ymax = upr, data = coefs, type = type_errorbar(length = 0.2))\n#' \n#' tpar(op)\n#' \n#' @export\ntype_errorbar = function(length = 0.05) {\n out = list(\n draw = draw_errorbar(length = length),\n data = data_pointrange(),\n name = \"p\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_errorbar = function(length = 0.05) {\n fun = function(ix, iy, ixmin, iymin, ixmax, iymax, icol, ibg, ipch, ilwd, cex, ...) {\n arrows(\n x0 = ixmin,\n y0 = iymin,\n x1 = ixmax,\n y1 = iymax,\n col = icol,\n lwd = ilwd,\n length = length,\n angle = 90,\n code = 3\n )\n draw_points()(ix = ix, iy = iy, icol = icol, ibg = ibg, ipch = ipch, ilwd = ilwd, cex = cex)\n }\n return(fun)\n}\n\n\n"], ["/tinyplot/R/tinyAxis.R", "#' @title Generic function for adding an axis to a (tiny)plot\n#' \n#' @description Internal function used for adding an axis to a [`tinyplot`]\n#' call.\n#' @details `tinyAxis` provides a thin(ish) wrapper around\n#' \\code{\\link[graphics]{Axis}}, but with enhanced flexibility to (i) match\n#' parameter combinations based on the axis type and plotting theme, (ii)\n#' provide better support for date-time variables, and (iii) enable convenient\n#' formatting of axis tick labels.\n#' @inheritParams graphics::Axis\n#' @param type the type of axis to be drawn; inherited from the `xaxt` or `yaxt`\n#' arguments of the parent [`tinyplot()`] call. One of either: `\"standard\"`\n#' (default that draws the axis, ticks, and labels), `\"none\"` (no axes),\n#' `\"ticks\"` (only ticks and labels without axis line), `\"labels\"` (only\n#' labels without ticks and axis line), or `\"axis\"` (only axis line and labels\n#' but no ticks). Partial matching is allowed, e.g. `type = \"s\"`.\n#' @inheritParams tinylabel\n#' @examples\n#' \\dontrun{\n#' \n#' # plot without axes\n#' tinyplot(0:10, axes = \"n\")\n#' # add x-axis (labels only)\n#' tinyplot:::tinyAxis(x = 0:10, side = 1, type = \"l\")\n#' # add y-axis (with custom label formatting)\n#' tinyplot:::tinyAxis(x = 0:10, side = 2, type = \"s\", labeller = \"$\")\n#' }\n#' @keywords internal\ntinyAxis = function(x = NULL, ..., type = \"standard\", labeller = NULL) {\n type = match.arg(type, c(\"standard\", \"none\", \"labels\", \"ticks\", \"axis\"))\n if (type == \"none\") {\n invisible(numeric(0L))\n } else {\n args = list(x = x, ...)\n if (type == \"labels\") {\n args$tick = FALSE\n } else if (type == \"ticks\") {\n args$lwd = 0\n if (!(\"lwd.ticks\" %in% names(args))) args$lwd.ticks = 1\n } else if (type == \"axis\") {\n args$lwd.ticks = 0\n } else {\n args$tick = TRUE\n }\n if (!is.null(labeller)) {\n if (!is.null(args$at)) {\n args$labels = if (!is.null(args$labels)) tinylabel(args$labels, labeller) else tinylabel(args$at, labeller)\n } else {\n args$at = if (!inherits(x, c(\"POSIXt\", \"Date\"))) axTicks(args$side) else axTicksDateTime(args$side, x = x) \n args$labels = tinylabel(args$at, labeller)\n }\n }\n do.call(\"Axis\", args)\n }\n}\n\n# Special case for Date-Time, adapted/simplified from axis.date()\naxTicksDateTime = function(side, x, ...) {\n if (inherits(x, \"POSIXt\")) {\n tz = attr(x, \"tz\")\n range = extendrange(x)\n rangeDateTime = .POSIXct(range, tz = tz)\n } else {\n range = sort(par(\"usr\")[if (side%%2) 1L:2L else 3:4L])\n range[1L] = ceiling(range[1L])\n range[2L] = floor(range[2L])\n rangeDateTime = range\n class(rangeDateTime) = \"Date\"\n }\n z = pretty(rangeDateTime, n = par(\"lab\")[2 - side%%2])\n keep = z >= range[1L] & z <= range[2L]\n z = z[keep]\n return(z)\n}\n"], ["/tinyplot/R/type_text.R", "#' Text annotations plot type\n#'\n#' @description Type function for adding text annotations to a plot. This function allows\n#' you to draw text at specified (x,y) coordinates.\n#'\n#' @param labels Character vector of length 1 or of the same length as the\n#' number of x,y coordinates.\n#' @param font Font to be used, following [graphics::par()].\n#' @param xpd Logical value or `NA` denoting text clipping behaviour, following\n#' [graphics::par()].\n#' @param srt Numeric giving the desired string rotation in degrees.\n#' @inheritParams graphics::text\n#' @examples\n#' tinyplot(mpg ~ hp | factor(cyl),\n#' data = mtcars,\n#' type = type_text(\n#' labels = row.names(mtcars),\n#' font = 2,\n#' adj = 0\n#' )\n#' )\n#' \n#' # to avoid clipping text at the plot region, we can use xpd = NA\n#' tinyplot(mpg ~ hp | factor(cyl),\n#' data = mtcars,\n#' type = type_text(\n#' labels = row.names(mtcars),\n#' font = 2,\n#' adj = 0,\n#' xpd = NA\n#' )\n#' )\n#'\n#' @export\ntype_text = function(labels, adj = NULL, pos = NULL, offset = 0.5, vfont = NULL, font = NULL, xpd = NULL, srt = 0) {\n out = list(\n draw = draw_text(adj = adj, pos = pos, offset = offset, vfont = vfont, font = font, xpd = xpd, srt = srt),\n data = data_text(labels = labels),\n name = \"text\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\ndata_text = function(labels) {\n fun = function(datapoints, ...) {\n if (length(labels) != 1 && length(labels) != nrow(datapoints)) {\n msg <- sprintf(\"`labels` must be of length 1 or %s.\", nrow(datapoints))\n stop(msg, call. = FALSE)\n }\n datapoints$labels = labels\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\ndraw_text = function(adj = NULL, pos = NULL, offset = 0.5, vfont = NULL, font = NULL, xpd = NULL, srt = 0) {\n if (is.null(xpd)) xpd = par(\"xpd\")\n fun = function(ix, iy, ilabels, icol, cex, ...) {\n text(\n x = ix, y = iy, labels = ilabels, col = icol,\n adj = adj, pos = pos, offset = offset,\n vfont = vfont, font = font,\n xpd = xpd,\n srt = srt,\n cex = cex\n )\n }\n}\n"], ["/tinyplot/R/type_area.R", "#' @rdname type_ribbon\n#' @export\ntype_area = function(alpha = NULL) {\n out = list(\n draw = NULL,\n data = data_area(alpha = alpha),\n name = \"area\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_area = function(alpha = alpha) {\n ribbon.alpha = if (is.null(alpha)) .tpar[[\"ribbon.alpha\"]] else (alpha)\n fun = function(datapoints, ...) {\n datapoints$ymax = datapoints$y\n datapoints$ymin = rep.int(0, nrow(datapoints))\n out = list(\n datapoints = datapoints,\n ymax = datapoints$ymax,\n ymin = datapoints$ymin,\n type = \"ribbon\",\n ribbon.alpha = ribbon.alpha\n )\n return(out)\n }\n return(fun)\n}\n"], ["/tinyplot/R/by_aesthetics.R", "by_col = function(ngrps = 1L, col = NULL, palette = NULL, gradient = NULL, ordered = NULL, alpha = NULL) {\n if (is.null(alpha)) alpha = 1\n if (is.null(ordered)) ordered = FALSE\n if (is.null(gradient)) gradient = FALSE\n assert_logical(ordered)\n assert_logical(gradient)\n if (gradient) {\n ngrps = 100L\n }\n \n # pal_qual = get_tpar(\"palette.qualitative\", default = NULL)\n pal_theme = get_tpar(\"palette.qualitative\", default = NULL)\n theme_flag = !is.null(pal_theme)\n\n # palette = substitute(palette, env = parent.env(environment()))\n\n # special \"by\" convenience keyword (will treat as NULL & handle grouping below)\n if (!anyNA(col) && !is.null(col) && length(col) == 1 && col == \"by\") col = NULL\n\n #\n ## Base case: If no color or palette provided, pass colors as a sequence of\n ## numbers (will inherit from / cycle over the user's default palette)\n \n if (is.null(col) && (is.null(palette) && !theme_flag)) {\n if (ngrps <= length(palette()) && !ordered) {\n col = palette()[seq_len(ngrps)]\n if (alpha) col = adjustcolor(col, alpha.f = alpha)\n } else {\n # fallback to restricted viridis palette\n col = colorRampPalette(\n hcl.colors(n = 100, palette = \"Viridis\", alpha = alpha)[(100 * 0.1 + 1):(100 * 0.9)],\n alpha = TRUE\n )(ngrps)\n }\n if (gradient || ordered) col = rev(col)\n return(col)\n }\n\n #\n ## Next simplest case: No palette, but color(s) provided directly. We do\n ## some simple sanity checks, apply alpha transparency and return as-is.\n\n if (is.atomic(col) && is.vector(col)) {\n if (length(col) == 1) {\n col = rep(col, ngrps)\n if (alpha) col = adjustcolor(col, alpha.f = alpha)\n return(col)\n } else if (length(col) < ngrps) {\n # if (!gradient) {\n # stop(sprintf(\"`col` must be of length 1, or greater than or equal to %s.\", ngrps), call. = FALSE)\n # } else {\n # # interpolate gradient colors\n # col = colorRampPalette(colors = col, alpha = TRUE)(ngrps)\n # }\n # if manual colours < ngrps, either (1) interpolate for gradient\n # colors, or (2) recycle for discrete colours\n if (gradient) {\n col = colorRampPalette(colors = col, alpha = TRUE)(ngrps)\n } else {\n ncolsstr = paste0(\"(\", length(col), \")\")\n ngrpsstr = paste0(\"(\", ngrps, \")\")\n warning(\n \"\\nFewer colours \", ncolsstr, \" provided than than there are groups \",\n ngrpsstr, \". Recycling to make up the shortfall.\"\n )\n col = rep(col, length.out = ngrps)\n }\n \n }\n if (gradient) {\n col = rev(col)\n } else if (!ordered && is.numeric(col)) {\n # col = palette()[col]\n if (ngrps <= length(palette())) {\n col = palette()[col]\n # if (alpha) col = adjustcolor(col, alpha.f = alpha)\n } else {\n col = hcl.colors(max(col), alpha = alpha)[col]\n }\n }\n if (anyNA(col) || is.character(col)) {\n if (alpha) col = adjustcolor(col, alpha.f = alpha)\n return(col)\n }\n }\n \n \n #\n ## Theme case: No palette provided, but fallback to tinytheme palette\n\n # we need to fix palette string, determine if in palette.pals() and then\n # determine no. of groups, before kicking over to sequential\n if (is.null(palette) && theme_flag) {\n if (length(pal_theme) == 1) {\n qual_match = match_pal(pal_theme, palette.pals())\n if (!is.na(qual_match)) {\n if (ngrps >= get_pal_lens(pal_theme) || ordered) {\n pal_theme = get_tpar(\"palette.sequential\", default = NULL)\n }\n # mostly a catch for x-gradient fills, e.g. type_ridge\n } else if (gradient && !is.na(match_pal(pal_theme, hcl.pals()))) {\n pal_theme = get_tpar(\"palette.sequential\", default = NULL)\n }\n }\n if (length(pal_theme) == 1) {\n palette_fun = gen_pal_fun(pal = pal_theme, gradient = gradient, alpha = alpha)\n args = list(n = ngrps, palette = pal_theme, alpha = alpha)\n }\n palette = pal_theme\n }\n \n if (is.null(palette)) {\n if (ngrps <= length(palette()) && !ordered && !gradient) {\n palette_fun = function(alpha) adjustcolor(palette(), alpha) # must be function to avoid arg ambiguity\n args = list(alpha = alpha)\n } else {\n if (ngrps <= 8 && !ordered) { # ngrps < 100 so we know gradient is FALSE too\n palette = \"R4\"\n palette_fun = palette.colors\n } else {\n palette = \"Viridis\"\n if (!gradient && !ordered) {\n palette_fun = hcl.colors\n } else {\n palette_fun_gradient = function(n, palette, from = 0.1, to = 0.9, alpha = 1) {\n colorRampPalette(\n hcl.colors(n = 100, palette = palette, alpha = alpha)[(100 * from + 1):(100 * to)],\n alpha = TRUE\n )(n)\n }\n palette_fun = palette_fun_gradient\n }\n }\n args = list(n = ngrps, palette = palette, alpha = alpha)\n }\n } else {\n if (is.character(palette)) {\n # special case: if vector of character strings, we assume that the user\n # must have passed a vector of colours (e.g., c(\"red\", \"blue\")) rather\n # than a known/named colour palette (e.g. \"Harmonic\")\n if (length(palette) > 1) {\n palette_fun = \"c\"\n if (!is.null(alpha)) palette = adjustcolor(palette, alpha.f = alpha)\n args = as.list(palette)\n if (length(args) < ngrps && length(args) != 1) {\n # if manual colours < ngrps, either (1) interpolate for gradient\n # colors, or (2) recycle for discrete colours\n if (gradient) {\n args = list(colorRampPalette(args, alpha = TRUE)(ngrps))\n } else {\n ncolsstr = paste0(\"(\", length(args), \")\")\n ngrpsstr = paste0(\"(\", ngrps, \")\")\n warning(\n \"\\nFewer colours \", ncolsstr, \" provided than than there are groups \",\n ngrpsstr, \". Recycling to make up the shortfall.\"\n )\n args = rep(args, length.out = ngrps)\n }\n }\n } else {\n palette_fun = gen_pal_fun(palette, gradient = gradient, alpha = alpha, n = ngrps)\n args = list(n = ngrps, palette = palette, alpha = alpha)\n }\n } else if (inherits(palette, c(\"call\", \"name\"))) {\n # catch for when using passes palette as named object (e.g,\n # pal26 = palette.colors(\"Alphabet\"))\n if (inherits(palette, \"name\") && is.character(eval(palette))) {\n args = as.list(eval(palette))\n palette_fun = \"c\"\n } else {\n args = as.list(palette)\n palette_fun = paste(args[[1]])\n args[[1]] = NULL\n }\n # catch for direct vector or list\n if (palette_fun %in% c(\"c\", \"list\")) {\n if (palette_fun == \"list\") palette_fun = \"c\"\n if (!is.null(alpha)) args = lapply(args, function(a) adjustcolor(a, alpha.f = alpha))\n if (length(args) < ngrps && length(args) != 1) {\n # if manual colours < ngrps, either (1) interpolate for gradient\n # colors, or (2) recycle for discrete colours\n if (gradient) {\n args = list(colorRampPalette(args, alpha = TRUE)(ngrps))\n } else {\n ncolsstr = paste0(\"(\", length(args), \")\")\n ngrpsstr = paste0(\"(\", ngrps, \")\")\n warning(\n \"\\nFewer colours \", ncolsstr, \" provided than than there are groups \",\n ngrpsstr, \". Recycling to make up the shortfall.\"\n )\n args = rep(args, length.out = ngrps)\n }\n }\n } else {\n args[[\"n\"]] = ngrps\n # remove unnamed arguments to prevent unintentional argument sliding\n if (any(names(args) == \"\")) args[[which(names(args) == \"\")]] = NULL\n }\n } else if (inherits(palette, \"function\")) {\n args = list()\n palette_fun = palette\n } else {\n stop(\n \"\\nInvalid palette argument. Must be a recognized keyword, or a \",\n \"palette-generating function with named arguments.\\n\"\n )\n }\n }\n\n cols = tryCatch(\n do.call(palette_fun, args),\n error = function(e) do.call(eval(palette), args) # catch for bespoke palette generating funcs\n )\n\n if (length(cols) > ngrps) cols = cols[1:ngrps]\n\n # For gradient and ordered colors, we'll run high to low\n if (gradient || ordered) cols = rev(cols)\n\n return(cols)\n}\n\n# Some utility functions for palette matching, etc.\n\nmatch_pal = function(pal, pals) {\n fx = function(x) tolower(gsub(\"[-, _, \\\\,, (, ), \\\\ , \\\\.]\", \"\", x))\n charmatch(fx(pal), fx(pals))\n}\n\nget_pal_lens = function(pal) {\n pal_lens = c(\n R3 = 8L, R4 = 8L, ggplot2 = 8L, `Okabe-Ito` = 9L, Accent = 8L,\n `Dark 2` = 8L, Paired = 12L, `Pastel 1` = 9L, `Pastel 2` = 8L, \n `Set 1` = 9L, `Set 2` = 8L, `Set 3` = 12L, `Tableau 10` = 10L, \n `Classic Tableau` = 10L, `Polychrome 36` = 36L, Alphabet = 26L\n )\n pal_lens[pal]\n}\n\n# take a character string, match to either palette.pals() pr hcl.pals(), and\n# generate the corresponding function factor with alpha transparency\ngen_pal_fun = function(pal, gradient = FALSE, alpha = NULL, n = NULL) {\n pal_match = match_pal(pal, palette.pals())\n if (!is.na(pal_match)) {\n if (pal_match < 1L) stop(\"'palette' is ambiguous\")\n pal_fun = palette.colors\n if (!is.null(n) && n >= get_pal_lens(pal_match)) {\n warning(\n \"\\nFewer colours \", get_pal_lens(pal_match), \" provided than than there are groups \",\n n, \". Recycling to make up the shortfall.\"\n )\n pal_fun = function(n, palette, alpha) palette.colors(n = n, palette = pal, alpha = alpha, recycle = TRUE)\n }\n if (gradient) {\n pal_fun = function(n, palette, alpha) colorRampPalette(palette.colors(palette = pal, alpha = alpha))(n)\n }\n } else {\n pal_match = match_pal(pal, hcl.pals())\n if (!is.na(pal_match)) {\n if (pal_match < 1L) stop(\"'palette' is ambiguous\")\n pal_fun = hcl.colors\n } else {\n stop(\n \"\\nPalette string not recogized. Must be a value produced by either\",\n \"`palette.pals()` or `hcl.pals()`.\\n\",\n call. = FALSE\n )\n }\n }\n return(pal_fun)\n}\n\n\nby_pch = function(ngrps, type, pch = NULL) {\n no_pch = FALSE\n if (identical(type, \"text\")) {\n pch <- rep(15, ngrps)\n } else if (!type %in% c(\"p\", \"b\", \"o\", \"pointrange\", \"errorbar\", \"boxplot\", \"qq\")) {\n no_pch = TRUE\n pch = NULL\n\n # special \"by\" convenience keyword\n } else if (!is.null(pch) && length(pch) == 1 && pch == \"by\") {\n no_pch = TRUE # skip checks below\n pch = 1:ngrps + par(\"pch\") - 1\n # correctly recycle if over max pch type\n pch_ceiling = 25 # see ?pch\n if (max(pch) > pch_ceiling) {\n pch_below = pch[pch <= pch_ceiling]\n pch_above = pch[pch > pch_ceiling]\n pch_above = rep_len(0:pch_ceiling, length(pch_above))\n pch = c(pch_below, pch_above)\n }\n\n # return NULL if not a valid point type\n } else if (is.null(pch)) {\n pch = par(\"pch\")\n }\n\n if (!no_pch) {\n if (!is.atomic(pch) || !is.vector(pch) || !(is.numeric(pch) || is.character(pch)) || (length(pch) != 1 && length(pch) != ngrps)) {\n # if (!is.atomic(pch) || !is.vector(pch) || !is.numeric(pch) || (length(pch) != 1 && length(pch) != ngrps)) {\n stop(sprintf(\"`pch` must be `NULL`, or a numeric or character vector of length 1 or %s.\", ngrps), call. = FALSE)\n }\n\n if (length(pch) == 1) {\n pch = rep(pch, ngrps)\n }\n }\n\n return(pch)\n}\n\n\nby_lty = function(ngrps, type, lty = NULL) {\n # We only care about line types, otherwise return NULL\n if (!type %in% c(\"l\", \"b\", \"o\", \"c\", \"h\", \"s\", \"S\", \"ribbon\", \"barplot\", \"boxplot\", \"rect\", \"segments\", \"qq\", \"abline\", \"hline\", \"vline\")) {\n out = NULL\n\n # special \"by\" convenience keyword\n } else if (!is.null(lty) && length(lty) == 1 && lty == \"by\") {\n lty_dict = c(\"solid\", \"dashed\", \"dotted\", \"dotdash\", \"longdash\", \"twodash\")\n par_lty = par(\"lty\")\n\n if (!par_lty %in% lty_dict) {\n warning(\n \"\\nBesoke lty specifications (i.e., using string combinations) are not\",\n \"currently supported alongside the lty='by' keyword argument.\",\n \"Defaulting to 1 and looping from there.\\n\"\n )\n par_lty = 1\n } else {\n par_lty = which(par_lty == lty_dict)\n }\n out = 1:ngrps + par_lty - 1\n # correctly recycle if over max pch type\n lty_ceiling = 6 # see ?pch\n if (max(out) > lty_ceiling) {\n lty_below = out[out <= lty_ceiling]\n lty_above = out[out > lty_ceiling]\n lty_above = rep_len(1:lty_ceiling, length(lty_above))\n out = c(lty_below, lty_above)\n }\n\n # NULL -> solid (or default) line\n } else if (is.null(lty)) {\n if (identical(type, \"boxplot\")) {\n out = NULL\n } else {\n out = rep(par(\"lty\"), ngrps)\n }\n\n # atomic vector: sanity check length\n } else if (is.atomic(lty) && is.vector(lty)) {\n if (length(lty) == 1) {\n out = rep(lty, ngrps)\n } else {\n if (length(lty) != ngrps) {\n stop(sprintf(\"`lty` must be `NULL` or a numeric vector of length 1 or %s.\", ngrps), call. = FALSE)\n }\n out = lty\n }\n }\n\n return(out)\n}\n\n\nby_lwd = function(ngrps, type, lwd = NULL) {\n lwd_base = par(\"lwd\")\n lwd_floor = lwd_base / min(5, max((ngrps - 1), 1))\n lwd_ceiling = lwd_base * min(5, ngrps)\n\n no_lwd = FALSE\n # special \"by\" convenience keyword\n if (!is.null(lwd) && length(lwd) == 1 && lwd == \"by\") {\n no_lwd = TRUE # skip checks below\n lwd = seq(lwd_floor, lwd_ceiling, length.out = ngrps)\n } else if (is.null(lwd)) {\n no_lwd = TRUE\n lwd = NULL\n }\n\n if (!no_lwd) {\n if (!is.atomic(lwd) || !is.vector(lwd) || !is.numeric(lwd) || (length(lwd) != 1 && length(lwd) != ngrps)) {\n stop(sprintf(\"`lwd` must be `NULL` or a numeric vector of length 1 or %s.\", ngrps), call. = FALSE)\n }\n if (length(lwd) == 1) {\n lwd = rep(lwd, ngrps)\n }\n }\n\n return(lwd)\n}\n\n\nby_bg = function(\n adjustcolor,\n alpha,\n bg,\n by,\n by_continuous,\n by_ordered,\n col,\n fill,\n ngrps,\n palette,\n ribbon.alpha,\n type) {\n if (is.null(bg) && !is.null(fill)) bg = fill\n if (!is.null(bg) && length(bg) == 1 && is.numeric(bg) && bg >= 0 && bg <= 1) {\n alpha = bg\n bg = \"by\"\n }\n if (!is.null(bg) && length(bg) == 1 && bg == \"by\") {\n bg = by_col(\n ngrps = ngrps,\n col = NULL,\n palette = palette,\n gradient = by_continuous,\n ordered = by_ordered,\n alpha = alpha\n )\n } else if (length(bg) != ngrps) {\n bg = rep(bg, ngrps)\n }\n if (type == \"ribbon\" || (type == \"boxplot\" && !is.null(by))) {\n if (!is.null(bg)) {\n bg = adjustcolor(bg, ribbon.alpha)\n } else if (!is.null(col)) {\n bg = adjustcolor(col, ribbon.alpha)\n }\n }\n\n return(bg)\n}\n"], ["/tinyplot/R/sanitize.R", "sanitize_ribbon.alpha = function(ribbon.alpha) {\n assert_numeric(ribbon.alpha, len = 1, lower = 0, upper = 1, null.ok = TRUE)\n if (is.null(ribbon.alpha)) ribbon.alpha = .tpar[[\"ribbon.alpha\"]]\n return(ribbon.alpha)\n}\n\n\n\nsanitize_type = function(type, x, y, dots) {\n if (inherits(type, \"tinyplot_type\")) {\n return(type)\n }\n\n known_types = c(\n \"p\", \"l\", \"o\", \"b\", \"c\", \"h\", \"j\", \"s\", \"S\", \"n\", \n \"abline\",\n \"area\",\n \"bar\", \"barplot\",\n \"box\", \"boxplot\",\n \"density\",\n \"errorbar\",\n \"function\",\n \"glm\",\n \"hist\", \"histogram\",\n \"hline\",\n \"j\", \"jitter\",\n \"lines\",\n \"lm\",\n \"loess\",\n \"pointrange\",\n \"points\",\n \"polygon\", \"polypath\",\n \"qq\",\n \"rect\",\n \"ribbon\",\n \"ridge\",\n \"rug\",\n \"segments\",\n \"spine\", \"spineplot\",\n \"spline\",\n \"summary\",\n \"text\",\n \"violin\",\n \"vline\"\n )\n assert_choice(type, known_types, null.ok = TRUE)\n\n if (is.null(type)) {\n if (!is.null(x) && (is.factor(x) || is.character(x)) && !(is.factor(y) || is.character(y))) {\n # enforce boxplot type for y ~ factor(x)\n type = type_boxplot\n } else if (is.factor(y) || is.character(y)) {\n # enforce spineplot type for factor(y) ~ x\n type = type_spineplot\n } else {\n type = \"p\"\n }\n }\n\n if (is.character(type)) type = switch(type,\n \"abline\" = type_abline,\n \"area\" = type_area,\n \"bar\" = type_barplot,\n \"barplot\" = type_barplot,\n \"box\" = type_boxplot,\n \"boxplot\" = type_boxplot,\n \"density\" = type_density,\n \"errorbar\" = type_errorbar,\n \"function\" = type_function,\n \"glm\" = type_glm,\n \"hist\" = type_histogram,\n \"histogram\" = type_histogram,\n \"hline\" = type_hline,\n \"j\" = type_jitter,\n \"jitter\" = type_jitter,\n \"lines\" = type_lines,\n \"lm\" = type_lm,\n \"loess\" = type_loess,\n \"p\" = type_points,\n \"pointrange\" = type_pointrange,\n \"points\" = type_points,\n \"polygon\" = type_polygon,\n \"polypath\" = type_polypath,\n \"qq\" = type_qq,\n \"rect\" = type_rect,\n \"ribbon\" = type_ribbon,\n \"ridge\" = type_ridge,\n \"rug\" = type_rug,\n \"segments\" = type_segments,\n \"spine\" = type_spineplot,\n \"spineplot\" = type_spineplot,\n \"spline\" = type_spline,\n \"summary\" = type_summary,\n \"text\" = type_text,\n \"violin\" = type_violin,\n \"vline\" = type_vline,\n type # default case\n )\n \n if (is.function(type)) {\n args = intersect(names(formals(type)), names(dots))\n args = if (length(args) >= 1L) dots[args] else list()\n type = do.call(type, args)\n type$dots = dots[setdiff(names(dots), names(args))]\n }\n \n if (inherits(type, \"tinyplot_type\")) return(type)\n\n out = list(draw = NULL, data = NULL, name = type)\n return(out)\n}\n"], ["/tinyplot/R/type_polypath.R", "#' Polypath polygon type\n#' \n#' @description Type function for plotting polygons.\n#' Arguments are passed to \\code{\\link[graphics]{polypath}}.\n#' \n#' @inheritParams graphics::polypath\n#' \n#' @examples\n#' # \"polypath\" type convenience character string\n#' tinyplot(\n#' c(.1, .1, .6, .6, NA, .4, .4, .9, .9),\n#' c(.1, .6, .6, .1, NA, .4, .9, .9, .4),\n#' type = \"polypath\", fill = \"grey\"\n#' )\n#' \n#' # Use `type_polypath()` to pass extra arguments for customization\n#' tinyplot(\n#' c(.1, .1, .6, .6, NA, .4, .4, .9, .9),\n#' c(.1, .6, .6, .1, NA, .4, .9, .9, .4),\n#' type = type_polypath(rule = \"evenodd\"), fill = \"grey\"\n#' )\n#' @export\ntype_polypath = function(rule = \"winding\") {\n draw_polypath = function() {\n fun = function(ix, iy, icol, ibg, ilty, ilwd, dots, ...) {\n polypath(\n x = ix,\n y = iy,\n border = icol,\n col = ibg,\n lty = ilty,\n lwd = ilwd,\n rule = rule\n )\n }\n return(fun)\n }\n\n out = list(\n draw = draw_polypath(),\n data = NULL,\n name = \"polypath\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n"], ["/tinyplot/R/type_vline.R", "#' @param v x-value(s) for vertical line(s). Numeric of length 1, or equal to\n#' the number of groups or number of facets (or the product thereof).\n#' @rdname type_abline\n#' @export\ntype_vline = function(v = 0) {\n assert_numeric(v)\n data_vline = function(datapoints, lwd, lty, col, ...) {\n if (nrow(datapoints) == 0) {\n msg = \"`type_vline() only works on existing plots with x and y data points.\"\n stop(msg, call. = FALSE)\n }\n # keep track of unique lty and lwd (needed for group catch / escape hatch\n # later in draw_hline)\n ul_lwd = length(unique(lwd))\n ul_lty = length(unique(lty))\n ul_col = length(unique(col))\n return(list(type_info = list(ul_lty = ul_lty, ul_lwd = ul_lwd, ul_col = ul_col)))\n }\n draw_vline = function() {\n fun = function(\n ifacet, iby, data_facet, icol, ilty, ilwd,\n ngrps, nfacets, by_continuous, facet_by,\n type_info,\n ...\n ) {\n\n # flag for aesthetics by groups\n grp_aes = type_info[[\"ul_col\"]] == 1 || type_info[[\"ul_lty\"]] == ngrps || type_info[[\"ul_lwd\"]] == ngrps\n \n if (length(v) != 1) {\n if (!length(v) %in% c(ngrps, nfacets, ngrps*nfacets)) {\n msg = \"Length of 'v' must be 1, or equal to the number of facets or number of groups (or product thereof).\"\n stop(msg, call. = FALSE)\n }\n if (!facet_by && length(v) == nfacets) {\n v = v[ifacet]\n if (!grp_aes && type_info[[\"ul_col\"]]!=ngrps) {\n icol = 1\n } else if (by_continuous) {\n icol = 1\n }\n } else if (!by_continuous && length(v) == ngrps * nfacets) {\n v = v[ifacet * ngrps - c(ngrps - iby)]\n } else if (!by_continuous) {\n v = v[iby]\n }\n } else if (!grp_aes) {\n icol = 1\n }\n \n abline(v = v, col = icol, lty = ilty, lwd = ilwd)\n }\n return(fun)\n }\n out = list(\n draw = draw_vline(),\n data = data_vline,\n name = \"vline\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_hline.R", "#' @rdname type_abline\n#' @param h y-value(s) for horizontal line(s). Numeric of length 1, or equal to\n#' the number of groups or number of facets (or the product thereof).\n#' @export\ntype_hline = function(h = 0) {\n assert_numeric(h)\n data_hline = function(datapoints, lwd, lty, col, ...) {\n if (nrow(datapoints) == 0) {\n msg = \"`type_hline() only works on existing plots with x and y data points.\"\n stop(msg, call. = FALSE)\n }\n # keep track of unique lty and lwd (needed for group catch / escape hatch\n # later in draw_hline)\n ul_lwd = length(unique(lwd))\n ul_lty = length(unique(lty))\n ul_col = length(unique(col))\n return(list(type_info = list(ul_lty = ul_lty, ul_lwd = ul_lwd, ul_col = ul_col)))\n }\n draw_hline = function() {\n fun = function(\n ifacet, iby, data_facet, icol, ilty, ilwd,\n ngrps, nfacets, by_continuous, facet_by,\n type_info,\n ...\n ) {\n \n # flag for aesthetics by groups\n grp_aes = type_info[[\"ul_col\"]] == 1 || type_info[[\"ul_lty\"]] == ngrps || type_info[[\"ul_lwd\"]] == ngrps\n \n if (length(h) != 1) {\n if (!length(h) %in% c(ngrps, nfacets, ngrps*nfacets)) {\n msg = \"Length of 'h' must be 1, or equal to the number of facets or number of groups (or product thereof).\"\n stop(msg, call. = FALSE)\n }\n if (!facet_by && length(h) == nfacets) {\n h = h[ifacet]\n if (!grp_aes && type_info[[\"ul_col\"]]!=ngrps) {\n icol = 1\n } else if (by_continuous) {\n icol = 1\n }\n } else if (!by_continuous && length(h) == ngrps * nfacets) {\n h = h[ifacet * ngrps - c(ngrps - iby)]\n } else if (!by_continuous) {\n h = h[iby]\n }\n } else if (!grp_aes) {\n icol = 1\n }\n\n abline(h = h, col = icol, lty = ilty, lwd = ilwd)\n }\n return(fun)\n }\n out = list(\n draw = draw_hline(),\n data = data_hline,\n name = \"hline\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_pointrange.R", "#' @rdname type_errorbar\n#' @export\ntype_pointrange = function() {\n out = list(\n draw = draw_pointrange(),\n data = data_pointrange(),\n name = \"p\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\n\ndraw_pointrange = function() {\n fun = function(ix, iy, ixmin, iymin, ixmax, iymax, icol, ibg, ipch, ilwd, cex, ...) {\n segments(\n x0 = ixmin,\n y0 = iymin,\n x1 = ixmax,\n y1 = iymax,\n col = icol,\n lwd = ilwd\n )\n draw_points()(ix = ix, iy = iy, icol = icol, ibg = ibg, ipch = ipch, ilwd = ilwd, cex = cex)\n }\n return(fun)\n}\n\n\ndata_pointrange = function() {\n fun = function(datapoints, xlabs, ...) {\n if (is.character(datapoints$x)) datapoints$x = as.factor(datapoints$x)\n if (is.factor(datapoints$x)) {\n ## original data (i.e., no new sorting by factor)\n xlvls = unique(datapoints$x)\n datapoints$x = factor(datapoints$x, levels = xlvls)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n datapoints$x = as.integer(datapoints$x)\n }\n datapoints$xmin = datapoints$x\n datapoints$xmax = datapoints$x\n out = list(\n x = datapoints$x,\n xlabs = xlabs,\n datapoints = datapoints)\n\n return(out)\n }\n return(fun)\n}\n"], ["/tinyplot/R/tinylabel.R", "#' Format labels\n#' \n#' @description Function for formatting label appearance, e.g. axis\n#' ticks labels. This is what the top-level `xaxl` and `yaxl` arguments\n#' from [`tinyplot`] ultimately get passed to.\n#' @param x a numeric or character vector\n#' @param labeller a formatting function to be applied to `x`, e.g. [`format`],\n#' [`toupper`], [`abs`], or other custom function (including from the popular\n#' **scales** package). Can also be one of the following convenience strings\n#' (symbols), for which common formatting transformations are provided:\n#' `\"percent\"` (`\"%\"`), `\"comma\"` (`\",\"`), `\"log\"` (`\"l\"`), `\"dollar\"`\n#' (`\"$\"`), `\"euro\"` (`\"€\"`), or `\"sterling\"` (`\"£\"`).\n#' @examples\n#' x = 1e4\n#' tinylabel(x, \"comma\")\n#' tinylabel(x, \",\") # same\n#' tinylabel(x, \"$\") # or \"dollar\"\n#' \n#' # pass to xaxl/yaxl for adjusting axes tick labels in a tinyplot call\n#' tinyplot(I(mpg/hp) ~ hp, data = mtcars, yaxl = \"%\")\n#' \n#' # log example (combined with axis scaling)\n#' tinyplot(x = 10^c(10:0), y = 0:10, type = \"b\", log = \"x\", xaxl = \"log\")\n#' \n#' # combine with `x/yaxb` to adjust the actual tick marks (\"break points\")\n#' # at the same time\n#' tinyplot(x = 10^c(10:0), y = 0:10, type = \"b\", log = \"x\", xaxl = \"log\",\n#' xaxb = 10^c(1,3,5,7,9))\n#' \n#' #\n#' ## custom function examples\n#' \n#' ## example I: date formatting\n#' \n#' dat = data.frame(\n#' date = seq(as.Date(\"2000/1/1\"), by = \"month\", length.out = 12),\n#' trend = 1:12 + rnorm(12, sd = 1)\n#' )\n#' \n#' tinyplot(trend ~ date, data = dat, xaxl = function(x) format(x, \"%b, %Y\"))\n#' \n#' ## example II: string wrapping \n#' \n#' # create a \"vectorised\" version of `base::strwrap` that breaks long\n#' # strings into new lines every 18 characters\n#' strwrap18 = function(x) sapply(\n#' strwrap(x, width = 18, simplify = FALSE),\n#' paste,\n#' collapse = \"\\n\"\n#' )\n#' \n#' # now demonstrate on a dataset with long y-tick labels\n#' dat2 = data.frame(\n#' x = rep(rnorm(100), 3),\n#' y = c(\n#' \"tinyplot is a lightweight extension of the base R graphics system.\",\n#' \"R is a language for statistical computing.\",\n#' \"Data visualization is an essential skill.\"\n#' )\n#' )\n#' \n#' tinytheme(\"bw\")\n#' tinyplot(y ~ x, data = dat2, type = \"j\", yaxl = strwrap18)\n#' tinytheme()\n#' @export\ntinylabel = function(x, labeller = NULL) {\n if (is.null(labeller)) return(x)\n if (is.character(labeller)) labeller = labeller_fun((labeller))\n return(labeller(x))\n}\n\n\nlabeller_fun = function(label = \"percent\") {\n \n labels = c(\n \"%\" = \"percent\",\n \",\" = \"comma\",\n \"$\" = \"dollar\",\n \"\\u20ac\" = \"euro\",\n \"\\u00a3\" = \"sterling\",\n \"l\" = \"log\"\n )\n if (label %in% names(labels)) label = labels[label]\n \n ## all labels plus absolute value version\n # labels = c(\"percent\", \"comma\", \"dollar\", \"euro\", \"sterling\")\n labels = c(labels, paste0(\"abs_\", labels))\n\n ## match full label first, then store abs_ info separately\n label = match.arg(label, labels)\n abs_ = substr(label, 1L, 4L) == \"abs_\"\n if (abs_) label = substr(label, 5L, nchar(label))\n\n ## actual formatting function\n format_percent = function(x) {\n sprintf(\"%.0f%%\", x * 100)\n }\n \n format_comma = function(x) {\n prettyNum(x, big.mark = \",\", scientific = FALSE)\n }\n \n format_dollar = function(x) {\n paste0(\"$\", prettyNum(x, big.mark = \",\", scientific = FALSE))\n }\n \n format_euro = function(x) {\n paste0(\"\\u20ac\", prettyNum(x, big.mark = \",\", scientific = FALSE))\n }\n \n format_sterling = function(x) {\n paste0(\"\\u00a3\", prettyNum(x, big.mark = \",\", scientific = FALSE))\n }\n \n format_log = function(x) {\n parse(text = paste0(10, \"^\", format(log10(x), digits = 3)))\n }\n \n fun = switch(\n label,\n percent = format_percent,\n comma = format_comma,\n dollar = format_dollar,\n euro = format_euro,\n sterling = format_sterling,\n log = format_log\n )\n\n ## combine with absolute value if necessary\n if (abs_) function(x) fun(abs(x)) else fun\n}\n"], ["/tinyplot/R/type_polygon.R", "#' Polygon plot type\n#'\n#' @description Type function for plotting polygons.\n#' Arguments are passed to \\code{\\link[graphics]{polygon}}.\n#' \n#' @inheritParams graphics::polygon\n#' \n#' @examples\n#' # \"polygon\" type convenience character string\n#' tinyplot(1:9, c(2,1,2,1,NA,2,1,2,1), type = \"polygon\")\n#' \n#' # Use `type_polygon()` to pass extra arguments for customization\n#' tinyplot(1:9, c(2,1,2,1,NA,2,1,2,1), type = type_polygon(density = c(10, 20)))\n#' \n#' @export\ntype_polygon = function(density = NULL, angle = 45) {\n out = list(\n draw = draw_polygon(density = density, angle = angle),\n data = NULL,\n name = \"polygon\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_polygon = function(density = density, angle = 45) {\n fun = function(ix, iy, icol, ibg, ilty = par(\"lty\"), ilwd = par(\"lwd\"), ...) {\n polygon(\n x = ix,\n y = iy,\n border = icol,\n col = ibg,\n lty = ilty,\n lwd = ilwd,\n density = density,\n angle = angle\n )\n }\n return(fun)\n}\n"], ["/tinyplot/R/get_saved_par.R", "#' @title Retrieve the saved graphical parameters\n#' \n#' @description Convenience function for retrieving the graphical parameters\n#' (i.e., the full list of `tag = value` pairs held in\n#' \\code{\\link[graphics]{par}}) from either immediately before or\n#' immediately after the most recent [tinyplot] call.\n#'\n#' @param when character. From when should the saved parameters be retrieved?\n#' Either \"before\" (the default) or \"after\" the preceding `tinyplot` call.\n#' \n#' @details A potential side-effect of [tinyplot] is that it can change a user's\n#' \\code{\\link[graphics]{par}} settings. For example, it may adjust the inner\n#' and outer plot margins to make space for an automatic legend; see\n#' [draw_legend]. While it is possible to immediately restore the original\n#' \\code{\\link[graphics]{par}} settings upon exit via the\n#' `tinyplot(..., restore.par = TRUE)` argument, this is not the default\n#' behaviour. The reason being that we need to preserve the adjusted parameter\n#' settings in case users want to add further graphical annotations to their\n#' plot (e.g., \\code{\\link[graphics]{abline}}, \\code{\\link[graphics]{text}},\n#' etc.) Nevertheless, it may still prove desirable to recall and reset these\n#' original graphical parameters after the fact (e.g., once all these extra\n#' annotations have been added). That is the purpose of this [get_saved_par]\n#' function.\n#' \n#' Of course, users may prefer to manually capture and reset graphical\n#' parameters, as per the standard method described in the\n#' \\code{\\link[graphics]{par}} documentation. For example:\n#' \n#' ```\n#' op = par(no.readonly = TRUE) # save current par settings \n#' # \n#' par(op) # reset original pars\n#' ```\n#' \n#' This standard manual approach may be safer than [get_saved_par] because it\n#' offers more precise control. Specifically, the value of [get_saved_par] \n#' itself will be reset after ever new [tinyplot] call; i.e. it may inherit an\n#' already-changed set of parameters. Users should bear these trade-offs in\n#' mind when deciding which approach to use. As a general rule,\n#' [get_saved_par] offers the convenience of resetting the original\n#' \\code{\\link[graphics]{par}} settings even if a user forgot to save them\n#' beforehand. But one should avoid invoking it after a series of consecutive\n#' [tinyplot] calls.\n#' \n#' Finally, note that users can always call \\code{\\link[grDevices]{dev.off}}\n#' to reset all \\code{\\link[graphics]{par}} settings to their defaults.\n#' \n#' @returns A list of \\code{\\link[graphics]{par}} settings.\n#' \n#' @examples\n#' #\n#' # Contrived example where we draw a grouped scatterplot with a legend and\n#' # manually add corresponding best fit lines for each group...\n#' #\n#' \n#' # First draw the grouped scatterplot\n#' tinyplot(Sepal.Length ~ Petal.Length | Species, iris)\n#' \n#' # Preserving adjusted par settings is good for adding elements to our plot\n#' for (s in levels(iris$Species)) {\n#' abline(\n#' lm(Sepal.Length ~ Petal.Length, iris, subset = Species==s),\n#' col = which(levels(iris$Species)==s)\n#' )\n#' }\n#' \n#' # Get saved par from before the preceding tinyplot call (but don't use yet)\n#' sp = get_saved_par(\"before\")\n#' \n#' # Note the changed margins will affect regular plots too, which is probably\n#' # not desirable\n#' plot(1:10)\n#' \n#' # Reset the original parameters (could use `par(sp)` here)\n#' tpar(sp)\n#' # Redraw our simple plot with our corrected right margin\n#' plot(1:10)\n#' \n#' #\n#' # Quick example going the other way, \"correcting\" for par.restore = TRUE...\n#' #\n#' \n#' tinyplot(Sepal.Length ~ Petal.Length | Species, iris, restore.par = TRUE)\n#' # Our added best lines will be wrong b/c of misaligned par\n#' for (s in levels(iris$Species)) {\n#' abline(\n#' lm(Sepal.Length ~ Petal.Length, iris, subset = Species==s),\n#' col = which(levels(iris$Species)==s), lty = 2\n#' )\n#' }\n#' # grab the par settings from the _end_ of the preceding tinyplot call to fix\n#' tpar(get_saved_par(\"after\"))\n#' # now the best lines are correct\n#' for (s in levels(iris$Species)) {\n#' abline(\n#' lm(Sepal.Length ~ Petal.Length, iris, subset = Species==s),\n#' col = which(levels(iris$Species)==s)\n#' )\n#' }\n#' \n#' # reset again to original saved par settings before exit\n#' tpar(sp)\n#'\n#' @export\nget_saved_par = function(when = c(\"before\", \"after\", \"first\")) {\n when = match.arg(when)\n par_env_name = paste0(\".saved_par_\", when)\n return(get(par_env_name, envir = get(\".tinyplot_env\", envir = parent.env(environment()))))\n}\n\n# (non-exported) companion function(s) for setting the original pars\nset_saved_par = function(when = c(\"before\", \"after\", \"first\"), value) {\n when = match.arg(when)\n par_env_name = paste0(\".saved_par_\", when)\n assign(par_env_name, value, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n}\n"], ["/tinyplot/R/tinytheme.R", "#' Set or Reset Plot Themes for `tinyplot`\n#'\n#' @md\n#' @description\n#' The `tinytheme` function sets or resets the theme for plots created with\n#' `tinyplot`. Themes control the appearance of plots, such as text alignment,\n#' font styles, axis labels, and even dynamic margin adjustment to reduce\n#' whitespace.\n#'\n#' @param theme A character string specifying the name of the theme to apply.\n#' Themes are arranged in an approximate hierarchy, adding or subtracting\n#' elements in the order presented below. Note that several themes are\n#' _dynamic_, in the sense that they attempt to reduce whitespace in a way\n#' that is responsive to the length of axes labels, tick marks, etc. These\n#' dynamic plots are marked with an asterisk (*) below.\n#' \n#' - `\"default\"`: inherits the user's default base graphics settings.\n#' - `\"basic\"`: light modification of `\"default\"`, only adding filled points, a panel background grid, and light gray background to facet titles.\n#' - `\"clean\"` (*): builds on `\"basic\"` by moving the subtitle above the plotting area, adding horizontal axis labels, employing tighter default plot margins and title gaps to reduce whitespace, and setting different default palettes (\"Tableau 10\" for discrete colors and \"agSunset\" for gradient colors). The first of our dynamic themes and the foundation for several derivative themes that follow below.\n#' - `\"clean2\"` (*): removes the plot frame (box) from `\"clean\"`.\n#' - `\"classic\"` (*): connects the axes in a L-shape, but removes the other top and right-hand edges of the plot frame (box). Also sets the \"Okabe-Ito\" palette as a default for discrete colors. Inspired by the **ggplot2** theme of the same name. \n#' - `\"bw\"` (*): similar to `\"clean\"`, except uses thinner lines for the plot frame (box), solid grid lines, and sets the \"Okabe-Ito\" palette as a default for discrete colors. Inspired by the **ggplot2** theme of the same name. \n#' - `\"minimal\"` (*): removes the plot frame (box) from `\"bw\"`, as well as the background for facet titles. Inspired by the **ggplot2** theme of the same name. \n#' - `\"ipsum\"` (*): similar to `\"minimal\"`, except subtitle is italicised and axes titles are aligned to the far edges. Inspired by the **hrbrthemes** theme of the same name for **ggplot2**. \n#' - `\"dark\"` (*): similar to `\"minimal\"`, but set against a dark background with foreground and a palette colours lightened for appropriate contrast.\n#' - `\"ridge\"` (*): a specialized theme for ridge plots (see [`type_ridge()`]). Builds off of `\"clean\"`, but adds ridge-specific tweaks (e.g. default \"Zissou 1\" palette for discrete colors, solid horizontal grid lines, and minor adjustments to y-axis labels). Not recommended for non-ridge plots.\n#' - `\"ridge2\"` (*): removes the plot frame (box) from `\"ridge\"`, but retains the x-axis line. Again, not recommended for non-ridge plots.\n#' - `\"tufte\"`: floating axes and minimalist plot artifacts in the style of Edward Tufte.\n#' - `\"void\"`: switches off all axes, titles, legends, etc.\n#' @param ... Named arguments to override specific theme settings. These\n#' arguments are passed to `tpar()` and take precedence over the predefined\n#' settings in the selected theme.\n#'\n#' @details\n#' Sets a list of graphical parameters using `tpar()`\n#'\n#' To reset the theme to default settings (no customization), call `tinytheme()`\n#' without arguments.\n#' \n#' **Caveat emptor:** Themes are a somewhat experimental feature of `tinyplot`.\n#' While we feel confident that themes should work as expected for most\n#' \"standard\" cases, there may be some sharp edges. Please report any unexpected\n#' behaviour to our GitHub repo:\n#' \n#' \n#' Known current limitations include:\n#' \n#' - Themes do not work well when `legend = \"top!\"`.\n#' - Dynamic margin spacing does not account for multi-line strings (e.g., axes\n#' or main titles that contain \"\\\\n\").\n#'\n#' @return The function returns nothing. It is called for its side effects.\n#' \n#' @seealso [`tpar`] which does the heavy lifting under the hood.\n#'\n#' @examples\n#' # Reusable plot function\n#' p = function() tinyplot(\n#' lat ~ long | depth, data = quakes,\n#' main = \"Earthquakes off Fiji\",\n#' sub = \"Data courtesy of the Harvard PRIM-H project\"\n#' )\n#' p()\n#' \n#' # Set a theme\n#' tinytheme(\"bw\")\n#' p()\n#'\n#' # Try a different theme\n#' tinytheme(\"dark\")\n#' p()\n#' \n#' # Customize the theme by overriding default settings\n#' tinytheme(\"bw\", fg = \"green\", font.main = 2, font.sub = 3, family = \"Palatino\")\n#' p()\n#' \n#' # Another custom theme example\n#' tinytheme(\"bw\", font.main = 2, col.axis = \"darkcyan\", family = \"HersheyScript\")\n#' p()\n#' \n#' # Aside: One or two specialized themes are only meant for certain plot types\n#' tinytheme(\"ridge2\")\n#' tinyplot(I(cut(lat, 10)) ~ depth, data = quakes, type = \"ridge\")\n#'\n#' # Reset the theme\n#' tinytheme()\n#' p()\n#' \n#' # Themes showcase\n#' ## We'll use a slightly more intricate plot (long y-axis labs and facets)\n#' ## to demonstrate dynamic margin adjustment etc.\n#' \n#' thms = eval(formals(tinytheme)$theme)\n#' \n#' for (thm in thms) {\n#' tinytheme(thm)\n#' tinyplot(\n#' I(Sepal.Length*1e4) ~ Petal.Length | Species, facet = \"by\", data = iris,\n#' main = \"Demonstration of tinyplot themes\",\n#' sub = paste0('tinytheme(\"', thm, '\")')\n#' )\n#' }\n#' \n#' # Reset\n#' tinytheme()\n#'\n#' @export\ntinytheme = function(\n theme = c(\n \"default\", \"basic\",\n \"clean\", \"clean2\", \"bw\", \"classic\",\n \"minimal\", \"ipsum\", \"dark\",\n \"ridge\", \"ridge2\",\n \"tufte\", \"void\"\n ),\n ...\n ) {\n \n theme = match.arg(theme)\n\n # in notebooks, we don't want to close the device because no image.\n # init_tpar() tries to be smart, but may fail.\n init_tpar(rm_hook = TRUE)\n\n assert_choice(\n theme,\n c(\n \"default\",\n sort(c(\"basic\", \"bw\", \"classic\", \"clean\", \"clean2\", \"dark\", \"ipsum\",\n \"minimal\", \"ridge\", \"ridge2\", \"tufte\", \"void\"))\n )\n )\n\n settings = switch(theme,\n \"default\" = theme_default,\n \"basic\" = theme_basic,\n \"bw\" = theme_bw,\n \"classic\" = theme_classic,\n \"clean\" = theme_clean,\n \"clean2\" = theme_clean2,\n \"dark\" = theme_dark,\n \"ipsum\" = theme_ipsum,\n \"minimal\" = theme_minimal,\n \"ridge\" = theme_ridge,\n \"ridge2\" = theme_ridge2,\n \"tufte\" = theme_tufte,\n \"void\" = theme_void,\n )\n\n dots = list(...)\n for (n in names(dots)) {\n settings[[n]] = dots[[n]]\n }\n\n if (length(settings) > 0) {\n if (theme == \"default\") {\n # for default theme, we want to revert the original pars and turn off the\n # before.new.plot hook (otherwise manual par(x = y) changes won't work) \n tpar(settings, hook = FALSE)\n old_hooks = get_environment_variable(\".tpar_hooks\")\n remove_hooks(old_hooks)\n } else {\n tpar(settings, hook = TRUE)\n }\n }\n\n return(invisible(NULL))\n}\n\n\n\n#\n## Themes (these are read and set at initial load time)\n\n# theme_default = list()\n\ntheme_default = list(\n tinytheme = \"default\",\n adj = par(\"adj\"), # 0.5,\n adj.main = par(\"adj\"), # 0.5,\n adj.sub = par(\"adj\"), # 0.5,\n bg = \"white\", # par(\"bg\") # \"white\"\n bty = par(\"bty\"), #\"o\",\n cex.axis = par(\"cex.axis\"), #1,\n cex.main = par(\"cex.main\"), #1.2,\n cex.xlab = par(\"cex.axis\"), #1,\n cex.ylab = par(\"cex.axis\"), #1,\n col.axis = par(\"col.axis\"), #1,\n col.xaxs = par(\"col.axis\"), #1,\n col.yaxs = par(\"col.axis\"), #1,\n col.lab = par(\"col.lab\"), #\"black\",\n col.main = par(\"col.main\"), #\"black\",\n col.sub = par(\"col.sub\"), #\"black\",\n dynmar = FALSE,\n facet.bg = NULL,\n facet.border = NA,\n family = par(\"family\"), # \"\"\n fg = par(\"fg\"),\n font = par(\"font\"), # 1,\n font.axis = par(\"font.axis\"), # 1,\n font.lab = par(\"font.lab\"), # 1,\n font.main = par(\"font.main\"), # 2,\n font.sub = par(\"font.sub\"), # 2,\n grid = FALSE,\n grid.col = \"lightgray\",\n grid.lty = \"dotted\",\n grid.lwd = 1,\n lab = par(\"lab\"), # c(5, 5, 7),\n las = par(\"las\"), # 0,\n lwd = par(\"lwd\"), # 1,\n lwd.axis = par(\"lwd\"), # 1,\n mar = c(5.1, 4.1, 4.1, 2.1), ## test\n mgp = par(\"mgp\"),\n # palette.qualitative = \"R4\",\n # palette.sequential = \"Viridis\",\n pch = par(\"pch\"), # 1,\n side.sub = 1,\n tck = NA,\n xaxt = \"standard\",\n yaxt = \"standard\"\n)\n\n# derivatives of \"default\" \n# - basic\n# - tufte\n# - void\n\ntheme_basic = modifyList(theme_default, list(\n tinytheme = \"basic\",\n facet.bg = \"gray90\",\n facet.border = \"black\",\n grid = TRUE,\n pch = 16\n))\n\ntheme_tufte = modifyList(theme_default, list(\n tinytheme = \"tufte\",\n adj.main = 0,\n adj.sub = 0,\n bty = \"n\",\n font.main = 1,\n lab = c(10, 10, 7),\n # palette.sequential = \"Grays\",\n pch = 16,\n side.sub = 3,\n tcl = 0.2\n))\n\ntheme_void = modifyList(theme_default, list(\n tinytheme = \"void\",\n adj.main = 0,\n adj.sub = 0,\n font.main = 1,\n palette.qualitative = \"Tableau 10\",\n palette.sequential = \"ag_Sunset\",\n pch = 16,\n side.sub = 3,\n # tck = -.02,\n xaxt = \"none\",\n yaxt = \"none\"\n))\n\n# derivatives of \"basic\" \n# - clean\n\ntheme_clean = modifyList(theme_basic, list(\n ## Notes:\n ## - 1. Reduce axis title gap by 0.5 lines and also reduce tcl to 0.3 lines.\n ## - 2. Sub moves to top.\n ## - 3. Also want to remove excess white on rhs of plot margin (when no legend).\n ## - Together, 1, 2, and 3 imply that...\n ## -- mgp[1] should be adjusted by 0.8 (= 0.5 + 0.3)\n ## -- mgp[2] should be adjusted by 0.3\n ## -- mar[1] should be adjusted by 1.8 (= 1 (no sub) + 0.5 + 0.3 (tighter axis labs))\n ## -- mar[2] should be adjusted by 0.8 (= 0.5 + 0.3)\n ## -- mar[3] should remain unchanged (main + sub will adjust automatically)\n ## -- mar[4] should be adjusted by 1.5 (relative to 2.1)\n ##\n tinytheme = \"clean\",\n adj.main = 0,\n adj.sub = 0,\n dynmar = TRUE,\n las = 1,\n mar = c(5.1, 4.1, 4.1, 2.1) - c(1+0.5+0.3, 0.5+0.3, 0, 1.5), ## test\n mgp = c(3, 1, 0) - c(0.5+0.3, 0.3, 0), # i.e., subtract 0.5 lines + the (abs) value of the tcl adjustment\n palette.qualitative = \"Tableau 10\",\n palette.sequential = \"ag_Sunset\",\n side.sub = 3,\n tcl = -0.3\n))\n\n# derivatives of \"clean\" \n# - clean2\n# - classic\n# - bw\n\ntheme_clean2 = modifyList(theme_clean, list(\n tinytheme = \"clean2\",\n facet.border = \"gray90\",\n xaxt = \"labels\",\n yaxt = \"labels\"\n))\n\ntheme_classic = modifyList(theme_clean, list(\n tinytheme = \"classic\",\n bty = \"l\",\n facet.bg = NULL,\n font.main = 1,\n grid = FALSE,\n palette.qualitative = \"Okabe-Ito\"\n))\n\ntheme_bw = modifyList(theme_clean, list(\n tinytheme = \"bw\",\n font.main = 1,\n grid.lty = 1,\n grid.lwd = 0.5,\n lwd = 0.5,\n lwd.axis = 0.5,\n palette.qualitative = \"Okabe-Ito\"\n))\n\n# derivatives of \"bw\"\n# - minimal\n# - ipsum\n# - dark\n \ntheme_minimal = modifyList(theme_bw, list(\n tinytheme = \"minimal\",\n bty = \"n\",\n facet.bg = NULL,\n facet.border = NULL,\n xaxt = \"labels\",\n yaxt = \"labels\"\n))\n\ntheme_ipsum = modifyList(theme_minimal, list(\n tinytheme = \"ipsum\",\n bty = \"n\",\n font.sub = 3,\n adj.ylab = 1,\n adj.xlab = 1\n))\n\ntheme_dark = modifyList(theme_minimal, list(\n tinytheme = \"dark\",\n bg = \"#1A1A1A\",\n fg = \"#BBBBBB\",\n # col = \"white\",\n col.xaxs = \"#BBBBBB\",\n col.yaxs = \"#BBBBBB\",\n col.lab = \"#BBBBBB\",\n col.main = \"#BBBBBB\",\n col.sub = \"#BBBBBB\",\n col.axis = \"#BBBBBB\",\n # facet.bg = \"gray20\",\n grid.col = \"#6D6D6D\",\n palette.qualitative = \"Set 2\",\n palette.sequential = \"Sunset\"\n))\n\n# derivative of clean/clean2\n\ntheme_ridge = modifyList(theme_clean, list(\n tinytheme = \"ridge\",\n palette.qualitative = \"Zissou 1\",\n grid = FALSE\n))\ntheme_ridge2 = modifyList(theme_clean2, list(\n tinytheme = \"ridge2\",\n palette.qualitative = \"Zissou 1\",\n grid = FALSE\n))\n"], ["/tinyplot/R/type_lines.R", "#' Lines plot type\n#'\n#' @description Type function for plotting lines.\n#' \n#' @inheritParams graphics::plot.default\n#' \n#' @examples\n#' # \"l\" type convenience character string\n#' tinyplot(circumference ~ age | Tree, data = Orange, type = \"l\")\n#' \n#' # Use `type_lines()` to pass extra arguments for customization\n#' tinyplot(circumference ~ age | Tree, data = Orange, type = type_lines(type = \"s\"))\n#' \n#' @export\ntype_lines = function(type = \"l\") {\n out = list(\n draw = draw_lines(type = type),\n data = NULL,\n name = type\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_lines = function(type = \"l\") {\n fun = function(ix, iy, icol, ipch, ibg, ilty, ilwd, cex = 1, ...) {\n lines(\n x = ix,\n y = iy,\n col = icol,\n type = type,\n pch = ipch,\n bg = ibg,\n lty = ilty,\n lwd = ilwd,\n cex = cex\n )\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_segments.R", "#' Line segments plot type\n#'\n#' @description Type function for plotting line segments.\n#' \n#' @details Contrary to base \\code{\\link[graphics]{segments}}, line segments in\n#' [tinyplot] must be specified using the `xmin`, `ymin`,`xmax`, and `ymax`\n#' arguments. \n#' \n#' @examples\n#' # \"segments\" type convenience character string\n#' tinyplot(\n#' xmin = c(0,.1), ymin = c(.2,1), xmax = c(1,.9), ymax = c(.75,0),\n#' type = \"segments\"\n#' )\n#' \n#' # Same result with type_segments()\n#' tinyplot(\n#' xmin = c(0,.1), ymin = c(.2,1), xmax = c(1,.9), ymax = c(.75,0),\n#' type = type_segments()\n#' )\n#' \n#' @export\ntype_segments = function() {\n out = list(\n draw = draw_segments(),\n data = NULL,\n name = \"segments\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_segments = function() {\n fun = function(ixmin, iymin, ixmax, iymax, ilty, ilwd, icol, ...) {\n segments(\n x0 = ixmin, y0 = iymin, x1 = ixmax, y1 = iymax,\n lty = ilty,\n lwd = ilwd,\n col = icol\n )\n }\n return(fun)\n}\n"], ["/tinyplot/R/lim.R", "# calculate limits of each plot\n\nlim_args = function(\n datapoints,\n xlim, ylim,\n xaxb = NULL, yaxb = NULL,\n xlim_user = FALSE, ylim_user = FALSE,\n type\n) {\n \n if (is.null(xlim)) {\n xlim = range(c(datapoints[[\"x\"]], datapoints[[\"xmin\"]],\n datapoints[[\"xmax\"]]), finite = TRUE)\n }\n if (is.null(ylim)) {\n ylim = range(c(datapoints[[\"y\"]], datapoints[[\"ymin\"]],\n datapoints[[\"ymax\"]]), finite = TRUE)\n }\n\n if (identical(type, \"boxplot\")) {\n xlim = xlim + c(-0.5, 0.5)\n }\n \n if (!xlim_user && !is.null(xaxb) && type != \"spineplot\") xlim = range(c(xlim, xaxb))\n if (!ylim_user && !is.null(yaxb) && type != \"spineplot\") ylim = range(c(ylim, yaxb))\n\n out = list(xlim = xlim, ylim = ylim)\n return(out)\n}\n\n"], ["/tinyplot/R/assertions.R", "check_dependency = function(library_name) {\n flag = requireNamespace(library_name, quietly = TRUE)\n if (isFALSE(flag)) {\n msg = sprintf(\"Please install the `%s` package.\", library_name)\n return(msg)\n } else {\n return(TRUE)\n }\n}\n\nassert_dependency = function(library_name) {\n flag = check_dependency(library_name)\n if (!isTRUE(flag)) stop(flag, call. = FALSE)\n return(invisible())\n}\n\nassert_choice = function(x, choice, null.ok = FALSE, name = as.character(substitute(x))) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(TRUE)\n }\n if (is.character(x) && length(x) == 1 && x %in% choice) {\n return(TRUE)\n }\n msg = sprintf(\n \"`%s` must be one of: %s\",\n name,\n paste(choice, collapse = \", \")\n )\n stop(msg, call. = FALSE)\n}\n\ncheck_true = function(x, null.ok = FALSE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(invisible(TRUE))\n }\n if (isTRUE(x)) {\n return(invisible(TRUE))\n }\n return(FALSE)\n}\n\nassert_true = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be true.\", name)\n if (!isTRUE(check_true(x, null.ok = null.ok))) {\n stop(msg, call. = FALSE)\n }\n}\n\ncheck_string = function(x, null.ok = FALSE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(invisible(TRUE))\n }\n if (is.character(x) && length(x) == 1) {\n return(invisible(TRUE))\n }\n return(FALSE)\n}\n\nassert_string = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be a string.\", name)\n if (!isTRUE(check_string(x, null.ok = null.ok))) {\n stop(msg, call. = FALSE)\n }\n}\n\ncheck_flag = function(x, null.ok = FALSE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(TRUE)\n }\n if (is.logical(x) && length(x) == 1) {\n return(TRUE)\n }\n return(FALSE)\n}\n\nassert_flag = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be a logical flag.\", name)\n if (!isTRUE(check_flag(x, null.ok = null.ok))) {\n stop(msg, call. = FALSE)\n }\n}\n\nassert_length = function(x, len = 1, null.ok = FALSE, name = as.character(substitute(x))) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(invisible(TRUE))\n }\n msg = sprintf(\"`%s` must be one of these lengths: %s\", name, paste(len, collapse = \", \"))\n if (!length(x) %in% len) {\n stop(msg, call. = FALSE)\n }\n}\n\nassert_logical = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(invisible(TRUE))\n }\n msg = sprintf(\"`%s` must be a logical vector\", name)\n if (!is.logical(x)) stop(msg, call. = FALSE)\n}\n\n\ncheck_integerish = function(x, len = NULL, lower = NULL, upper = NULL, null.ok = TRUE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(TRUE)\n }\n if (!is.numeric(x)) {\n return(FALSE)\n }\n x = stats::na.omit(x)\n if (!is.null(len) && length(x) != len) {\n return(FALSE)\n }\n if (!is.null(lower) && any(x < lower)) {\n return(FALSE)\n }\n if (!is.null(upper) && any(x > upper)) {\n return(FALSE)\n }\n if (isTRUE(any(abs(x - round(x)) > (.Machine$double.eps)^0.5))) {\n return(FALSE)\n }\n return(TRUE)\n}\n\nassert_integerish = function(x, len = NULL, lower = NULL, upper = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(invisible())\n }\n msg = sprintf(\"`%s` must be integer-ish\", name)\n if (is.null(x) && !isTRUE(null.ok)) stop(sprintf(\"%s should not be NULL.\", name), call. = FALSE)\n if (!isTRUE(check_integerish(x, len = len, lower = lower, upper = upper, null.ok = null.ok))) {\n if (!is.numeric(x)) msg = paste0(msg, \"; it is not numeric\")\n if (!is.null(len) && length(x) != len) msg = paste0(msg, sprintf(\"; its length must be %s\", len))\n if (!is.null(lower) && any(x < lower)) msg = paste0(msg, sprintf(\"; all values must be greater than or equal to %s\", lower))\n if (!is.null(upper) && any(x > upper)) msg = paste0(msg, sprintf(\"; all values must be less than or equal to %s\", upper))\n if (isTRUE(any(abs(x - round(x)) > (.Machine$double.eps)^0.5))) msg = paste0(msg, \"; all values must be close to integers\")\n stop(msg, call. = FALSE)\n }\n}\n\ncheck_numeric = function(x, len = NULL, lower = NULL, upper = NULL, null.ok = TRUE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(TRUE)\n }\n if (!is.numeric(x)) {\n return(FALSE)\n }\n if (!is.null(len) && length(x) != len) {\n return(FALSE)\n }\n if (!is.null(lower) && any(x < lower)) {\n return(FALSE)\n }\n if (!is.null(upper) && any(x > upper)) {\n return(FALSE)\n }\n return(TRUE)\n}\n\nassert_numeric = function(x, len = NULL, lower = NULL, upper = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be numeric\", name)\n if (!isTRUE(check_numeric(x, len = len, lower = lower, upper = upper, null.ok = null.ok))) {\n if (!is.null(len) && length(x) != len) msg = paste0(msg, sprintf(\"; its length must be %s\", len))\n if (!is.null(lower) && any(x < lower)) msg = paste0(msg, sprintf(\"; all values must be greater than or equal to %s\", lower))\n if (!is.null(upper) && any(x > upper)) msg = paste0(msg, sprintf(\"; all values must be less than or equal to %s\", upper))\n stop(msg, call. = FALSE)\n }\n}\n\nassert_data_frame = function(x, min_rows = 0, min_cols = 0, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be a data.frame.\", name)\n if (!is.data.frame(x)) stop(msg, call. = FALSE)\n msg = sprintf(\"Number of rows in `%s` must be at least `%s`\", name, min_rows)\n if (nrow(x) < min_rows) stop(msg, call. = FALSE)\n msg = sprintf(\"Number of columns in `%s` must be at least `%s`\", name, min_cols)\n if (ncol(x) < min_cols) stop(msg, call. = FALSE)\n}\n\n\ncheck_character = function(x, len = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(TRUE)\n } else if (!is.character(x)) {\n msg = sprintf(\"`%s` must be character.\", name)\n return(msg)\n } else if (!is.null(len) && length(x) != len) {\n msg = sprintf(\"`%s` must have length %s.\", name, len)\n return(msg)\n }\n return(TRUE)\n}\n\nassert_character = function(x, len = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n flag = check_character(x, len = len, null.ok = null.ok, name = name)\n if (!isTRUE(flag)) {\n stop(flag, call. = FALSE)\n } else {\n return(invisible(TRUE))\n }\n}\n\nassert_list = function(x, named = FALSE, len = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(invisible(TRUE))\n }\n if (!is.list(x)) stop(\"Input is not a list.\", call. = FALSE)\n if (isTRUE(named)) {\n if (is.null(names(x))) {\n stop(sprintf(\"`%s` should be named list.\", name), call. = FALSE)\n }\n }\n if (!is.null(len)) {\n if (length(x) != len) {\n stop(sprintf(\"`%s` must be of length %s.\", name, len), call. = FALSE)\n }\n }\n}\n\nassert_function = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(invisible(TRUE))\n }\n if (!is.function(x)) {\n msg = sprintf(\"`%s` must be a function.\", name)\n stop(msg, call. = FALSE)\n }\n}\n\ncheck_atomic_vector = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(invisible(TRUE))\n }\n # doesn't work on glue::glue() output\n # flag = is.atomic(x) && is.vector(x) && !is.list(x)\n flag = is.atomic(x) && is.null(dim(x)) && length(x) > 0 && !is.list(x)\n if (flag) {\n out = TRUE\n } else if (is.factor(x) && is.null(dim(x))) {\n out = TRUE\n } else {\n out = sprintf(\"`%s` must be an atomic vector.\", name)\n }\n return(out)\n}\n\nassert_atomic_vector = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n flag = check_atomic_vector(x, null.ok = null.ok, name = name)\n if (!isTRUE(flag)) {\n stop(flag, call. = FALSE)\n } else {\n return(invisible(TRUE))\n }\n}\n\nassert_class = function(x, classname) {\n if (!inherits(x, classname)) {\n msg = sprintf(\"`x` must be of class `%s`.\", classname)\n stop(msg, call. = FALSE)\n }\n}\n\n"], ["/tinyplot/R/tinyplot_add.R", "#' Add new elements to the current `tinyplot`\n#'\n#' @description\n#' This convenience function grabs the preceding `tinyplot` call and updates it\n#' with any new arguments that have been explicitly provided by the user. It\n#' then injects `add=TRUE` and evaluates the updated call, thereby drawing a new\n#' layer on top of the existing plot. `plt_add()` is a shorthand alias for\n#' `tinyplot_add()`.\n#'\n#' @section Limitations:\n#' - `tinyplot_add()` works reliably only when adding to a plot originally\n#' created using the [`tinyplot.formula`] method with a valid `data` argument.\n#' We cannot guarantee correct behavior if the original plot was created with\n#' the atomic [`tinyplot.default`] method, due to potential environment\n#' mismatches. (An exception is when the original plot arguments---`x`, `y`,\n#' etc.---are located in the global environment.)\n#'\n#' - Automatic legends for the added elements will be turned off.\n#'\n#' @param ... All named arguments override arguments from the previous calls.\n#' Arguments not supplied to [tinyplot_add] remain unchanged from the previous\n#' call.\n#'\n#' @examples\n#' tinyplot(Sepal.Width ~ Sepal.Length | Species,\n#' facet = ~Species,\n#' data = iris)\n#'\n#' tinyplot_add(type = \"lm\") ## or : plt_add(type = \"lm\")\n#'\n#' ## Note: the previous function is equivalent to (but much more convenient\n#' ## than) re-writing the full call with the new type and `add=TRUE`:\n#'\n#' # tinyplot(Sepal.Width ~ Sepal.Length | Species,\n#' # facet = ~Species,\n#' # data = iris,\n#' # type = \"lm\",\n#' # add = TRUE)\n#'\n#' @returns No return value, called for side effect of producing a plot.\n#'\n#' @export\ntinyplot_add = function(...) {\n cal = getOption(\"tinyplot_last_call\", default = NULL)\n\n ## TODO: remove the global option above and move to this when density is refactored\n # cal = get(\".last_call\", envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n\n if (is.null(cal)) {\n stop(\"No previous tinyplot call found.\")\n }\n\n args = list(...)\n for (n in names(args)) {\n if (n != \"\") {\n cal[[n]] = args[[n]]\n }\n }\n\n # allow first argument in tinyplot_add() to be unnamed\n if (isTRUE(names(args)[1] == \"\")) {\n cal[[2]] = args[[1]]\n }\n\n cal[[\"add\"]] = TRUE\n eval(cal)\n}\n\n\n\n#' @export\n#' @name plt_add\n#' @rdname tinyplot_add\nplt_add = tinyplot_add\n"], ["/tinyplot/R/type_rect.R", "#' Rectangle plot type\n#'\n#' @description Type function for plotting rectangles.\n#' \n#' @details Contrary to base \\code{\\link[graphics]{rect}}, rectangles in\n#' [tinyplot] must be specified using the `xmin`, `ymin`,`xmax`, and `ymax`\n#' arguments. \n#' \n#' @examples\n#' i = 4*(0:10)\n#' \n#' # \"rect\" type convenience character string\n#' tinyplot(\n#' xmin = 100+i, ymin = 300+i, xmax = 150+i, ymax = 380+i,\n#' by = i, fill = 0.2,\n#' type = \"rect\"\n#' )\n#' \n#' # Same result with type_rect()\n#' tinyplot(\n#' xmin = 100+i, ymin = 300+i, xmax = 150+i, ymax = 380+i,\n#' by = i, fill = 0.2,\n#' type = type_rect()\n#' )\n#' \n#' @export\ntype_rect = function() {\n out = list(\n draw = draw_rect(),\n data = NULL,\n name = \"rect\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_rect = function() {\n fun = function(ixmin, iymin, ixmax, iymax, ilty, ilwd, icol, ibg, ...) {\n rect(\n xleft = ixmin, ybottom = iymin, xright = ixmax, ytop = iymax,\n lty = ilty,\n lwd = ilwd,\n border = icol,\n col = ibg\n )\n }\n return(fun)\n}\n"], ["/tinyplot/R/tinyformula.R", "## auxiliary functions for formula/facet parsing\n\ntinyformula = function(formula, facet = NULL) {\n ## input\n ## - formula: y ~ x or y ~ x | z or ~ x or ~ x | z\n ## - facet: ~ a or ~ a + b or b ~ a\n ##\n ## output:\n ## - x: ~ x\n ## - y: NULL or ~ y\n ## - by: NULL or ~ z or ~ z1 + z2 + ... (use interaction of all)\n ## - xfacet: NULL or ~ a or ~ a + b etc.\n ## - yfacet: NULL or ~ b\n ## - full: e.g. ~ x + y + z + a + b\n\n ## preliminaries\n if (!inherits(formula, \"formula\")) formula = as.formula(formula)\n nf = length(formula)\n\n ## basic formula types\n x = ~ x\n y = if (nf == 2L) NULL else ~ y\n by = if (!inherits(formula[[nf]], \"call\") || formula[[nf]][[1L]] != as.name(\"|\")) NULL else ~ z\n if (is.null(facet) || !inherits(facet, \"formula\")) {\n xfacet = NULL\n yfacet = NULL\n } else {\n xfacet = ~ a\n yfacet = if (length(facet) == 2L) NULL else ~ b\n }\n\n ## fill with actual terms\n environment(x) = environment(formula)\n if (!is.null(y)) {\n environment(y) = environment(formula)\n y[[2L]] = formula[[2L]]\n }\n if (is.null(by)) {\n x[[2L]] = formula[[nf]]\n } else {\n environment(by) = environment(formula)\n by[[2L]] = formula[[nf]][[3L]]\n x[[2L]] = formula[[nf]][[2L]]\n }\n if (!is.null(xfacet)) {\n environment(xfacet) = environment(formula)\n xfacet[[2L]] = facet[[length(facet)]]\n }\n if (!is.null(yfacet)) {\n environment(yfacet) = environment(formula)\n yfacet[[2L]] = facet[[2L]]\n }\n\n ## combine everything\n full = x\n if (!is.null(y)) full[[2L]] = call(\"+\", full[[2L]], y[[2L]])\n if (!is.null(by)) full[[2L]] = call(\"+\", full[[2L]], by[[2L]])\n if (!is.null(xfacet)) full[[2L]] = call(\"+\", full[[2L]], xfacet[[2L]])\n if (!is.null(yfacet)) full[[2L]] = call(\"+\", full[[2L]], yfacet[[2L]])\n\n ## return list of all formulas\n return(list(\n x = x,\n y = y,\n by = by,\n xfacet = xfacet,\n yfacet = yfacet,\n full = full\n ))\n}\n\ntinyframe = function(formula, data, drop = FALSE) {\n ## input\n ## - formula: (sub-)formula\n ## - data: model.frame from full formula\n if (is.null(formula)) return(NULL)\n names = sapply(attr(terms(formula), \"variables\")[-1L], deparse, width.cutoff = 500L)\n data[, names, drop = drop]\n}\n"], ["/tinyplot/R/utils.R", "rescale_num = function (x, from = NULL, to = NULL) {\n if (is.null(from)) from = range(x)\n if (is.null(to)) to = c(0, 1)\n (x - from[1])/diff(from) * diff(to) + to[1]\n}\n\n## Function for efficiently checking whether a vector has more than n unique\n## values (uses a hash set approach for large vectors to check sequentially)\nmore_than_n_unique = function(x, n, small_vec_len = 1e3L) {\n len_x = length(x)\n # For \"small\" vectors, just use direct length(unique(x)) approach\n if (len_x <= small_vec_len) {\n return(length(unique(x)) > n)\n } else {\n # For larger vectors, use the hash set approach\n env = new.env(hash = TRUE, size = n)\n count = 0\n for (val in x) {\n if (!exists(as.character(val), env)) {\n assign(as.character(val), TRUE, env)\n count = count + 1\n if (count > n) {\n return(TRUE)\n }\n }\n }\n return(FALSE)\n }\n}\n\n\n## Null coalescing operator\nif (getRversion() <= \"4.4.0\") {\n `%||%` = function(x, y) if (is.null(x)) y else x\n}\n\n\n## Function that computes an appropriate bandwidth kernel based on a string\n## input\nbw_fun = function(kernel, x) {\n kernel = tolower(kernel)\n switch(\n kernel,\n nrd0 = bw.nrd0(x),\n nrd = bw.nrd(x),\n ucv = bw.ucv(x),\n bcv = bw.bcv(x),\n sj = bw.SJ(x),\n stop(\"Invalid `bw` string. Choose from 'nrd0', 'nrd', 'ucv', 'bcv', or 'SJ'.\")\n )\n}\n"], ["/tinyplot/R/setup_device.R", "setup_device = function(file, width, height) {\n # write to file\n if (!is.null(file)) {\n filepath = file\n filewidth = width\n fileheight = height\n if (is.null(filewidth)) filewidth = .tpar[[\"file.width\"]]\n if (is.null(fileheight)) fileheight = .tpar[[\"file.height\"]]\n fileres = .tpar[[\"file.res\"]]\n # catch to close interactive device if one isn't already open\n fkdev = is.null(dev.list())\n # grab existing device pars to pass on to next one\n dop = par(no.readonly = TRUE)\n # close interactive device if not already open\n if (isTRUE(fkdev)) dev.off()\n exttype = file_ext(filepath)\n if (exttype == \"pdf\" && .tpar[[\"cairo\"]]) {\n exttype = \"cairo\"\n } else if (exttype == \"jpg\") {\n exttype = \"jpeg\"\n }\n switch(exttype,\n png = png(filepath, width = filewidth, height = fileheight, units = \"in\", res = fileres),\n jpeg = jpeg(filepath, width = filewidth, height = fileheight, units = \"in\", res = fileres),\n pdf = pdf(filepath, width = filewidth, height = fileheight),\n cairo = cairo_pdf(filepath, width = filewidth, height = fileheight),\n svg = svg(filepath, width = filewidth, height = fileheight),\n stop(\"\\nUnsupported file extension. Only '.png', '.jpg', '.pdf', or '.svg' are allowed.\\n\")\n )\n dop$new = FALSE # catch for some interfaces\n par(dop)\n\n # interactive plot with user-specified width/height\n } else if (!is.null(width) || !is.null(height)) {\n devwidth = width\n devheight = height\n # if one of width or height is missing, set equal to the other\n if (is.null(devwidth)) devwidth = devheight\n if (is.null(devheight)) devheight = devwidth\n # catch to close interactive device if one isn't already open\n fkdev = is.null(dev.list())\n # grab existing device pars to pass on to next one\n dop = par(no.readonly = TRUE)\n # close interactive device if not already open\n if (isTRUE(fkdev)) dev.off()\n dev.new(width = devwidth, height = devheight)\n dop$new = FALSE # catch for some interfaces\n par(dop)\n }\n}\n"], ["/tinyplot/R/zzz.R", "#' Operations on package load\n#' @importFrom utils globalVariables\n#' @param libname library name\n#' @param pkgname package name name\n#' @keywords internal\n#' @noRd\n.onLoad = function(libname, pkgname) {\n # https://stackoverflow.com/questions/12598242/global-variables-in-packages-in-r\n # https://stackoverflow.com/questions/49056642/r-how-to-make-variable-available-to-namespace-at-loading-time?noredirect=1&lq=1\n init_environment()\n init_tpar()\n set_environment_variable(\".saved_par_before\", NULL)\n set_environment_variable(\".saved_par_after\", NULL)\n set_environment_variable(\".saved_par_first\", NULL)\n set_environment_variable(\".last_call\", NULL)\n set_environment_variable(\".tpar_hooks\", NULL)\n\n globalVariables(c(\n \"add\",\n \"asp\",\n \"axes\",\n \"by_continuous\",\n \"by_ordered\",\n \"cex_fct_adj\",\n \"dots\",\n \"draw\",\n \"facet_bg\",\n \"facet_border\",\n \"facet_col\",\n \"facet_font\",\n \"facet_newlines\",\n \"facet_rect\",\n \"facet_text\",\n \"facet.args\",\n \"facet\",\n \"facets\",\n \"fill\",\n \"flip\",\n \"frame.plot\",\n \"has_legend\",\n \"iby\",\n \"ifacet\",\n \"nfacet_cols\",\n \"nfacet_rows\",\n \"nfacets\",\n \"ngrps\",\n \"oxaxis\",\n \"oyaxis\",\n \"ribbon.alpha\",\n \"split_data\",\n \"type\",\n \"x\",\n \"xaxl\",\n \"xaxs\",\n \"xaxt\",\n \"xlabs\",\n \"xlim\",\n \"xlim_user\",\n \"xlvls\",\n \"xmax\",\n \"xmin\",\n \"y\",\n \"yaxl\",\n \"yaxs\",\n \"yaxt\",\n \"ylabs\",\n \"ylim\",\n \"ylim_user\",\n \"ymax\",\n \"ymin\"\n ))\n}\n"], ["/tinyplot/R/hooks.R", "# Copied from https://raw.githubusercontent.com/r-lib/evaluate/refs/heads/main/R/hooks.R\n# license: MIT + file LICENSE\n\n\n\n#' Set and remove hooks\n#'\n#' This interface wraps the base [setHook()] function to provide a return\n#' value that makes it easy to undo.\n#'\n#' @param hooks a named list of hooks - each hook can either be a function or\n#' a list of functions.\n#' @param action `\"replace\"`, `\"append\"` or `\"prepend\"`\n#' @keywords internal\nset_hooks <- function(hooks, action = \"append\") {\n old <- list()\n for (hook_name in names(hooks)) {\n old[[hook_name]] <- getHook(hook_name)\n setHook(hook_name, hooks[[hook_name]], action = action)\n }\n invisible(old)\n}\n\n#' @rdname set_hooks\n#' @keywords internal\nremove_hooks <- function(hooks) {\n for (hook_name in names(hooks)) {\n hook <- getHook(hook_name)\n if (length(hook) > 0) {\n for (fun in unlist(hooks[hook_name])) {\n hook[sapply(hook, identical, fun)] <- NULL\n }\n }\n setHook(hook_name, hook, \"replace\")\n }\n}\n"], ["/tinyplot/R/environment.R", "init_environment = function() {\n tnypltptns = parent.env(environment())\n assign(\".tinyplot_env\", new.env(), envir = tnypltptns)\n .tpar = new.env()\n assign(\".tpar\", .tpar, envir = tnypltptns)\n}\n\nget_environment_variable = function(name) {\n get(name, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n}\n\nset_environment_variable = function(name, value) {\n assign(name, value, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n}\n"], ["/tinyplot/R/tinyplot-package.R", "#' @keywords internal\n\"_PACKAGE\"\n\nNULL\n"]], "task_instance_info": {"created_time": "2025-08-21 01:20:28", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(family = \"gaussian\", se = TRUE, level = 0.95, type = \"response\") {}", "code_description": "This code segment functions to: Configure visualization settings for a generalized linear model by specifying statistical computation parameters, controlling confidence interval display options, and structuring graphical components for prediction outputs transformed through response-link conversions."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\ntype_glm = function(family = \"gaussian\", se = TRUE, level = 0.95, type = \"response\", ...) {\n data_glm(family = family, se = se, level = level, type = type, ...)\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-20-50"}, "editdistance_info": {"edit_distance": 40.404, "calculate_time": "2025-08-21 01:20:50", "true_code_clean": "function(family = \"gaussian\", se = TRUE, level = 0.95, type = \"response\") {\n assert_flag(se)\n out = list(\n draw = draw_ribbon(),\n data = data_glm(family = family, se = se, level = level, type = type),\n name = if (isTRUE(se)) \"ribbon\" else \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}", "predict_code_clean": "type_glm = function(family = \"gaussian\", se = TRUE, level = 0.95, type = \"response\", ...) {\n data_glm(family = family, se = se, level = level, type = type, ...)\n}"}} {"repo_name": "tinyplot", "file_name": "/tinyplot/R/type_area.R", "inference_info": {"prefix_code": "#' @rdname type_ribbon\n#' @export\ntype_area = function(alpha = NULL) {\n out = list(\n draw = NULL,\n data = data_area(alpha = alpha),\n name = \"area\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_area = function(alpha = alpha) {\n ribbon.alpha = if (is.null(alpha)) .tpar[[\"ribbon.alpha\"]] else (alpha)\n fun = ", "suffix_code": "\n return(fun)\n}\n", "middle_code": "function(datapoints, ...) {\n datapoints$ymax = datapoints$y\n datapoints$ymin = rep.int(0, nrow(datapoints))\n out = list(\n datapoints = datapoints,\n ymax = datapoints$ymax,\n ymin = datapoints$ymin,\n type = \"ribbon\",\n ribbon.alpha = ribbon.alpha\n )\n return(out)\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/tinyplot/R/type_ribbon.R", "#' Ribbon and area plot types\n#' \n#' @param alpha numeric value between 0 and 1 specifying the opacity of ribbon shading\n#' If no `alpha` value is provided, then will default to `tpar(\"ribbon.alpha\")` \n#' (i.e., probably `0.2` unless this has been overridden by the user in their global \n#' settings.)\n#'\n#' @description Type constructor functions for producing polygon ribbons, which \n#' define a `y` interval (usually spanning from `ymin` to `ymax`) for each\n#' `x` value. Area plots are a special case of ribbon plot where `ymin` is\n#' set to 0 and `ymax` is set to `y`.\n#' \n#' @examples\n#' x = 1:100/10\n#' y = sin(x)\n#' \n#' #\n#' ## Ribbon plots\n#' \n#' # \"ribbon\" convenience string\n#' tinyplot(x = x, ymin = y-1, ymax = y+1, type = \"ribbon\")\n\n#' # Same result with type_ribbon()\n#' tinyplot(x = x, ymin = y-1, ymax = y+1, type = type_ribbon())\n#' \n#' # y will be added as a line if it is specified\n#' tinyplot(x = x, y = y, ymin = y-1, ymax = y+1, type = \"ribbon\")\n#'\n#' #\n#' ## Area plots\n#' \n#' # \"area\" type convenience string\n#' tinyplot(x, y, type = \"area\")\n#' \n#' # Same result with type_area()\n#' tinyplot(x, y, type = type_area())\n#' \n#' # Area plots are often used for time series charts\n#' tinyplot(AirPassengers, type = \"area\")\n#' @export\ntype_ribbon = function(alpha = NULL) {\n out = list(\n draw = draw_ribbon(),\n data = data_ribbon(ribbon.alpha = alpha),\n name = \"ribbon\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_ribbon = function() {\n fun = function(ix, iy, ixmin, ixmax, iymin, iymax, ibg, ilty, ilwd, icol, ipch, i, flip = FALSE, ...) {\n polyg = type_polygon()$draw\n lin = type_lines()$draw\n if (isFALSE(flip)) {\n polyg(ix = c(ix, rev(ix)), iy = c(iymin, rev(iymax)), icol = NA, ibg = ibg)\n } else {\n polyg(c(ixmin, rev(ixmax)), iy = c(iy, rev(iy)), icol = NA, ibg = ibg)\n }\n lin(ix = ix, iy = iy, icol = icol, ipch = ipch, ibg = ibg, ilty = ilty, ilwd = ilwd, type = \"l\")\n }\n return(fun)\n}\n\n\ndata_ribbon = function(ribbon.alpha = NULL) {\n ribbon.alpha = sanitize_ribbon.alpha(ribbon.alpha)\n fun = function(datapoints, xlabs, null_by, null_facet, ...) {\n # Convert x to factor if it's not already\n if (is.character(datapoints$x)) {\n datapoints$x = as.factor(datapoints$x)\n }\n\n if (is.factor(datapoints$x)) {\n xlvls = levels(datapoints$x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n datapoints$x = as.integer(datapoints$x)\n } else {\n xlabs = NULL\n }\n\n if (null_by && null_facet) {\n xord = order(datapoints$x)\n } else if (null_facet) {\n xord = order(datapoints$by, datapoints$x)\n } else if (null_by) {\n xord = order(datapoints$facet, datapoints$x)\n } else {\n xord = order(datapoints$by, datapoints$facet, datapoints$x)\n }\n\n # Reorder x, y, ymin, and ymax based on the order determined\n datapoints = datapoints[xord,]\n\n # Catch for missing ymin and ymax \n if (is.null(datapoints$ymin)) datapoints$ymin = datapoints$y \n if (is.null(datapoints$ymax)) datapoints$ymax = datapoints$y\n\n out = list(\n x = datapoints$x,\n y = datapoints$y,\n ymin = datapoints$ymin,\n ymax = datapoints$ymax,\n xlabs = xlabs,\n datapoints = datapoints,\n ribbon.alpha = ribbon.alpha)\n\n if (length(unique(datapoints$by)) > 1) out[[\"by\"]] = datapoints$by\n if (length(unique(datapoints$facet)) > 1) out[[\"facet\"]] = datapoints$facet\n\n return(out)\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_density.R", "#' Density plot type\n#' \n#' @md\n#' @description Type function for density plots.\n#' @inheritParams stats::density\n#' @param kernel a character string giving the smoothing kernel to be used. This\n#' must partially match one of `\"gaussian\"`, `\"rectangular\"`, `\"triangular\"`,\n#' `\"epanechnikov\"`, `\"biweight\"`, `\"cosine\"` or `\"optcosine\"`, with default\n#' `\"gaussian\"`, and may be abbreviated to a unique prefix (single letter).\n#'\n#' `\"cosine\"` is smoother than `\"optcosine\"`, which is the usual 'cosine'\n#' kernel in the literature and almost MSE-efficient. However, `\"cosine\"` is\n#' the version used by S.\n#' @inheritParams type_ribbon\n#' @param joint.bw character string indicating whether (and how) the smoothing\n#' bandwidth should be computed from the joint data distribution when there\n#' are multiple subgroups. The options are `\"mean\"` (the default), `\"full\"`,\n#' and `\"none\"`. Also accepts a logical argument, where `TRUE` maps to\n#' `\"mean\"` and `FALSE` maps to `\"none\"`. See the \"Bandwidth selection\"\n#' section below for a discussion of practical considerations.\n#' @inherit stats::density details\n#' @section Bandwidth selection: While the choice of smoothing bandwidth will\n#' always stand to affect a density visualization, it gains an added\n#' importance when multiple densities are drawn simultaneously (e.g., for\n#' subgroups with respect to `by` or `facet`). Allowing each subgroup to\n#' compute its own separate bandwidth independently offers greater flexibility\n#' in capturing the unique characteristics of each subgroup, particularly when\n#' distributions differ substantially in location and/or scale. However, this\n#' approach may overemphasize small random variations and make it harder to\n#' visually compare densities across subgroups. Hence, it is often useful to\n#' employ the same (\"joint\") bandwidth across all subgroups. The following\n#' strategies are available via the `joint.bw` argument:\n#' \n#' - The default `joint.bw = \"mean\"` first computes the individual bandwidths\n#' for each group but then computes their mean, weighted by the number of\n#' observations in each group. This will work well when all groups have\n#' similar amounts of scatter (similar variances), even when they have\n#' potentially rather different locations. The weighted averaging stabilizes\n#' potential fluctuations in the individual bandwidths, especially when some\n#' subgroups are rather small.\n#' \n#' - Alternatively, `joint.bw = \"full\"` can be used to compute the joint\n#' bandwidth from the full joint distribution (merging all groups). This will\n#' yield an even more robust bandwidth, especially when the groups overlap\n#' substantially (i.e., have similar locations and scales). However, it may\n#' lead to too large bandwidths and thus too much smoothing, especially when\n#' the locations of the groups differ substantially.\n#' \n#' - Finally, `joint.bw = \"none\"` disables the joint bandwidth so that each\n#' group just employs its individual bandwidth. This is often the best choice\n#' if the amounts of scatter differ substantially between the groups, thus\n#' necessitating different amounts of smoothing.\n#' @section Titles: This tinyplot method for density plots differs from the base\n#' \\code{\\link[stats]{plot.density}} function in its treatment of titles. The\n#' x-axis title displays only the variable name, omitting details about the\n#' number of observations and smoothing bandwidth. Additionally, the main\n#' title is left blank by default for a cleaner appearance.\n#' @examples\n#' # \"density\" type convenience string\n#' tinyplot(~Sepal.Length, data = iris, type = \"density\")\n#' \n#' # grouped density example\n#' tinyplot(~Sepal.Length | Species, data = iris, type = \"density\")\n#' \n#' # use `bg = \"by\"` (or, equivalent `fill = \"by\"`) to get filled densities\n#' tinyplot(~Sepal.Length | Species, data = iris, type = \"density\", fill = \"by\")\n#' \n#' # use `type_density()` to pass extra arguments for customization\n#' tinyplot(\n#' ~Sepal.Length | Species, data = iris,\n#' type = type_density(bw = \"SJ\"),\n#' main = \"Bandwidth computed using Sheather & Jones (1991)\"\n#' )\n#' \n#' # The default for grouped density plots is to use the mean of the\n#' # individual subgroup bandwidths (weighted by group size) as the\n#' # joint bandwidth. Alternatively, the bandwidth from the \"full\"\n#' # data or separate individual bandwidths (\"none\") can be used.\n#' tinyplot(~Sepal.Length | Species, data = iris,\n#' ylim = c(0, 1.25), type = \"density\") # mean (default)\n#' tinyplot_add(joint.bw = \"full\", lty = 2) # full data\n#' tinyplot_add(joint.bw = \"none\", lty = 3) # none (individual)\n#' legend(\"topright\", c(\"Mean\", \"Full\", \"None\"), lty = 1:3, bty = \"n\", title = \"Joint BW\")\n#' \n#' @importFrom stats density weighted.mean\n#' @importFrom stats bw.SJ bw.bcv bw.nrd bw.nrd0 bw.ucv \n#' @export\ntype_density = function(\n bw = \"nrd0\",\n joint.bw = c(\"mean\", \"full\", \"none\"),\n adjust = 1,\n kernel = c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"),\n n = 512,\n # more args from density here?\n alpha = NULL\n ) {\n kernel = match.arg(kernel, c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"))\n if (is.logical(joint.bw)) {\n joint.bw = ifelse(joint.bw, \"mean\", \"none\")\n }\n joint.bw = match.arg(joint.bw, c(\"mean\", \"full\", \"none\"))\n out = list(\n data = data_density(bw = bw, adjust = adjust, kernel = kernel, n = n,\n joint.bw = joint.bw, alpha = alpha),\n draw = NULL,\n name = \"density\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\ndata_density = function(bw = \"nrd0\", adjust = 1, kernel = \"gaussian\", n = 512,\n joint.bw = \"none\", alpha = NULL) {\n fun = function(by, facet, ylab, col, bg, ribbon.alpha, datapoints, ...) {\n \n ribbon.alpha = if (is.null(alpha)) .tpar[[\"ribbon.alpha\"]] else (alpha)\n \n if (is.null(ylab)) ylab = \"Density\"\n \n datapoints = split(datapoints, list(datapoints$by, datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n \n if (joint.bw == \"none\" || is.numeric(bw)) {\n dens_bw = bw\n } else {\n if (joint.bw == \"mean\") {\n # Use weighted mean of subgroup bandwidths\n bws = sapply(datapoints, function(dat) bw_fun(kernel = bw, dat$x))\n ws = sapply(datapoints, nrow)\n dens_bw = weighted.mean(bws, ws)\n } else if (joint.bw == \"full\") {\n dens_bw = bw_fun(kernel = bw, unlist(sapply(datapoints, `[[`, \"x\")))\n }\n }\n \n datapoints = lapply(datapoints, function(dat) {\n d = density(dat$x, bw = dens_bw, kernel = kernel, n = n)\n out = data.frame(\n by = dat$by[1], # already split\n facet = dat$facet[1], # already split\n y = d$y,\n x = d$x\n )\n return(out)\n })\n datapoints = do.call(rbind, datapoints)\n datapoints$ymax = datapoints$y\n datapoints$ymin = rep.int(0, nrow(datapoints))\n \n # flags for legend and fill\n dtype = if (!is.null(bg)) \"ribbon\" else \"l\"\n dwas_area_type = !is.null(bg)\n \n out = list(\n ylab = ylab,\n type = dtype,\n was_area_type = dwas_area_type,\n ribbon.alpha = ribbon.alpha,\n datapoints = datapoints,\n by = if (length(unique(datapoints$by)) == 1) by else datapoints$by, \n facet = if (length(unique(datapoints$facet)) == 1) facet else datapoints$facet\n )\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_ridge.R", "#' Ridge plot type\n#'\n#' @description Type function for producing ridge plots (also known as joy plots),\n#' which display density distributions for multiple groups with vertical offsets.\n#' This function uses `tinyplot` scaffolding, which enables added functionality\n#' such as grouping and faceting.\n#'\n#' The line color is controlled by the `col` argument in the `tinyplot()` call.\n#' The fill color is controlled by the `bg` argument in the `tinyplot()` call.\n#'\n#' @param scale Numeric. Controls the scaling factor of each plot.\n#' Values greater than 1 means that plots overlap.\n#' @param joint.max character indicating how to scale the maximum of the densities:\n#' The default `\"all\"` indicates that all densities are scaled jointly relative to\n#' the same maximum so that the areas of all densities are comparable.\n#' Alternatively, `\"facet\"` indicates that the maximum is computed within\n#' each facet so that the areas of the densities are comparable within each\n#' facet but not necessarily across facets. Finally, `\"by\"` indicates that\n#' each row (in each facet) is scaled separately, so that the areas of the\n#' densities for `by` groups in the same row are comparable but not necessarily\n#' across rows.\n#' @param breaks Numeric. If a color gradient is used for shading, the\n#' breaks between the colors can be modified. The default is to use\n#' equidistant breaks spanning the range of the `x` variable.\n#' @param probs Numeric. Instead of specifying the same `breaks` on the\n#' x-axis for all groups, it is possible to specify group-specific quantiles\n#' at the specified `probs`. The quantiles are computed based on the density\n#' (rather than the raw original variable). Only one of `breaks` or\n#' `probs` must be specified.\n#' @param ylevels a character or numeric vector specifying in which order\n#' the levels of the y-variable should be plotted.\n#' @inheritParams stats::density\n#' @param kernel a character string giving the smoothing kernel to be used. This\n#' must partially match one of `\"gaussian\"`, `\"rectangular\"`, `\"triangular\"`,\n#' `\"epanechnikov\"`, `\"biweight\"`, `\"cosine\"` or `\"optcosine\"`, with default\n#' `\"gaussian\"`, and may be abbreviated to a unique prefix (single letter).\n#'\n#' `\"cosine\"` is smoother than `\"optcosine\"`, which is the usual 'cosine'\n#' kernel in the literature and almost MSE-efficient. However, `\"cosine\"` is\n#' the version used by S.\n#' @param joint.bw character string indicating whether (and how) the smoothing\n#' bandwidth should be computed from the joint data distribution. The default\n#' of `\"mean\"` will compute the joint bandwidth as the mean of the individual\n#' subgroup bandwidths (weighted by their number of observations). Choosing\n#' `\"full\"` will result in a joint bandwidth computed from the full\n#' distribution (merging all subgroups). For `\"none\"` the individual bandwidth\n#' will be computed independently for each subgroup. Also accepts a logical\n#' argument, where `TRUE` maps to `\"mean\"` and `FALSE` maps to `\"none\"`. See\n#' \\code{\\link{type_density}} for some discussion of practical considerations.\n#' @param gradient Logical or character. Should a gradient fill be used to\n#' shade the area under the density? If a character specification is used,\n#' then it can either be of length 1 and specify the palette to be used with\n#' `gradient = TRUE` corresponding to `gradient = \"viridis\"`. If a character\n#' vector of length greater than 1 is used, then it should specify the\n#' colors in the palette, e.g., `gradient = hcl.colors(512)`.\n#' @param raster Logical. Should the `gradient` fill be drawn using\n#' \\code{\\link[graphics]{rasterImage}}? Defaults to `FALSE`, in which case the\n#' `gradient` fill will instead be drawn using\n#' \\code{\\link[graphics]{polygon}}. See the `Technical note on gradient fills`\n#' section below.\n#' @param col Character string denoting the outline (border) color for all\n#' of the ridge densities. Note that a singular value is expected; if multiple\n#' colors are provided then only the first will be used. This argument is mostly\n#' useful for the aesthetic effect of drawing a common outline color in\n#' combination with gradient fills. See Examples.\n#' @param alpha Numeric in the range `[0,1]` for adjusting the alpha\n#' transparency of the density fills. In most cases, will default to a value of\n#' 1, i.e. fully opaque. But for some `by` grouped plots (excepting the special\n#' cases where `by==y` or `by==x`), will default to 0.6.\n#' \n#' @section Technical note on gradient fills:\n#' \n#' `tinyplot` uses two basic approaches for drawing gradient fills in ridge line\n#' plots, e.g., if `type_ridge(gradient = TRUE)`.\n#' \n#' The first (and default) polygon-based approach involves dividing up the main\n#' density region into many smaller polygons along the x-axis. Each of these\n#' smaller polygons inherits a different color \"segment\" from the underlying\n#' palette swatch, which in turn creates the effect of a continuous gradient\n#' when they are all plotted together. Internally, this polygon-based approach\n#' is vectorized (i.e., all of the sub-polygons are plotted simultaneously). It\n#' is thus efficient from a plotting perspective and generally also performs\n#' well from an aesthetic perspective. However, it can occasionally produce\n#' undesirable plotting artifacts on some graphics devices---e.g., thin but\n#' visible vertical lines---if alpha transparency is being used at the same \n#' time.\n#' \n#' For this reason, we also offer an alternative raster-based approach for\n#' gradient fills that users can invoke via\n#' `type_ridge(gradient = TRUE, raster = TRUE)`. The essential idea is that we\n#' coerce the density polygon into a raster representation (using\n#' \\code{\\link[graphics]{rasterImage}}) and achieve the gradient effect via\n#' color interpolation. The trade-off this time is potential smoothness\n#' artifacts around the top of the ridge densities at high resolutions, since we\n#' have converted a vector object into a raster object.\n#' \n#' Again, we expect that the choice between these two approaches will only\n#' matter for ridge plots that combine gradient fills with alpha transparency\n#' (and on certain graphics devices). We recommend that users experiment to\n#' determine which approach is optimal for their device.\n#'\n#' @examples\n#' aq = transform(\n#' airquality,\n#' Month = factor(month.abb[Month], levels = month.abb[5:9]),\n#' Month2 = factor(month.name[Month], levels = month.name[5:9]),\n#' Late = ifelse(Day > 15, \"Late\", \"Early\")\n#' )\n#' \n#' # default ridge plot (using the \"ridge\" convenience string)\n#' tinyplot(Month ~ Temp, data = aq, type = \"ridge\")\n#' \n#' # for ridge plots, we recommend pairing with the dedicated theme(s), which\n#' # facilitate nicer y-axis labels, grid lines, etc.\n#' \n#' tinytheme(\"ridge\")\n#' tinyplot(Month ~ Temp, data = aq, type = \"ridge\")\n#' \n#' tinytheme(\"ridge2\") # removes the plot frame (but keeps x-axis line)\n#' tinyplot(Month ~ Temp, data = aq, type = \"ridge\")\n#' \n#' # the \"ridge(2)\" themes are especially helpful for long y labels, due to\n#' # dyanmic plot adjustment\n#' tinyplot(Month2 ~ Temp, data = aq, type = \"ridge\")\n#' \n#' # pass customization arguments through type_ridge()... for example, use\n#' # the scale argument to change/avoid overlap of densities (more on scaling\n#' # further below)\n#' \n#' tinyplot(Month ~ Temp, data = aq, type = type_ridge(scale = 1))\n#' \n#' ## by grouping is also supported. two special cases of interest:\n#'\n#' # 1) by == y (color by y groups)\n#' tinyplot(Month ~ Temp | Month, data = aq, type = \"ridge\")\n#'\n#' # 2) by == x (gradient coloring along x)\n#' tinyplot(Month ~ Temp | Temp, data = aq, type = \"ridge\")\n#'\n#' # aside: pass explicit `type_ridge(col = )` arg to set a different\n#' # border color\n#' tinyplot(Month ~ Temp | Temp, data = aq, type = type_ridge(col = \"white\"))\n#'\n#' # gradient coloring along the x-axis can also be invoked manually without\n#' # a legend (the next two tinyplot calls are equivalent)\n#' \n#' # tinyplot(Month ~ Temp, data = aq, type = type_ridge(gradient = \"agsunset\"))\n#' tinyplot(Month ~ Temp, data = aq, type = type_ridge(gradient = TRUE))\n#' \n#' # aside: when combining gradient fill with alpha transparency, it may be\n#' # better to use the raster-based approach (test on your graphics device)\n#' \n#' tinyplot(Month ~ Temp, data = aq,\n#' type = type_ridge(gradient = TRUE, alpha = 0.5),\n#' main = \"polygon fill (default)\")\n#' tinyplot(Month ~ Temp, data = aq,\n#' type = type_ridge(gradient = TRUE, alpha = 0.5, raster = TRUE),\n#' main = \"raster fill\")\n#'\n#' # highlighting only the center 50% of the density (i.e., 25%-75% quantiles)\n#' tinyplot(Month ~ Temp, data = aq, type = type_ridge(\n#' gradient = hcl.colors(3, \"Dark Mint\")[c(2, 1, 2)],\n#' probs = c(0.25, 0.75), col = \"white\"))\n#'\n#' # highlighting the probability distribution by color gradient\n#' # (darkest point = median)\n#' tinyplot(Month ~ Temp, data = aq, type = type_ridge(\n#' gradient = hcl.colors(250, \"Dark Mint\")[c(250:1, 1:250)],\n#' probs = 0:500/500))\n#'\n#' # faceting also works, although we recommend switching (back) to the \"ridge\"\n#' # theme for faceted ridge plots\n#' \n#' tinytheme(\"ridge\")\n#' tinyplot(Month ~ Ozone, facet = ~ Late, data = aq,\n#' type = type_ridge(gradient = TRUE))\n#' \n#' ## use the joint.max argument to vary the maximum density used for\n#' ## determining relative scaling...\n#' \n#' # jointly across all densities (default) vs. per facet\n#' tinyplot(Month ~ Temp, facet = ~ Late, data = aq,\n#' type = type_ridge(scale = 1))\n#' tinyplot(Month ~ Temp, facet = ~ Late, data = aq,\n#' type = type_ridge(scale = 1, joint.max = \"facet\"))\n#' \n#' # jointly across all densities (default) vs. per by row\n#' tinyplot(Month ~ Temp | Late, data = aq,\n#' type = type_ridge(scale = 1))\n#' tinyplot(Month ~ Temp | Late, data = aq,\n#' type = type_ridge(scale = 1, joint.max = \"by\"))\n#' \n#' # restore the default theme\n#' tinytheme()\n#'\n#' @export\ntype_ridge = function(\n scale = 1.5,\n joint.max = c(\"all\", \"facet\", \"by\"),\n breaks = NULL,\n probs = NULL,\n ylevels = NULL,\n bw = \"nrd0\",\n joint.bw = c(\"mean\", \"full\", \"none\"),\n adjust = 1,\n kernel = c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"),\n n = 512,\n # more args from density here?\n gradient = FALSE,\n raster = FALSE,\n col = NULL,\n alpha = NULL\n ) {\n \n kernel = match.arg(kernel, c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"))\n if (is.logical(joint.bw)) {\n joint.bw = ifelse(joint.bw, \"mean\", \"none\")\n }\n joint.bw = match.arg(joint.bw, c(\"mean\", \"full\", \"none\"))\n\n out = list(\n draw = draw_ridge(),\n data = data_ridge(bw = bw, adjust = adjust, kernel = kernel, n = n,\n joint.bw = joint.bw,\n scale = scale,\n joint.max = joint.max,\n gradient = gradient,\n breaks = breaks,\n probs = probs,\n ylevels = ylevels,\n raster = raster,\n col = col,\n alpha = alpha\n ),\n name = \"ridge\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n#\n## Underlying data_ridge function\ndata_ridge = function(bw = \"nrd0\", adjust = 1, kernel = \"gaussian\", n = 512,\n joint.bw = \"mean\",\n scale = 1.5,\n joint.max = \"all\",\n gradient = FALSE,\n breaks = NULL,\n probs = NULL,\n ylevels = NULL,\n raster = FALSE,\n col = NULL,\n alpha = NULL\n ) {\n fun = function(datapoints, yaxt = NULL, null_by, ...) {\n # catch for special cases\n anyby = !null_by\n x_by = anyby && identical(datapoints$x, datapoints$by)\n y_by = anyby && identical(datapoints$y, datapoints$by)\n if (x_by) {\n gradient = TRUE\n datapoints$by = \"\"\n } else if (y_by) {\n datapoints$by = \"\"\n } else if (anyby && is.null(alpha)) {\n alpha = 0.6\n }\n # flag for (non-gradient) interior fill adjustment\n fill_by = anyby || y_by\n if (isTRUE(x_by)) fill_by = FALSE\n # if (isTRUE(anyby) && is.null(alpha)) alpha = 0.6\n\n ## reorder levels of y-variable if requested\n if (!is.null(ylevels)) {\n if (!is.factor(datapoints$y)) datapoints$y = factor(datapoints$y)\n datapoints$y = factor(datapoints$y, levels = if(is.numeric(ylevels)) levels(datapoints$y)[ylevels] else ylevels)\n if (y_by) datapoints$by = datapoints$y\n }\n\n ##\n datapoints = split(datapoints, list(datapoints$y, datapoints$by, datapoints$facet))\n\n if (joint.bw == \"none\" || is.numeric(bw)) {\n dens_bw = bw\n } else {\n if (joint.bw == \"mean\") {\n # Use weighted mean of subgroup bandwidths\n bws = sapply(datapoints, function(dat) bw_fun(kernel = bw, dat$x))\n ws = sapply(datapoints, nrow)\n dens_bw = weighted.mean(bws, ws)\n } else if (joint.bw == \"full\") {\n dens_bw = bw_fun(kernel = bw, unlist(sapply(datapoints, `[[`, \"x\")))\n }\n }\n\n datapoints = lapply(datapoints, function(dat) {\n dens = density(dat$x, bw = dens_bw, kernel = kernel, n = n)\n out = data.frame(\n by = dat$by[1], # already split\n facet = dat$facet[1], # already split\n x = dens$x,\n y = dat$y[1],\n ymin = 0L,\n ymax = dens$y\n )\n return(out)\n })\n datapoints = do.call(rbind, datapoints)\n\n if (is.character(joint.max)) {\n joint.max = match.arg(joint.max, c(\"all\", \"facet\", \"by\"))\n joint.max = switch(joint.max,\n \"all\" = rep.int(1, nrow(datapoints)),\n \"facet\" = datapoints$facet,\n \"by\" = interaction(datapoints$facet, datapoints$y)\n )\n joint.max = ave(datapoints$ymax, joint.max, FUN = max)\n }\n datapoints$ymax = datapoints$ymax / joint.max * scale\n\n datapoints = split(datapoints, datapoints$facet)\n offset_z = function(k) {\n ksplit = split(k, k$y)\n for (idx in seq_along(ksplit)) {\n ksplit[[idx]]$ymax = ksplit[[idx]]$ymax + idx - 1\n ksplit[[idx]]$ymin = ksplit[[idx]]$ymin + idx - 1\n }\n k = do.call(rbind, ksplit)\n return(k)\n }\n datapoints = do.call(rbind, lapply(datapoints, offset_z))\n\n if (y_by) {\n datapoints$y = factor(datapoints$y)\n datapoints$by = factor(datapoints$y, levels = rev(levels(datapoints$y)))\n } else if (x_by) {\n datapoints$by = datapoints$x\n }\n\n # Manual breaks flag. Only used if gradient is on\n manbreaks = !is.null(breaks) || !is.null(probs)\n\n ## use color gradient?\n xlim = range(datapoints$x, na.rm = TRUE)\n if (!is.null(probs)) {\n if (!is.null(breaks)) {\n warning(\"only one of 'breaks' and 'quantile' must be specified\")\n probs = NULL\n } else {\n if (probs[1L] > 0) probs = c(0, probs)\n if (probs[length(probs)] < 1) probs = c(probs, 1)\n }\n }\n if (!isFALSE(gradient)) {\n dotspal = list(...)[[\"palette\"]]\n palette = if (!is.null(dotspal)) dotspal else gradient\n gradient = TRUE\n if (isTRUE(palette)) {\n palette = if (!is.null(.tpar[[\"palette.sequential\"]])) .tpar[[\"palette.sequential\"]] else \"viridis\"\n }\n\n if (length(palette) > 1L || !is.character(palette)) {\n ## color vector already given\n if (is.null(breaks) && is.null(probs)) {\n breaks = seq(from = xlim[1L], to = xlim[2L], length.out = length(palette) + 1L)\n } else {\n npal = pmax(length(breaks), length(probs)) - 1L\n if (length(palette) != npal) {\n warning(\"length of 'palette' does not match 'breaks'/'probs'\")\n palette = rep_len(palette, npal)\n }\n if (isTRUE(raster)) raster = npal > 20L\n }\n } else {\n ## only palette name given\n npal = if (is.null(breaks) && is.null(probs)) 512L else pmax(length(breaks), length(probs)) - 1L\n palette = hcl.colors(npal, palette = palette)\n if (is.null(breaks) && is.null(probs)) breaks = seq(from = xlim[1L], to = xlim[2L], length.out = npal + 1L)\n if (isTRUE(raster)) raster = npal > 20L\n }\n } else {\n palette = NULL\n if (!is.null(breaks) || !is.null(probs)) gradient = TRUE\n }\n if (!is.null(breaks)) {\n breaks[1L] = pmin(breaks[1L], xlim[1L])\n breaks[length(breaks)] = pmax(breaks[length(breaks)], xlim[2L])\n }\n \n if (is.null(col) && (!anyby || x_by)) col = \"black\"\n\n out = list(\n datapoints = datapoints,\n yaxt = \"n\",\n ylim = c(min(datapoints$ymin), max(datapoints$ymax)),\n type_info = list(\n gradient = gradient,\n palette = palette,\n breaks = breaks,\n probs = probs,\n manbreaks = manbreaks,\n yaxt = yaxt,\n raster = raster,\n x_by = x_by,\n y_by = y_by,\n fill_by = fill_by,\n col = col,\n alpha = alpha\n )\n )\n return(out)\n }\n return(fun)\n}\n\n\n#\n## Underlying draw_ridge function\ndraw_ridge = function() {\n fun = function(ix, iy, iz, ibg, icol, iymin, iymax, type_info, ...) {\n ridge_theme = identical(.tpar[[\"tinytheme\"]], \"ridge\") || identical(.tpar[[\"tinytheme\"]], \"ridge2\")\n d = data.frame(x = ix, y = iy, ymin = iymin, ymax = iymax)\n dsplit = split(d, d$y)\n if (is.null(ibg)) {\n default_bg = if (!ridge_theme && !is.null(.tpar[[\"palette.qualitative\"]])) seq_palette(by_col(), n = 2)[2] else \"gray\"\n ibg = if (isTRUE(type_info[[\"fill_by\"]])) seq_palette(icol, n = 2)[2] else default_bg\n }\n if (!is.null(type_info[[\"alpha\"]]) && is.null(type_info[[\"palette\"]])) {\n ibg = adjustcolor(ibg, alpha.f = type_info[[\"alpha\"]])\n }\n if (!is.null(type_info[[\"col\"]])) icol = type_info[[\"col\"]]\n lab = if (is.factor(d$y)) levels(d$y) else unique(d$y)\n if (isTRUE(type_info[[\"y_by\"]])) {\n # avoid duplicating the y-axis labs for the special y==by case\n # val = match(lab, levels(d$y)) - 1\n val = match(d$y[1], levels(d$y))\n lab = lab[val]\n val = val - 1\n } else {\n val = cumsum(rep(1, length(lab))) - 1\n }\n if (ridge_theme) abline(h = val, col = .tpar[[\"grid.col\"]])\n draw_segments = if (type_info[[\"raster\"]]) segmented_raster else segmented_polygon\n for (i in rev(seq_along(dsplit))) {\n if (type_info[[\"gradient\"]]) {\n with(\n dsplit[[i]],\n draw_segments(\n x, ymax, ymin = ymin[1L],\n breaks = type_info[[\"breaks\"]],\n probs = type_info[[\"probs\"]],\n manbreaks = type_info[[\"manbreaks\"]],\n col = if (is.null(type_info[[\"palette\"]])) ibg else type_info[[\"palette\"]],\n # border = if (is.null(type_info[[\"palette\"]])) icol else \"transparent\",\n alpha = type_info[[\"alpha\"]]\n )\n )\n }\n with(dsplit[[i]], polygon(x, ymax, col = if (type_info[[\"gradient\"]]) \"transparent\" else ibg, border = NA))\n with(dsplit[[i]], lines(x, ymax, col = icol))\n }\n # tinyAxis(x = d$y, side = 2, at = val, labels = lab, type = type_info[[\"yaxt\"]], padj = padj)\n if (ridge_theme) {\n tinyAxis(x = d$y, side = 2, at = val, labels = lab, type = type_info[[\"yaxt\"]],\n padj = 0,\n mgp = c(3, 1, 0) - c(0.5, 0.5 + 0.3, 0),\n tcl = 0)\n if (identical(.tpar[[\"tinytheme\"]], \"ridge2\")) axis(1, labels = FALSE)\n } else {\n tinyAxis(x = d$y, side = 2, at = val, labels = lab, type = type_info[[\"yaxt\"]])\n }\n }\n return(fun)\n}\n\n\n#\n## Auxiliary functions\n\n## auxiliary function for drawing shaded segmented polygon\nsegmented_polygon = function(x, y, ymin = 0, breaks = range(x), probs = NULL, manbreaks = FALSE, col = \"lightgray\", border = \"transparent\", alpha = NULL) {\n\n if (!is.null(probs)) {\n ## map quantiles to breaks\n if (!(missing(breaks) || is.null(breaks))) stop(\"only one of 'breaks' and 'probs' must be specified\")\n breaks = quantile.density(list(x = x, y = y - ymin), probs = probs)\n }\n\n ## sanity check\n if (breaks[1L] > x[1L] || breaks[length(breaks)] < x[length(x)]) stop(\"'breaks' do no span range of 'x'\")\n\n # ## recycle color (if necessary) rather use colorRampPalette below\n # col = rep_len(col, length(breaks) - 1L)\n \n # Create individual polygons\n if (isFALSE(manbreaks)) {\n # Special case for length(breaks)==length(x). We can take a fully vectorised\n # shortcut\n xx = c(rbind(x[-length(x)], x[-1], x[-1], x[-length(x)], NA))\n yy = c(rbind(y[-length(y)], y[-1], ymin, ymin, NA))\n } else {\n # For other cases, we'll do a bit more work to make sure that the polygons\n # overlap\n bvals = do.call(c, sapply(seq_along(breaks[-1]), function(b) tail(x[x= xrange[1] & breaks < xrange[2])\n idx = c(idx, length(idx)+1)\n col = col[idx]\n col = colorRampPalette(col, alpha = TRUE)(length(x)) # support alpha?\n }\n } else if (isFALSE(manbreaks) || length(col) > length(x) || length(x) %% length(col) != 0) {\n xrange = range(xx, na.rm = TRUE)\n idx = which(breaks >= xrange[1] & breaks < xrange[2])\n idx = c(idx, length(idx)+1)\n col = col[idx]\n col = colorRampPalette(col, alpha = TRUE)(length(x)) # support alpha?\n }\n }\n border = if (is.null(alpha)) col else adjustcolor(col = col, alpha.f = alpha/2)\n \n ## draw all polygons\n polygon(xx, yy, col = col, border = border, lwd = 0.5)\n}\n\n#' @importFrom graphics rasterImage\n#' @importFrom grDevices as.raster\nsegmented_raster = function(x, y, ymin = 0, breaks = range(x), probs = NULL, manbreaks = FALSE, col = \"lightgray\", border = \"transparent\", alpha = NULL) {\n ## set up raster matrix on x-grid and 500 y-pixels \n n = length(x) - 1L\n m = 500L ## FIXME: hard-coded?\n r = matrix(1:n, ncol = n, nrow = m, byrow = TRUE)\n\n ## map quantiles to breaks\n if (!is.null(probs)) {\n if (!(missing(breaks) || is.null(breaks))) stop(\"only one of 'breaks' and 'probs' must be specified\")\n breaks = quantile.density(list(x = x, y = y - ymin), probs = probs)\n }\n\n if (!is.null(alpha)) col = adjustcolor(col, alpha.f = alpha)\n col = rev(col) ## uncomment to make extreme cols dark\n ## map colors to intervals and fill colors by column\n col = col[cut(x, breaks = breaks, include.lowest = TRUE)]\n r[] = col[r]\n\n ## clip raster pixels above density line\n ymax = max(y)\n ix = cbind(as.vector(row(r)), as.vector(col(r)))\n ix = ix[seq(from = ymax, to = ymin, length.out = m)[row(r)] > y[col(r)], , drop = FALSE]\n r[ix] = NA\n\n ## plot density and add raster gradient\n rasterImage(as.raster(r), min(x), ymin, max(x), ymax, interpolate = length(breaks) >= 20L) ## FIXME: improve quality for \"few\" breaks?\n}\n\n## auxiliary function for determining quantiles based on density function\n\n#' @importFrom stats median approx\nquantile.density = function(x, probs = seq(0, 1, 0.25), ...) {\n ## sanity check for probabilities\n if (any(probs < 0 | probs > 1)) stop(\"'probs' outside [0,1]\")\n\n ## probability density function, extrapolated to zero, use midpoints\n n = length(x$x)\n pdf = x$y\n pdf = c(0, pdf, 0)\n\n ## x variable, also extrapolated, use midpoints\n x = x$x\n delta = median(diff(x))\n x = c(x[1L] - delta, x, x[n] + delta)\n\n ## numerical integration of density\n cdf = c(0, cumsum(diff(x) * (pdf[-1L] + pdf[-(n + 2L)])/2))\n cdf = cdf/cdf[n + 2L]\n\n ## approximate quantiles\n approx(cdf, x, xout = probs, rule = 2)$y \n}\n"], ["/tinyplot/R/type_histogram.R", "#' Histogram plot type\n#' \n#' @md\n#' @description Type function for histogram plots. `type_hist` is an alias for\n#' `type_histogram`.\n#' @param breaks Passed to \\code{\\link[graphics]{hist}}. One of:\n#' - a vector giving the breakpoints between histogram cells,\n#' - a function to compute the vector of breakpoints,\n#' - a single number giving the number of cells for the histogram,\n#' - a character string naming an algorithm to compute the number of cells (see ‘Details’ of \\code{\\link[graphics]{hist}}),\n#' - a function to compute the number of cells.\n#' In the last three cases the number is a suggestion only; as the breakpoints\n#' will be set to pretty values, the number is limited to 1e6 (with a warning if\n#' it was larger). If breaks is a function, the x vector is supplied to it as\n#' the only argument (and the number of breaks is only limited by the amount of\n#' available memory).\n#' @param free.breaks Logical indicating whether the breakpoints should be\n#' computed separately for each group or facet? Default is `FALSE`, meaning\n#' that the breakpoints are computed from the full dataset; thus ensuring\n#' common bin widths across each group/facet. Can also use `free` as an\n#' acceptable argument alias. Ignored if there are no groups and/or facets.\n#' @param drop.zeros Logical indicating whether bins with zero counts should be\n#' dropped before plotting. Default is `TRUE`. Note that switching to `FALSE`\n#' may interfere with faceted plot behaviour if `facet.args = list(free)`,\n#' since the `x` variable is effectively recorded over the full range of the\n#' x-axis (even if it does not extend over this range for every group).\n#' @inheritParams graphics::hist\n#' @examples\n#' # \"histogram\"/\"hist\" type convenience string(s)\n#' tinyplot(Nile, type = \"histogram\")\n#' \n#' # Use `type_histogram()` to pass extra arguments for customization\n#' tinyplot(Nile, type = type_histogram(breaks = 30))\n#' tinyplot(Nile, type = type_histogram(breaks = 30, freq = FALSE))\n#' # etc.\n#' \n#' # Grouped histogram example\n#' tinyplot(\n#' ~Petal.Width | Species,\n#' type = \"histogram\",\n#' data = iris\n#' )\n#' \n#' # Faceted version\n#' tinyplot(\n#' ~Petal.Width, facet = ~Species,\n#' type = \"histogram\",\n#' data = iris\n#' )\n#' \n#' # For visualizing faceted histograms across varying scales, you may also wish\n#' # to impose free histogram breaks too (i.e., calculate breaks separately for\n#' # each group). Compare:\n#' \n#' # free facet scales + shared histogram breaks, versus...\n#' tinyplot(\n#' ~Petal.Width, facet = ~Species,\n#' facet.args = list(free = TRUE),\n#' type = type_histogram(),\n#' data = iris\n#' )\n#' # ... free facet scales + free histogram breaks\n#' tinyplot(\n#' ~Petal.Width, facet = ~Species,\n#' facet.args = list(free = TRUE),\n#' type = type_histogram(free = TRUE),\n#' data = iris\n#' )\n#' \n#' @export\ntype_histogram = function(breaks = \"Sturges\",\n freq = NULL, right = TRUE,\n free.breaks = FALSE, drop.zeros = TRUE) {\n out = list(\n data = data_histogram(breaks = breaks,\n free.breaks = free.breaks, drop.zeros = drop.zeros,\n freq = freq, right = right),\n draw = draw_rect(),\n name = \"histogram\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n#' @export\n#' @name type_hist\n#' @rdname type_histogram\ntype_hist = type_histogram\n\n\ndata_histogram = function(breaks = \"Sturges\",\n free.breaks = FALSE, drop.zeros = TRUE,\n freq = NULL, right = TRUE) {\n \n hbreaks = breaks\n hfree.breaks = free.breaks\n hdrop.zeros = drop.zeros\n hfreq = freq\n hright = right\n \n fun = function(by, facet, ylab, col, bg, ribbon.alpha, datapoints, .breaks = hbreaks, .freebreaks = hfree.breaks, .freq = hfreq, .right = hright, .drop.zeros = hdrop.zeros, ...) {\n \n hbreaks = ifelse(!sapply(.breaks, is.null), .breaks, \"Sturges\")\n \n if (is.null(by) && is.null(palette)) {\n if (is.null(col)) col = par(\"fg\")\n if (is.null(bg)) bg = \"lightgray\"\n } else {\n if (is.null(bg)) bg = ribbon.alpha\n }\n\n if (!.freebreaks) xbreaks = hist(datapoints$x, breaks = hbreaks, right = .right, plot = FALSE)$breaks\n datapoints = split(datapoints, list(datapoints$by, datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n \n datapoints = lapply(datapoints, function(k) {\n if (.freebreaks) xbreaks = breaks\n h = hist(k$x, breaks = xbreaks, right = .right, plot = FALSE)\n # zero count cases\n if (.drop.zeros) {\n nzidx = which(h$counts > 0)\n h$density = h$density[nzidx]\n h$counts = h$counts[nzidx]\n h$breaks = h$breaks[c(1, nzidx+1)]\n h$mids = h$mids[nzidx]\n }\n freq = if(!is.null(.freq)) .freq else is.null(.freq) && h$equidist\n out = data.frame(\n by = k$by[1], # already split\n facet = k$facet[1], # already split\n ymin = 0,\n ymax = if (freq) h$counts else h$density,\n xmin = h$breaks[-1],\n xmax = h$mids + (h$mids - h$breaks[-1]),\n freq = freq\n )\n return(out)\n })\n datapoints = do.call(rbind, datapoints)\n \n if (is.null(ylab)) {\n ylab = ifelse(datapoints$freq[1], \"Frequency\", \"Density\")\n }\n\n out = list(\n x = c(datapoints$xmin, datapoints$xmax), \n y = c(datapoints$ymin, datapoints$ymax),\n ymin = datapoints$ymin, \n ymax = datapoints$ymax, \n xmin = datapoints$xmin, \n xmax = datapoints$xmax, \n ylab = ylab, \n col = col, \n bg = bg, \n datapoints = datapoints,\n by = if (length(unique(datapoints$by)) == 1) by else datapoints$by, \n facet = if (length(unique(datapoints$facet)) == 1) facet else datapoints$facet\n )\n return(out)\n }\n return(fun)\n}\n"], ["/tinyplot/R/tinyplot.R", "#' @title Lightweight extension of the base R plotting function\n#'\n#' @description\n#' Enhances the base \\code{\\link[graphics]{plot}} function. Supported features\n#' include automatic legends and facets for grouped data, additional plot types,\n#' theme customization, and so on. Users can call either `tinyplot()`, or its\n#' shorthand alias `plt()`.\n#'\n#' @md\n#' @param x,y the x and y arguments provide the x and y coordinates for the\n#' plot. Any reasonable way of defining the coordinates is acceptable; most\n#' likely the names of existing vectors or columns of data frames. See the\n#' 'Examples' section below, or the function\n#' \\code{\\link[grDevices]{xy.coords}} for details. If supplied separately, `x`\n#' and `y` must be of the same length.\n#' @param xmin,xmax,ymin,ymax minimum and maximum coordinates of relevant area\n#' or interval plot types. Only used when the `type` argument is one of\n#' `\"rect\"` or `\"segments\"` (where all four min-max coordinates are required),\n#' or `\"pointrange\"`, `\"errorbar\"`, or `\"ribbon\"` (where only `ymin` and\n#' `ymax` required alongside `x`). In the formula method the arguments\n#' can be specified as `ymin = var` if `var` is a variable in `data`.\n#' @param by grouping variable(s). The default behaviour is for groups to be\n#' represented in the form of distinct colours, which will also trigger an\n#' automatic legend. (See `legend` below for customization options.) However,\n#' groups can also be presented through other plot parameters (e.g., `pch` or\n#' `lty`) by passing an appropriate \"by\" keyword; see Examples. Note that\n#' continuous (i.e., gradient) colour legends are also supported if the user\n#' passes a numeric or integer to `by`. To group by multiple variables, wrap\n#' them with \\code{\\link[base]{interaction}}.\n#' @param facet the faceting variable(s) that you want arrange separate plot\n#' windows by. Can be specified in various ways:\n#' - In \"atomic\" form, e.g. `facet = fvar`. To facet by multiple variables in\n#' atomic form, simply interact them, e.g.\n#' `interaction(fvar1, fvar2)` or `factor(fvar1):factor(fvar2)`.\n#' - As a one-sided formula, e.g. `facet = ~fvar`. Multiple variables can be\n#' specified in the formula RHS, e.g. `~fvar1 + fvar2` or `~fvar1:fvar2`. Note\n#' that these multi-variable cases are _all_ treated equivalently and\n#' converted to `interaction(fvar1, fvar2, ...)` internally. (No distinction\n#' is made between different types of binary operators, for example, and so\n#' `f1+f2` is treated the same as `f1:f2`, is treated the same as `f1*f2`,\n#' etc.)\n#' - As a two-side formula, e.g. `facet = fvar1 ~ fvar2`. In this case, the\n#' facet windows are arranged in a fixed grid layout, with the formula LHS\n#' defining the facet rows and the RHS defining the facet columns. At present\n#' only single variables on each side of the formula are well supported. (We\n#' don't recommend trying to use multiple variables on either the LHS or RHS\n#' of the two-sided formula case.)\n#' - As a special `\"by\"` convenience keyword, in which case facets will match\n#' the grouping variable(s) passed to `by` above.\n#' @param facet.args an optional list of arguments for controlling faceting\n#' behaviour. (Ignored if `facet` is NULL.) Supported arguments are as\n#' follows:\n#' - `nrow`, `ncol` for overriding the default \"square\" facet window\n#' arrangement. Only one of these should be specified, but `nrow` will take\n#' precedence if both are specified together. Ignored if a two-sided formula\n#' is passed to the main `facet` argument, since the layout is arranged in a\n#' fixed grid.\n#' - `free` a logical value indicating whether the axis limits (scales) for\n#' each individual facet should adjust independently to match the range of\n#' the data within that facet. Default is `FALSE`. Separate free scaling of\n#' the x- or y-axis (i.e., whilst holding the other axis fixed) is not\n#' currently supported.\n#' - `fmar` a vector of form `c(b,l,t,r)` for controlling the base margin\n#' between facets in terms of lines. Defaults to the value of `tpar(\"fmar\")`,\n#' which should be `c(1,1,1,1)`, i.e. a single line of padding around each\n#' individual facet, assuming it hasn't been overridden by the user as part\n#' their global \\code{\\link[tinyplot]{tpar}} settings. Note some automatic\n#' adjustments are made for certain layouts, and depending on whether the plot\n#' is framed or not, to reduce excess whitespace. See\n#' \\code{\\link[tinyplot]{tpar}} for more details.\n#' - `cex`, `font`, `col`, `bg`, `border` for adjusting the facet title text\n#' and background. Default values for these arguments are inherited from\n#' \\code{\\link[tinyplot]{tpar}} (where they take a \"facet.\" prefix, e.g.\n#' `tpar(\"facet.cex\")`). The latter function can also be used to set these\n#' features globally for all `tinyplot` plots.\n#' @param formula a \\code{\\link[stats]{formula}} that optionally includes\n#' grouping variable(s) after a vertical bar, e.g. `y ~ x | z`. One-sided\n#' formulae are also permitted, e.g. `~ y | z`. Only a single `y` and `x`\n#' variable (if any) must be specified but multiple grouping variables\n#' can be included in different ways, e.g. `y ~ x | z1:z2` or\n#' `y ~ x | z1 + z2`. (These two representations are treated as equivalent;\n#' both are parsed as `interaction(z1, z2)` internally.) If arithmetic\n#' operators are used for transforming variables, they should be wrapped in\n#' `I()`, e.g., `I(y1/y2) ~ x`. Note that the `formula` and `x` arguments\n#' should not be specified in the same call.\n#' @param data a data.frame (or list) from which the variables in formula\n#' should be taken. A matrix is converted to a data frame.\n#' @param type character string or call to a `type_*()` function giving the\n#' type of plot desired.\n#' - NULL (default): Choose a sensible type for the type of `x` and `y` inputs\n#' (i.e., usually `\"p\"`).\n#' - 1-character values supported by \\code{\\link[graphics]{plot}}:\n#' - `\"p\"` Points\n#' - `\"l\"` Lines\n#' - `\"b\"` Both points and lines\n#' - `\"c\"` Empty points joined by lines\n#' - `\"o\"` Overplotted points and lines\n#' - `\"s\"` Stair steps\n#' - `\"S\"` Stair steps\n#' - `\"h\"` Histogram-like vertical lines\n#' - `\"n\"` Empty plot over the extent of the data\n#' - `tinyplot`-specific types. These fall into several categories:\n#' - Shapes:\n#' - `\"area\"` / [`type_area()`]: Plots the area under the curve from `y` = 0 to `y` = f(`x`).\n#' - `\"errorbar\"` / [`type_errorbar()`]: Adds error bars to points; requires `ymin` and `ymax`.\n#' - `\"pointrange\"` / [`type_pointrange()`]: Combines points with error bars.\n#' - `\"polygon\"` / [`type_polygon()`]: Draws polygons.\n#' - `\"polypath\"` / [`type_polypath()`]: Draws a path whose vertices are given in `x` and `y`.\n#' - `\"rect\"` / [`type_rect()`]: Draws rectangles; requires `xmin`, `xmax`, `ymin`, and `ymax`.\n#' - `\"ribbon\"` / [`type_ribbon()`]: Creates a filled area between `ymin` and `ymax`.\n#' - `\"segments\"` / [`type_segments()`]: Draws line segments between pairs of points.\n#' - `\"text\"` / [`type_text()`]: Add text annotations.\n#' - Visualizations:\n#' - `\"barplot\"` / [`type_barplot()`]: Creates a bar plot.\n#' - `\"boxplot\"` / [`type_boxplot()`]: Creates a box-and-whisker plot.\n#' - `\"density\"` / [`type_density()`]: Plots the density estimate of a variable.\n#' - `\"histogram\"` / [`type_histogram()`]: Creates a histogram of a single variable.\n#' - `\"jitter\"` / [`type_jitter()`]: Jittered points.\n#' - `\"qq\"` / [`type_qq()`]: Creates a quantile-quantile plot.\n#' - `\"ridge\"` / [`type_ridge()`]: Creates a ridgeline (aka joy) plot.\n#' - `\"rug\"` / [`type_rug()`]: Adds a rug to an existing plot.\n#' - `\"spineplot\"` / [`type_spineplot()`]: Creates a spineplot or spinogram.\n#' - `\"violin\"` / [`type_violin()`]: Creates a violin plot.\n#' - Models:\n#' - `\"loess\"` / [`type_loess()`]: Local regression curve.\n#' - `\"lm\"` / [`type_lm()`]: Linear regression line.\n#' - `\"glm\"` / [`type_glm()`]: Generalized linear model fit.\n#' - `\"spline\"` / [`type_spline()`]: Cubic (or Hermite) spline interpolation.\n#' - Functions:\n#' - [`type_abline()`]: line(s) with intercept and slope.\n#' - [`type_hline()`]: horizontal line(s).\n#' - [`type_vline()`]: vertical line(s).\n#' - [`type_function()`]: arbitrary function.\n#' - [`type_summary()`]: summarize `y` by unique values of `x`.\n#' @param legend one of the following options:\n#' - NULL (default), in which case the legend will be determined by the\n#' grouping variable. If there is no group variable (i.e., `by` is NULL) then\n#' no legend is drawn. If a grouping variable is detected, then an automatic\n#' legend is drawn to the _outer_ right of the plotting area. Note that the\n#' legend title and categories will automatically be inferred from the `by`\n#' argument and underlying data.\n#' - A convenience string indicating the legend position. The string should\n#' correspond to one of the position keywords supported by the base `legend`\n#' function, e.g. \"right\", \"topleft\", \"bottom\", etc. In addition, `tinyplot`\n#' supports adding a trailing exclamation point to these keywords, e.g.\n#' \"right!\", \"topleft!\", or \"bottom!\". This will place the legend _outside_\n#' the plotting area and adjust the margins of the plot accordingly. Finally,\n#' users can also turn off any legend printing by specifying \"none\".\n#' - Logical value, where TRUE corresponds to the default case above (same\n#' effect as specifying NULL) and FALSE turns the legend off (same effect as\n#' specifying \"none\").\n#' - A list or, equivalently, a dedicated `legend()` function with supported\n#' legend arguments, e.g. \"bty\", \"horiz\", and so forth.\n#' @param main a main title for the plot, see also `title`.\n#' @param sub a subtitle for the plot.\n#' @param xlab a label for the x axis, defaults to a description of x.\n#' @param ylab a label for the y axis, defaults to a description of y.\n#' @param ann a logical value indicating whether the default annotation (title\n#' and x and y axis labels) should appear on the plot.\n#' @param xlim the x limits (x1, x2) of the plot. Note that x1 > x2 is allowed\n#' and leads to a ‘reversed axis’. The default value, NULL, indicates that\n#' the range of the `finite` values to be plotted should be used.\n#' @param ylim the y limits of the plot.\n#' @param axes logical or character. Should axes be drawn (`TRUE` or `FALSE`)?\n#' Or alternatively what type of axes should be drawn: `\"standard\"` (with\n#' axis, ticks, and labels; equivalent to `TRUE`), `\"none\"` (no axes;\n#' equivalent to `FALSE`), `\"ticks\"` (only ticks and labels without axis line),\n#' `\"labels\"` (only labels without ticks and axis line), `\"axis\"` (only axis\n#' line and labels but no ticks). To control this separately for the two\n#' axes, use the character specifications for `xaxt` and/or `yaxt`.\n#' @param xaxt,yaxt character specifying the type of x-axis and y-axis,\n#' respectively. See `axes` for the possible values.\n#' @param xaxs,yaxs character specifying the style of the interval calculation\n#' used for the x-axis and y-axis, respectively. See\n#' \\code{\\link[graphics]{par}} for the possible values.\n#' @param xaxb,yaxb numeric vector (or character vector, if appropriate) giving\n#' the break points at which the axis tick-marks are to be drawn. Break points\n#' outside the range of the data will be ignored if the associated axis\n#' variable is categorical, or an explicit `x/ylim` range is given.\n#' @param xaxl,yaxl a function or a character keyword specifying the format of\n#' the x- or y-axis tick labels. Note that this is a post-processing step that\n#' affects the _appearance_ of the tick labels only; use in conjunction with\n#' `x/yaxb` if you would like to adjust the position of the tick marks too. In\n#' addition to user-supplied formatting functions (e.g., [`format`],\n#' [`toupper`], [`abs`], or other custom function), several convenience\n#' keywords (or their symbol equivalents) are available for common formatting\n#' transformations: `\"percent\"` (`\"%\"`), `\"comma\"` (`\",\"`), `\"log\"` (`\"l\"`),\n#' `\"dollar\"` (`\"$\"`), `\"euro\"` (`\"€\"`), or `\"sterling\"` (`\"£\"`). See the\n#' [`tinylabel`] documentation for examples.\n#' @param log a character string which contains `\"x\"` if the x axis is to be\n#' logarithmic, `\"y\"` if the y axis is to be logarithmic and `\"xy\"` or `\"yx\"`\n#' if both axes are to be logarithmic.\n#' @param flip logical. Should the plot orientation be flipped, so that the\n#' y-axis is on the horizontal plane and the x-axis is on the vertical plane?\n#' Default is FALSE.\n#' @param frame.plot a logical indicating whether a box should be drawn around\n#' the plot. Can also use `frame` as an acceptable argument alias.\n#' The default is to draw a frame if both axis types (set via `axes`, `xaxt`,\n#' or `yaxt`) include axis lines.\n#' @param grid argument for plotting a background panel grid, one of either:\n#' - a logical (i.e., `TRUE` to draw the grid), or\n#' - a panel grid plotting function like `grid()`.\n#' Note that this argument replaces the `panel.first` and `panel.last`\n#' arguments from base `plot()` and tries to make the process more seamless\n#' with better default behaviour. The default behaviour is determined by (and\n#' can be set globally through) the value of `tpar(\"grid\")`.\n#' @param palette one of the following options:\n#' - NULL (default), in which case the palette will be chosen according to\n#' the class and cardinality of the \"by\" grouping variable. For non-ordered\n#' factors or strings with a reasonable number of groups, this will inherit\n#' directly from the user's default \\code{\\link[grDevices]{palette}} (e.g.,\n#' \"R4\"). In other cases, including ordered factors and high cardinality, the\n#' \"Viridis\" palette will be used instead. Note that a slightly restricted\n#' version of the \"Viridis\" palette---where extreme color values have been\n#' trimmed to improve visual perception---will be used for ordered factors\n#' and continuous variables. In the latter case of a continuous grouping\n#' variable, we also generate a gradient legend swatch.\n#' - A convenience string corresponding to one of the many palettes listed by\n#' either `palette.pals()` or `hcl.pals()`. Note that the string can be\n#' case-insensitive (e.g., \"Okabe-Ito\" and \"okabe-ito\" are both valid).\n#' - A palette-generating function. This can be \"bare\" (e.g.,\n#' `palette.colors`) or \"closed\" with a set of named arguments (e.g.,\n#' `palette.colors(palette = \"Okabe-Ito\", alpha = 0.5)`). Note that any\n#' unnamed arguments will be ignored and the key `n` argument, denoting the\n#' number of colours, will automatically be spliced in as the number of\n#' groups.\n#' - A vector or list of colours, e.g. `c(\"darkorange\", \"purple\", \"cyan4\")`.\n#' If too few colours are provided for a discrete (qualitative) set of\n#' groups, then the colours will be recycled with a warning. For continuous\n#' (sequential) groups, a gradient palette will be interpolated. \n#' @param col plotting color. Character, integer, or vector of length equal to\n#' the number of categories in the `by` variable. See `col`. Note that the\n#' default behaviour in `tinyplot` is to vary group colors along any variables\n#' declared in the `by` argument. Thus, specifying colors manually should not\n#' be necessary unless users wish to override the automatic colors produced by\n#' this grouping process. Typically, this would only be done if grouping\n#' features are deferred to some other graphical parameter (i.e., passing the\n#' \"by\" keyword to one of `pch`, `lty`, `lwd`, or `bg`; see below.)\n#' @param pch plotting \"character\", i.e., symbol to use. Character, integer, or\n#' vector of length equal to the number of categories in the `by` variable.\n#' See `pch`. In addition, users can supply a special `pch = \"by\"` convenience\n#' argument, in which case the characters will automatically loop over the\n#' number groups. This automatic looping will begin at the global character\n#' value (i.e., `par(\"pch\")`) and recycle as necessary.\n#' @param lty line type. Character, integer, or vector of length equal to the\n#' number of categories in the `by` variable. See `lty`. In addition, users\n#' can supply a special `lty = \"by\"` convenience argument, in which case the\n#' line type will automatically loop over the number groups. This automatic\n#' looping will begin at the global line type value (i.e., `par(\"lty\")`) and\n#' recycle as necessary.\n#' @param lwd line width. Numeric scalar or vector of length equal to the\n#' number of categories in the `by` variable. See `lwd`. In addition, users\n#' can supply a special `lwd = \"by\"` convenience argument, in which case the\n#' line width will automatically loop over the number of groups. This\n#' automatic looping will be centered at the global line width value (i.e.,\n# ` par(\"lwd\")`) and pad on either side of that.\n#' @param bg background fill color for the open plot symbols 21:25 (see\n#' `points.default`), as well as ribbon and area plot types.\n#' Users can also supply either one of two special convenience arguments that\n#' will cause the background fill to inherit the automatic grouped coloring\n#' behaviour of `col`:\n#'\n#' - `bg = \"by\"` will insert a background fill that inherits the main color\n#' mappings from `col`.\n#' - `by = ` (i.e., a numeric in the range `[0,1]`) will insert\n#' a background fill that inherits the main color mapping(s) from `col`, but\n#' with added alpha-transparency.\n#'\n#' For both of these convenience arguments, note that the (grouped) `bg`\n#' mappings will persist even if the (grouped) `col` defaults are themselves\n#' overridden. This can be useful if you want to preserve the grouped palette\n#' mappings by background fill but not boundary color, e.g. filled points. See\n#' examples.\n#' @param fill alias for `bg`. If non-NULL values for both `bg` and `fill` are\n#' provided, then the latter will be ignored in favour of the former.\n#' @param alpha a numeric in the range `[0,1]` for adjusting the alpha channel\n#' of the color palette, where 0 means transparent and 1 means opaque. Use\n#' fractional values, e.g. `0.5` for semi-transparency.\n#' @param cex character expansion. A numerical vector (can be a single value)\n#' giving the amount by which plotting characters and symbols should be scaled\n#' relative to the default. Note that NULL is equivalent to 1.0, while NA\n#' renders the characters invisible.\n#' @param subset,na.action,drop.unused.levels arguments passed to `model.frame`\n#' when extracting the data from `formula` and `data`.\n#' @param add logical. If TRUE, then elements are added to the current plot rather\n#' than drawing a new plot window. Note that the automatic legend for the\n#' added elements will be turned off. See also [tinyplot_add], which provides\n#' a convenient wrapper around this functionality for layering on top of an\n#' existing plot without having to repeat arguments.\n#' @param draw a function that draws directly on the plot canvas (before `x` and\n#' `y` are plotted). The `draw` argument is primarily useful for adding common\n#' elements to each facet of a faceted plot, e.g.\n#' \\code{\\link[graphics]{abline}} or \\code{\\link[graphics]{text}}. Note that\n#' this argument is somewhat experimental and that _no_ internal checking is\n#' done for correctness; the provided argument is simply captured and\n#' evaluated as-is. See Examples.\n#' @param restore.par a logical value indicating whether the\n#' \\code{\\link[graphics]{par}} settings prior to calling `tinyplot` should be\n#' restored on exit. Defaults to FALSE, which makes it possible to add\n#' elements to the plot after it has been drawn. However, note the the outer\n#' margins of the graphics device may have been altered to make space for the\n#' `tinyplot` legend. Users can opt out of this persistent behaviour by\n#' setting to TRUE instead. See also [get_saved_par] for another option to\n#' recover the original \\code{\\link[graphics]{par}} settings, as well as\n#' longer discussion about the trade-offs involved.\n#' @param empty logical indicating whether the interior plot region should be\n#' left empty. The default is `FALSE`. Setting to `TRUE` has a similar effect\n#' to invoking `type = \"n\"` above, except that any legend artifacts owing to a\n#' particular plot type (e.g., lines for `type = \"l\"` or squares for\n#' `type = \"area\"`) will still be drawn correctly alongside the empty plot. In\n#' contrast,`type = \"n\"` implicitly assumes a scatterplot and so any legend\n#' will only depict points.\n#' @param file character string giving the file path for writing a plot to disk.\n#' If specified, the plot will not be displayed interactively, but rather sent\n#' to the appropriate external graphics device (i.e.,\n#' \\code{\\link[grDevices]{png}}, \\code{\\link[grDevices]{jpeg}},\n#' \\code{\\link[grDevices]{pdf}}, or \\code{\\link[grDevices]{svg}}). As a point\n#' of convenience, note that any global parameters held in `(t)par` are\n#' automatically carried over to the external device and don't need to be\n#' reset (in contrast to the conventional base R approach that requires\n#' manually opening and closing the device). The device type is determined by\n#' the file extension at the end of the provided path, and must be one of\n#' \".png\", \".jpg\" (\".jpeg\"), \".pdf\", or \".svg\". (Other file types may be\n#' supported in the future.) The file dimensions can be controlled by the\n#' corresponding `width` and `height` arguments below, otherwise will fall\n#' back to the `\"file.width\"` and `\"file.height\"` values held in\n#' \\code{\\link[tinyplot]{tpar}} (i.e., both defaulting to 7 inches, and where\n#' the default resolution for bitmap files is also specified as 300\n#' DPI).\n#' @param width numeric giving the plot width in inches. Together with `height`,\n#' typically used in conjunction with the `file` argument above, overriding the\n#' default values held in `tpar(\"file.width\", \"file.height\")`. If either `width`\n#' or `height` is specified, but a corresponding `file` argument is not\n#' provided as well, then a new interactive graphics device dimensions will be\n#' opened along the given dimensions. Note that this interactive resizing may\n#' not work consistently from within an IDE like RStudio that has an integrated\n#' graphics windows.\n#' @param height numeric giving the plot height in inches. Same considerations as\n#' `width` (above) apply, e.g. will default to `tpar(\"file.height\")` if not\n#' specified.\n#' @param asp the y/xy/x aspect ratio, see `plot.window`.\n#' @param ... other graphical parameters. If `type` is a character specification\n#' (such as `\"hist\"`) then any argument names that match those from the corresponding\n#' `type_*()` function (such as \\code{\\link{type_hist}}) are passed on to that.\n#' All remaining arguments from `...` can be further graphical parameters, see\n#' \\code{\\link[graphics]{par}}).\n#'\n#' @returns No return value, called for side effect of producing a plot.\n#'\n#' @details\n#' Disregarding the enhancements that it supports, `tinyplot` tries as far as\n#' possible to mimic the behaviour and syntax logic of the original base\n#' \\code{\\link[graphics]{plot}} function. Users should therefore be able to swap\n#' out existing `plot` calls for `tinyplot` (or its shorthand alias `plt`),\n#' without causing unexpected changes to the output.\n#'\n#' @importFrom grDevices axisTicks adjustcolor cairo_pdf colorRampPalette extendrange palette palette.colors palette.pals hcl.colors hcl.pals xy.coords png jpeg pdf svg dev.off dev.new dev.list\n#' @importFrom graphics abline arrows axis Axis axTicks box boxplot grconvertX grconvertY hist lines mtext par plot.default plot.new plot.window points polygon polypath segments rect text title\n#' @importFrom utils modifyList head tail\n#' @importFrom stats na.omit\n#' @importFrom tools file_ext\n#'\n#' @examples\n#' aq = transform(\n#' airquality,\n#' Month = factor(Month, labels = month.abb[unique(Month)])\n#' )\n#'\n#' # In most cases, `tinyplot` should be a drop-in replacement for regular\n#' # `plot` calls. For example:\n#'\n#' op = tpar(mfrow = c(1, 2))\n#' plot(0:10, main = \"plot\")\n#' tinyplot(0:10, main = \"tinyplot\")\n#' tpar(op) # restore original layout\n#'\n#' # Aside: `tinyplot::tpar()` is a (near) drop-in replacement for `par()`\n#'\n#' # Unlike vanilla plot, however, tinyplot allows you to characterize groups\n#' # using either the `by` argument or equivalent `|` formula syntax.\n#'\n#' with(aq, tinyplot(Day, Temp, by = Month)) ## atomic method\n#' tinyplot(Temp ~ Day | Month, data = aq) ## formula method\n#'\n#' # (Notice that we also get an automatic legend.)\n#'\n#' # You can also use the equivalent shorthand `plt()` alias if you'd like to\n#' # save on a few keystrokes\n#'\n#' plt(Temp ~ Day | Month, data = aq) ## shorthand alias\n#'\n#' # Use standard base plotting arguments to adjust features of your plot.\n#' # For example, change `pch` (plot character) to get filled points and `cex`\n#' # (character expansion) to increase their size.\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' pch = 16,\n#' cex = 2\n#' )\n#'\n#' # We can add alpha transparency for overlapping points\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' pch = 16,\n#' cex = 2,\n#' alpha = 0.3\n#' )\n#'\n#' # To get filled points with a common solid background color, use an\n#' # appropriate plotting character (21:25) and combine with one of the special\n#' # `bg` convenience arguments.\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' pch = 21, # use filled circles\n#' cex = 2,\n#' bg = 0.3, # numeric in [0,1] adds a grouped background fill with transparency\n#' col = \"black\" # override default color mapping; give all points a black border\n#' )\n#'\n#' # Converting to a grouped line plot is a simple matter of adjusting the\n#' # `type` argument.\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' type = \"l\"\n#' )\n#'\n#' # Similarly for other plot types, including some additional ones provided\n#' # directly by tinyplot, e.g. density plots or internal plots (ribbons,\n#' # pointranges, etc.)\n#'\n#' tinyplot(\n#' ~ Temp | Month,\n#' data = aq,\n#' type = \"density\",\n#' fill = \"by\"\n#' )\n#'\n#' # Facet plots are supported too. Facets can be drawn on their own...\n#'\n#' tinyplot(\n#' Temp ~ Day,\n#' facet = ~Month,\n#' data = aq,\n#' type = \"area\",\n#' main = \"Temperatures by month\"\n#' )\n#'\n#' # ... or combined/contrasted with the by (colour) grouping.\n#'\n#' aq = transform(aq, Summer = Month %in% c(\"Jun\", \"Jul\", \"Aug\"))\n#' tinyplot(\n#' Temp ~ Day | Summer,\n#' facet = ~Month,\n#' data = aq,\n#' type = \"area\",\n#' palette = \"dark2\",\n#' main = \"Temperatures by month and season\"\n#' )\n#'\n#' # Users can override the default square window arrangement by passing `nrow`\n#' # or `ncol` to the helper facet.args argument. Note that we can also reduce\n#' # axis label repetition across facets by turning the plot frame off.\n#'\n#' tinyplot(\n#' Temp ~ Day | Summer,\n#' facet = ~Month, facet.args = list(nrow = 1),\n#' data = aq,\n#' type = \"area\",\n#' palette = \"dark2\",\n#' frame = FALSE,\n#' main = \"Temperatures by month and season\"\n#' )\n#'\n#' # Use a two-sided formula to arrange the facet windows in a fixed grid.\n#' # LHS -> facet rows; RHS -> facet columns\n#'\n#' aq$hot = ifelse(aq$Temp >= 75, \"hot\", \"cold\")\n#' aq$windy = ifelse(aq$Wind >= 15, \"windy\", \"calm\")\n#' tinyplot(\n#' Temp ~ Day,\n#' facet = windy ~ hot,\n#' data = aq\n#' )\n#'\n#' # To add common elements to each facet, use the `draw` argument\n#'\n#' tinyplot(\n#' Temp ~ Day,\n#' facet = windy ~ hot,\n#' data = aq,\n#' draw = abline(h = 75, lty = 2, col = \"hotpink\")\n#' )\n#'\n#' # The (automatic) legend position and look can be customized using\n#' # appropriate arguments. Note the trailing \"!\" in the `legend` position\n#' # argument below. This tells `tinyplot` to place the legend _outside_ the plot\n#' # area.\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' type = \"l\",\n#' legend = legend(\"bottom!\", title = \"Month of the year\", bty = \"o\")\n#' )\n#'\n#' # The default group colours are inherited from either the \"R4\" or \"Viridis\"\n#' # palettes, depending on the number of groups. However, all palettes listed\n#' # by `palette.pals()` and `hcl.pals()` are supported as convenience strings,\n#' # or users can supply a valid palette-generating function for finer control\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' type = \"l\",\n#' palette = \"tableau\"\n#' )\n#'\n#' # It's possible to customize the look of your plots by setting graphical\n#' # parameters (e.g., via `(t)par`)... But a more convenient way is to just use\n#' # built-in themes (see `?tinytheme`).\n#'\n#' tinytheme(\"clean2\")\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' type = \"b\",\n#' alpha = 0.5,\n#' main = \"Daily temperatures by month\",\n#' sub = \"Brought to you by tinyplot\"\n#' )\n#' # reset the theme\n#' tinytheme()\n#'\n#' # For more examples and a detailed walkthrough, please see the introductory\n#' # tinyplot tutorial available online:\n#' # https://grantmcdermott.com/tinyplot/vignettes/introduction.html\n#'\n#' @rdname tinyplot\n#' @export\ntinyplot =\n function(x, ...) {\n UseMethod(\"tinyplot\")\n }\n\n#' @rdname tinyplot\n#' @export\ntinyplot.default = function(\n x = NULL,\n y = NULL,\n xmin = NULL,\n xmax = NULL,\n ymin = NULL,\n ymax = NULL,\n by = NULL,\n facet = NULL,\n facet.args = NULL,\n data = NULL,\n type = NULL,\n legend = NULL,\n main = NULL,\n sub = NULL,\n xlab = NULL,\n ylab = NULL,\n ann = par(\"ann\"),\n xlim = NULL,\n ylim = NULL,\n axes = TRUE,\n xaxt = NULL,\n yaxt = NULL,\n xaxs = NULL,\n yaxs = NULL,\n xaxb = NULL,\n yaxb = NULL,\n xaxl = NULL,\n yaxl = NULL,\n log = \"\",\n flip = FALSE,\n frame.plot = NULL,\n grid = NULL,\n palette = NULL,\n pch = NULL,\n lty = NULL,\n lwd = NULL,\n col = NULL,\n bg = NULL,\n fill = NULL,\n alpha = NULL,\n cex = 1,\n add = FALSE,\n draw = NULL,\n empty = FALSE,\n restore.par = FALSE,\n file = NULL,\n width = NULL,\n height = NULL,\n asp = NA,\n ...) {\n\n par_first = get_saved_par(\"first\")\n if (is.null(par_first)) set_saved_par(\"first\", par())\n\n assert_logical(add)\n \n # save for tinyplot_add()\n if (!add) {\n calls = sys.calls()\n idx = grep(\"^tinyplot\", sapply(calls, function(k) k[[1]]))\n if (length(idx) > 0) {\n options(tinyplot_last_call = calls[[idx[1]]])\n }\n ## TODO: remove the global option above and move to this when density is refactored\n # cal = match.call(call = sys.call(sys.parent()), expand.dots = TRUE)\n # assign(\".last_call\", cal, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n }\n\n dots = list(...)\n\n if (add) legend = FALSE\n draw = substitute(draw)\n\n\n # sanitize arguments\n\n # type factories vs. strings\n type = sanitize_type(type, x, y, dots)\n if (\"dots\" %in% names(type)) dots = type$dots\n \n # retrieve type-specific data and drawing functions\n type_data = type$data\n type_draw = type$draw\n type = type$name\n \n # area flag (mostly for legend)\n was_area_type = identical(type, \"area\")\n # check flip flag is logical \n assert_flag(flip)\n\n palette = substitute(palette)\n\n # themes\n if (is.null(palette)) palette = get_tpar(\"palette\", default = NULL)\n if (is.null(pch)) pch = get_tpar(\"pch\", default = NULL)\n\n xlabs = ylabs = NULL\n\n # type_ridge()\n ygroup = NULL\n\n # will be overwritten by some type_data() functions and ignored by others\n ribbon.alpha = sanitize_ribbon.alpha(NULL)\n\n ## handle defaults of axes, xaxt, yaxt, frame.plot\n ## - convert axes to character if necessary\n ## - set defaults of xaxt/yaxt (if these are NULL) based on axes\n ## - set logical axes based on xaxt/yaxt\n ## - set frame.plot default based on xaxt/yaxt\n if (isFALSE(axes)) {\n axes = xaxt = yaxt = \"none\"\n } else if (isTRUE(axes)) {\n axes = \"standard\"\n if (is.null(xaxt)) xaxt = get_tpar(\"xaxt\", default = \"standard\")\n if (is.null(yaxt)) yaxt = get_tpar(\"yaxt\", default = \"standard\")\n } else {\n xaxt = yaxt = axes\n }\n axis_types = c(\"standard\", \"none\", \"labels\", \"ticks\", \"axis\")\n axes = match.arg(axes, axis_types)\n xaxt = match.arg(xaxt, axis_types)\n yaxt = match.arg(yaxt, axis_types)\n xaxt = substr(match.arg(xaxt, axis_types), 1L, 1L)\n yaxt = substr(match.arg(yaxt, axis_types), 1L, 1L)\n axes = any(c(xaxt, yaxt) != \"n\")\n if (is.null(frame.plot) || !is.logical(frame.plot)) frame.plot = all(c(xaxt, yaxt) %in% c(\"s\", \"a\"))\n\n # Write plot to output file or window with fixed dimensions\n setup_device(file = file, width = width, height = height)\n if (!is.null(file)) on.exit(dev.off(), add = TRUE)\n\n # Save current graphical parameters\n opar = par(no.readonly = TRUE)\n if (restore.par || !is.null(facet)) {\n if (!is.null(file) || !is.null(width) || !is.null(height)) {\n opar$new = FALSE # catch for some interfaces\n }\n on.exit(par(opar), add = TRUE)\n }\n # set_orig_par(opar)\n set_saved_par(when = \"before\", opar)\n\n # catch for adding to existing facet plot\n if (!is.null(facet) && add) {\n recordGraphics(\n par(get_saved_par(when = \"after\")),\n list = list(),\n env = getNamespace('tinyplot')\n )\n }\n\n # Capture deparsed expressions early, before x, y and by are evaluated\n x_dep = if (!is.null(x)) {\n deparse1(substitute(x))\n } else if (type %in% c(\"rect\", \"segments\")) {\n x = NULL\n NULL\n }\n y_dep = if (is.null(y)) {\n deparse1(substitute(x))\n } else {\n deparse1(substitute(y))\n }\n by_dep = deparse1(substitute(by))\n null_by = is.null(by)\n\n ## coerce character variables to factors\n if (!is.null(x) && is.character(x)) x = factor(x)\n if (!is.null(y) && is.character(y)) y = factor(y)\n if (!null_by && is.character(by)) by = factor(by)\n\n # flag if x==by (currently only used for \"boxplot\", \"spineplot\" and \"ridges\" types)\n x_by = identical(x, by)\n\n facet_dep = deparse1(substitute(facet))\n # flag if facet==by\n facet_by = FALSE\n if (!is.null(facet) && length(facet) == 1 && facet == \"by\") {\n by = as.factor(by) ## if by==facet, then both need to be factors\n facet = by\n facet_by = TRUE\n } else if (!is.null(facet) && inherits(facet, \"formula\")) {\n facet = get_facet_fml(facet, data = data)\n if (isTRUE(attr(facet, \"facet_grid\"))) {\n facet.args[[\"nrow\"]] = attr(facet, \"facet_nrow\")\n }\n }\n facet_attr = attributes(facet) ## TODO: better solution for restoring facet attributes?\n null_facet = is.null(facet)\n\n if (is.null(x)) {\n ## Special catch for rect and segment plots without a specified y-var\n if (type %in% c(\"rect\", \"segments\")) {\n xmin_dep = deparse(substitute(xmin))\n xmax_dep = deparse(substitute(xmax))\n x_dep = paste0(\"[\", xmin_dep, \", \", xmax_dep, \"]\")\n x = rep(NA, length(x))\n }\n }\n if (is.null(y)) {\n ## Special catch for area and interval plots without a specified y-var\n if (type %in% c(\"rect\", \"segments\", \"pointrange\", \"errorbar\", \"ribbon\")) {\n ymin_dep = deparse(substitute(ymin))\n ymax_dep = deparse(substitute(ymax))\n y_dep = paste0(\"[\", ymin_dep, \", \", ymax_dep, \"]\")\n y = rep(NA, length(x))\n } else if (type == \"density\") {\n if (is.null(ylab)) ylab = \"Density\"\n } else if (type == \"function\") {\n if (is.null(ylab)) ylab = \"Frequency\"\n } else if (!(type %in% c(\"histogram\", \"barplot\"))) {\n y = x\n x = seq_along(x)\n if (is.null(xlab)) xlab = \"Index\"\n }\n }\n\n if (is.null(xlab)) xlab = x_dep\n if (is.null(ylab) && type != \"histogram\") ylab = y_dep\n \n # flag(s) indicating whether x/ylim was set by the user (needed later for\n # special case where facets are free but still want to set x/ylim manually)\n xlim_user = !is.null(xlim)\n ylim_user = !is.null(ylim)\n\n # alias\n if (is.null(bg) && !is.null(fill)) bg = fill\n\n datapoints = list(x = x, y = y, xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, ygroup = ygroup)\n datapoints = Filter(function(z) length(z) > 0, datapoints)\n datapoints = data.frame(datapoints)\n if (nrow(datapoints) > 0) {\n datapoints[[\"rowid\"]] = seq_len(nrow(datapoints))\n datapoints[[\"facet\"]] = if (!is.null(facet)) facet else \"\"\n datapoints[[\"by\"]] = if (!null_by) by else \"\"\n }\n\n ## initialize empty list with information that type_data\n ## can overwrite in order to pass on to type_draw\n type_info = list()\n\n if (!is.null(type_data)) {\n fargs = list(\n datapoints = datapoints,\n bg = bg,\n by = by,\n col = col,\n log = log,\n lty = lty,\n lwd = lwd,\n facet = facet,\n facet_by = facet_by,\n facet.args = facet.args,\n null_by = null_by,\n null_facet = null_facet,\n palette = palette,\n ribbon.alpha = ribbon.alpha,\n xaxt = xaxt,\n xaxb = xaxb,\n xaxl = xaxl,\n xlab = xlab,\n xlabs = xlabs,\n xlim = xlim,\n yaxt = yaxt,\n yaxb = yaxb,\n yaxl = yaxl,\n ylab = ylab,\n ylim = ylim\n )\n fargs = c(fargs, dots)\n list2env(do.call(type_data, fargs), environment())\n }\n\n\n # swap x and y values if flip is TRUE\n assert_flag(flip)\n # extra catch for boxplots\n # now swap the values\n if (isTRUE(flip)) {\n if (type != \"boxplot\") {\n # limits, labs, etc.\n xlim_cp = xlim\n xlim = ylim\n ylim = xlim_cp\n xlab_cp = xlab\n xlab = ylab\n ylab = xlab_cp\n xlabs_cp = xlabs\n xlabs = ylabs\n ylabs = xlabs_cp\n xaxt_cp = xaxt\n xaxt = yaxt\n yaxt = xaxt_cp\n xaxs_cp = xaxs\n xaxs = yaxs\n yaxs = xaxs_cp\n xaxb_cp = xaxb\n xaxb = yaxb\n yaxb = xaxb_cp\n xaxl_cp = xaxl\n xaxl = yaxl\n yaxl = xaxl_cp\n if (!is.null(log)) {\n log = if (log == \"x\") \"y\" else if (log == \"y\") \"x\" else log\n }\n # x/y vars\n x_cp = datapoints[[\"x\"]]\n datapoints[[\"x\"]] = datapoints[[\"y\"]]\n datapoints[[\"y\"]] = x_cp\n # x/y min and max vars\n xmin_cp = if (!is.null(datapoints[[\"xmin\"]])) datapoints[[\"xmin\"]] else NULL\n datapoints[[\"xmin\"]] = if (!is.null(datapoints[[\"ymin\"]])) datapoints[[\"ymin\"]] else NULL\n datapoints[[\"ymin\"]] = if (!is.null(xmin_cp)) xmin_cp else NULL\n xmax_cp = if (!is.null(datapoints[[\"xmax\"]])) datapoints[[\"xmax\"]] else NULL\n datapoints[[\"xmax\"]] = if (!is.null(datapoints[[\"ymax\"]])) datapoints[[\"ymax\"]] else NULL\n datapoints[[\"ymax\"]] = if (!is.null(xmax_cp)) xmax_cp else NULL\n # clean up\n rm(xlim_cp, xlab_cp, xlabs_cp, xaxt_cp, xaxs_cp, xaxb_cp, xaxl_cp, x_cp, xmin_cp, xmax_cp)\n } else {\n # We'll let boxplot(..., horizontal = TRUE) handle most of the adjustments\n # and just catch a few elements that we draw beforehand.\n xlab_cp = xlab\n xlab = ylab\n ylab = xlab_cp\n rm(xlab_cp)\n }\n }\n \n # For cases where x/yaxb is provided and corresponding x/ylabs is not null...\n # We can subset these here to provide breaks\n if (!is.null(xaxb) && !is.null(xlabs)) {\n xlabs = xlabs[names(xlabs) %in% xaxb]\n xaxb = NULL # don't need this any more\n }\n if (!is.null(yaxb) && !is.null(ylabs)) {\n ylabs = ylabs[names(ylabs) %in% yaxb]\n yaxb = NULL # don't need this any more\n }\n \n # plot limits\n fargs = lim_args(\n datapoints = datapoints,\n xlim = xlim, ylim = ylim,\n xaxb = xaxb, yaxb = yaxb,\n xlim_user = xlim_user, ylim_user = ylim_user,\n type = type\n )\n list2env(fargs, environment())\n\n\n # split data\n by_ordered = FALSE\n by_continuous = !null_by && inherits(datapoints$by, c(\"numeric\", \"integer\"))\n if (isTRUE(by_continuous) && type %in% c(\"l\", \"b\", \"o\", \"ribbon\", \"polygon\", \"polypath\", \"boxplot\")) {\n warning(\"\\nContinuous legends not supported for this plot type. Reverting to discrete legend.\")\n by_continuous = FALSE\n } else if (!null_by) {\n by_ordered = is.ordered(by)\n }\n\n if (length(unique(datapoints$facet)) == 1) {\n datapoints[[\"facet\"]] = NULL\n }\n if (!is.null(datapoints$facet)) {\n split_data = split(datapoints, datapoints$facet)\n split_data = lapply(split_data, as.list)\n } else {\n split_data = list(as.list(datapoints))\n }\n\n # aesthetics by group: col, bg, etc.\n ngrps = if (null_by) 1L else if (is.factor(by)) length(levels(by)) else if (by_continuous) 100L else length(unique(by))\n pch = by_pch(ngrps = ngrps, type = type, pch = pch)\n lty = by_lty(ngrps = ngrps, type = type, lty = lty)\n lwd = by_lwd(ngrps = ngrps, type = type, lwd = lwd)\n col = by_col(\n ngrps = ngrps, col = col, palette = palette,\n gradient = by_continuous, ordered = by_ordered, alpha = alpha)\n bg = by_bg(\n adjustcolor = adjustcolor, alpha = alpha, bg = bg, by = by, by_continuous = by_continuous,\n by_ordered = by_ordered, col = col, fill = fill, palette = substitute(palette),\n ribbon.alpha = ribbon.alpha, ngrps = ngrps, type = type)\n \n ncolors = length(col)\n lgnd_labs = rep(NA, times = ncolors)\n if (isTRUE(by_continuous)) {\n ## Identify the pretty break points for our labels\n nlabs = 5\n ncolors = length(col)\n ubyvar = unique(by)\n byvar_range = range(ubyvar)\n pbyvar = pretty(byvar_range, n = nlabs)\n pbyvar = pbyvar[pbyvar >= byvar_range[1] & pbyvar <= byvar_range[2]]\n # optional thinning\n if (length(ubyvar) == 2 && all(ubyvar %in% pbyvar)) {\n pbyvar = ubyvar\n } else if (length(pbyvar) > nlabs) {\n pbyvar = pbyvar[seq_along(pbyvar) %% 2 == 0]\n }\n ## Find the (approximate) location of our pretty labels\n pidx = rescale_num(c(byvar_range, pbyvar), to = c(1, ncolors))[-c(1:2)]\n pidx = round(pidx)\n lgnd_labs[pidx] = pbyvar\n }\n\n # Determine the number and arrangement of facets.\n # Note: We're do this up front, so we can make some adjustments to legend cex\n # next (if there are facets). But the actual drawing of the facets will only\n # come later.\n attributes(datapoints$facet) = facet_attr ## TODO: better solution for restoring facet attributes?\n fargs = facet_layout(facet = datapoints$facet, facet.args = facet.args, add = add)\n list2env(fargs, environment())\n\n #\n ## Global plot elements (legend and titles)\n #\n\n # place and draw the legend\n has_legend = FALSE # simple indicator variable for later use\n\n if (!exists(\"legend_args\")) {\n legend_args = dots[[\"legend_args\"]]\n }\n if (is.null(legend_args)) legend_args = list(x = NULL)\n legend = substitute(legend)\n\n if (isFALSE(legend)) {\n legend = \"none\"\n } else if (isTRUE(legend)) {\n legend = NULL\n }\n if (!is.null(legend) && legend == \"none\") {\n legend_args[[\"x\"]] = \"none\"\n }\n\n if (null_by) {\n if (is.null(legend)) {\n legend = \"none\"\n legend_args[[\"x\"]] = \"none\"\n }\n }\n\n if ((is.null(legend) || legend != \"none\") && !add) {\n if (isFALSE(by_continuous)) {\n if (ngrps > 1) {\n lgnd_labs = if (is.factor(datapoints$by)) levels(datapoints$by) else unique(datapoints$by)\n } else {\n lgnd_labs = ylab\n }\n }\n\n has_sub = !is.null(sub)\n\n if (isTRUE(was_area_type) || isTRUE(type %in% c(\"area\", \"rect\", \"hist\", \"histogram\"))) {\n legend_args[[\"pt.lwd\"]] = par(\"lwd\")\n legend_args[[\"lty\"]] = 0\n }\n\n draw_legend(\n legend = legend,\n legend_args = legend_args,\n by_dep = by_dep,\n lgnd_labs = lgnd_labs,\n type = type,\n pch = pch,\n lty = lty,\n lwd = lwd,\n col = col,\n bg = bg,\n gradient = by_continuous,\n cex = cex * cex_fct_adj,\n has_sub = has_sub\n )\n\n has_legend = TRUE\n } else if (legend_args[[\"x\"]] == \"none\" && !add) {\n omar = par(\"mar\")\n ooma = par(\"oma\")\n topmar_epsilon = 0.1\n\n # Catch to avoid recursive offsets, e.g. repeated tinyplot calls with\n # \"bottom!\" legend position.\n\n ## restore inner margin defaults\n ## (in case the plot region/margins were affected by the preceding tinyplot call)\n if (any(ooma != 0)) {\n if (ooma[1] != 0 && omar[1] == par(\"mgp\")[1] + 1 * par(\"cex.lab\")) omar[1] = 5.1\n if (ooma[2] != 0 && omar[2] == par(\"mgp\")[1] + 1 * par(\"cex.lab\")) omar[2] = 4.1\n if (ooma[3] == topmar_epsilon && omar[3] != 4.1) omar[3] = 4.1\n if (ooma[4] != 0 && omar[4] == 0) omar[4] = 2.1\n par(mar = omar)\n }\n ## restore outer margin defaults (with a catch for custom mfrow plots)\n if (all(par(\"mfrow\") == c(1, 1))) {\n par(omd = c(0, 1, 0, 1))\n }\n\n # clean up for now\n rm(omar, ooma, topmar_epsilon)\n\n # Draw new plot\n plot.new()\n }\n\n # Titles. Only draw these if add = FALSE\n if (!add) {\n # main title\n # Note that we include a special catch for the main title if legend is\n # \"top!\" (and main is specified in the first place).\n legend_eval = tryCatch(eval(legend), error = function(e) NULL)\n # Extra bit of footwork if user passed legend = legend(...) instead of\n # legend = list(...), since the call environment is tricky\n if (is.null(legend_eval)) {\n legend_eval = tryCatch(paste0(legend)[[2]], error = function(e) NULL)\n }\n\n adj_title = !is.null(legend) && (legend == \"top!\" || (!is.null(legend_args[[\"x\"]]) && legend_args[[\"x\"]] == \"top!\") || (is.list(legend_eval) && legend_eval[[1]] == \"top!\"))\n\n # For the \"top!\" legend case, bump main title up to make space for the\n # legend beneath it: Take the normal main title line gap (i.e., 1.7 lines)\n # and add the difference between original top margin and new one (i.e.,\n # which should equal the height of the new legend). Note that we also\n # include a 0.1 epsilon bump, which we're using to reset the tinyplot\n # window in case of recursive \"top!\" calls. (See draw_legend code.)\n\n if (isTRUE(adj_title)) {\n line_main = par(\"mar\")[3] - opar[[\"mar\"]][3] + 1.7 + 0.1\n } else {\n line_main = NULL\n }\n\n if (!is.null(sub)) {\n if (isTRUE(get_tpar(\"side.sub\", 1) == 3)) {\n if (is.null(line_main)) line_main = par(\"mgp\")[3] + 1.7 - .1\n line_main = line_main + 1.2\n }\n if (isTRUE(get_tpar(\"side.sub\", 1) == 3)) {\n line_sub = get_tpar(\"line.sub\", 1.7)\n } else {\n line_sub = get_tpar(\"line.sub\", 4)\n }\n args = list(\n text = sub,\n line = line_sub,\n cex = get_tpar(\"cex.sub\", 1.2),\n col = get_tpar(\"col.sub\", \"black\"),\n adj = get_tpar(c(\"adj.sub\", \"adj\")),\n font = get_tpar(\"font.sub\", 1),\n side = get_tpar(\"side.sub\", 1),\n las = 1\n )\n args = Filter(function(x) !is.null(x), args)\n do.call(mtext, args)\n }\n\n if (!is.null(main)) {\n args = list(\n main = main,\n line = line_main,\n cex.main = get_tpar(\"cex.main\", 1.4),\n col.main = get_tpar(\"col.main\", \"black\"),\n font.main = get_tpar(\"font.main\", 2),\n adj = get_tpar(c(\"adj.main\", \"adj\"), 3))\n args = Filter(function(x) !is.null(x), args)\n do.call(title, args)\n }\n\n\n # Axis titles\n args = list(xlab = xlab)\n args[[\"adj\"]] = get_tpar(c(\"adj.xlab\", \"adj\"))\n do.call(title, args)\n args = list(ylab = ylab)\n args[[\"adj\"]] = get_tpar(c(\"adj.ylab\", \"adj\"))\n do.call(title, args)\n }\n\n #\n ## Exterior plot elements (plot and facet windows, axes, etc.)\n #\n\n omar = NULL # Placeholder variable for now, which we re-assign as part of facet margins\n\n # placeholders for facet_window_args() call\n facet_newlines = facet_text = facet_rect = facet_font = facet_col = facet_bg = facet_border = NULL\n\n if (!is.null(facet) && !add) {\n if (is.null(omar)) omar = par(\"mar\")\n\n # Grab some of the customizable facet args that we'll be using later\n facet_rect = FALSE\n facet_text = .tpar[[\"facet.cex\"]]\n facet_font = .tpar[[\"facet.font\"]]\n facet_col = .tpar[[\"facet.col\"]]\n facet_bg = .tpar[[\"facet.bg\"]]\n facet_border = .tpar[[\"facet.border\"]]\n if (!is.null(facet.args)) {\n if (!is.null(facet.args[[\"cex\"]])) facet_text = facet.args[[\"cex\"]]\n if (!is.null(facet.args[[\"col\"]])) facet_col = facet.args[[\"col\"]]\n if (!is.null(facet.args[[\"font\"]])) facet_font = facet.args[[\"font\"]]\n if (!is.null(facet.args[[\"bg\"]])) facet_bg = facet.args[[\"bg\"]]\n if (!is.null(facet.args[[\"border\"]])) facet_border = facet.args[[\"border\"]]\n }\n if (!is.null(facet_bg) || !is.null(facet_border)) facet_rect = TRUE\n\n # Need extra adjustment to top margin if facet titles have \"\\n\" newline\n # separator. (Note that we'll also need to take account for this in the\n # individual facet margins / gaps further below.)\n facet_newlines = lengths(gregexpr(\"\\n\", grep(\"\\\\n\", facets, value = TRUE)))\n # if (length(facet_newlines)==0) facet_newlines = 0\n # omar[3] = omar[3] + max(facet_newlines)\n facet_newlines = ifelse(length(facet_newlines) == 0, 0, max(facet_newlines))\n omar[3] = omar[3] + facet_newlines * facet_text / cex_fct_adj\n # apply the changes\n par(mar = omar)\n }\n\n # Now draw the individual facet windows (incl. axes, grid lines, and facet titles)\n # Will be skipped if adding to an existing plot; see ?facet\n\n facet_window_args = recordGraphics(\n draw_facet_window(\n add = add,\n # facet-specific args\n cex_fct_adj = cex_fct_adj,\n facet.args = facet.args,\n facet_newlines = facet_newlines, facet_font = facet_font,\n facet_rect = facet_rect, facet_text = facet_text,\n facet_col = facet_col, facet_bg = facet_bg, facet_border = facet_border,\n facet = facet,\n facets = facets, ifacet = ifacet,\n nfacets = nfacets, nfacet_cols = nfacet_cols, nfacet_rows = nfacet_rows,\n # axes args\n axes = axes, flip = flip, frame.plot = frame.plot,\n oxaxis = oxaxis, oyaxis = oyaxis,\n xlabs = xlabs, xlim = xlim, xlim_user = xlim_user, xaxt = xaxt, xaxs = xaxs, xaxb = xaxb, xaxl = xaxl,\n ylabs = ylabs, ylim = ylim, ylim_user = ylim_user, yaxt = yaxt, yaxs = yaxs, yaxb = yaxb, yaxl = yaxl,\n asp = asp, log = log,\n # other args (in approx. alphabetical + group ordering)\n dots = dots,\n draw = draw,\n grid = grid,\n has_legend = has_legend,\n type = type,\n x = x, xmax = xmax, xmin = xmin,\n y = y, ymax = ymax, ymin = ymin\n ),\n list = list(\n add = add,\n cex_fct_adj = cex_fct_adj,\n facet.args = facet.args,\n facet_newlines = facet_newlines, facet_font = facet_font,\n facet_rect = facet_rect, facet_text = facet_text,\n facet_col = facet_col, facet_bg = facet_bg, facet_border = facet_border,\n facet = datapoints$facet,\n facets = facets, ifacet = ifacet,\n nfacets = nfacets, nfacet_cols = nfacet_cols, nfacet_rows = nfacet_rows,\n axes = axes, flip = flip, frame.plot = frame.plot,\n oxaxis = oxaxis, oyaxis = oyaxis,\n xlabs = xlabs, xlim = xlim, xlim_user = xlim_user, xaxt = xaxt, xaxs = xaxs, xaxb = xaxb, xaxl = xaxl,\n ylabs = ylabs, ylim = ylim, ylim_user = ylim_user, yaxt = yaxt, yaxs = yaxs, yaxb = yaxb, yaxl = yaxl,\n asp = asp, log = log,\n dots = dots,\n draw = draw,\n grid = grid,\n has_legend = has_legend,\n type = type,\n x = datapoints$x, xmax = datapoints$xmax, xmin = datapoints$xmin,\n y = datapoints$y, ymax = datapoints$ymax, ymin = datapoints$ymin\n ),\n getNamespace(\"tinyplot\")\n )\n list2env(facet_window_args, environment())\n\n\n #\n ## Interior plot elements\n #\n\n # Finally, we can draw all of the plot elements (points, lines, etc.)\n # We'll do this via a nested loops:\n # 1) Outer loop over facets\n # 2) Inner loop over groups\n\n ## Outer loop over the facets\n for (i in seq_along(split_data)) {\n # Split group-level data again to grab any \"by\" groups\n idata = split_data[[i]]\n iby = idata[[\"by\"]]\n if (!null_by) { ## maybe all(iby==\"\")\n if (isTRUE(by_continuous)) {\n idata[[\"col\"]] = col[round(rescale_num(idata$by, from = range(datapoints$by), to = c(1, 100)))]\n idata[[\"bg\"]] = bg[round(rescale_num(idata$by, from = range(datapoints$by), to = c(1, 100)))]\n idata = list(idata)\n } else {\n idata = lapply(idata, split, iby)\n idata = do.call(function(...) Map(\"list\", ...), idata)\n }\n } else {\n idata = list(idata)\n if (isTRUE(by_continuous)) {\n if (length(col) != 1) {\n idata[[1]][[\"col\"]] = col[round(rescale_num(by, to = c(1, 100)))]\n } else {\n idata[[1]][[\"col\"]] = col\n }\n if (length(bg) != 1) {\n idata[[1]][[\"bg\"]] = bg[round(rescale_num(by, to = c(1, 100)))]\n } else {\n idata[[1]][[\"bg\"]] = bg\n }\n }\n }\n \n # Set the facet \"window\" manually\n # See: https://github.com/grantmcdermott/tinyplot/issues/65\n if (nfacets > 1) {\n mfgi = ceiling(i / nfacet_cols)\n mfgj = i %% nfacet_cols\n if (mfgj == 0) mfgj = nfacet_cols\n par(mfg = c(mfgi, mfgj))\n\n # For free facets, we need to reset par(usr) based extent of that\n # particular facet... which we calculated and saved to the .fusr env var\n # (list) back in draw_facet_window()\n if (isTRUE(facet.args[[\"free\"]])) {\n fusr = get(\".fusr\", envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n par(usr = fusr[[i]])\n }\n }\n\n\n ## Inner loop over the \"by\" groupings\n for (ii in seq_along(idata)) {\n icol = col[ii]\n ibg = bg[ii]\n ipch = pch[ii]\n ilty = lty[ii]\n ilwd = lwd[ii]\n \n ix = idata[[ii]][[\"x\"]]\n iy = idata[[ii]][[\"y\"]]\n iz = idata[[ii]][[\"z\"]]\n ixmin = idata[[ii]]$xmin\n ixmax = idata[[ii]]$xmax\n iymin = idata[[ii]]$ymin\n iymax = idata[[ii]]$ymax\n ilabels = idata[[ii]][[\"labels\"]]\n\n if (isTRUE(by_continuous)) {\n icol = idata[[ii]]$col\n ibg = idata[[ii]]$bg\n }\n\n # empty plot flag\n empty_plot = FALSE\n if (isTRUE(empty) || isTRUE(type == \"n\") || ((length(ix) == 0) && !(type %in% c(\"histogram\", \"hist\", \"rect\", \"segments\", \"spineplot\")))) {\n empty_plot = TRUE\n }\n\n # Draw the individual plot elements...\n if (!isTRUE(empty_plot)) {\n if (is.null(type_draw)) {\n type_draw = switch(type,\n \"ribbon\" = type_ribbon()$draw,\n \"polygon\" = type_polygon()$draw,\n \"rect\" = type_rect()$draw,\n \"p\" = ,\n \"points\" = type_points()$draw,\n \"l\" = ,\n \"o\" = ,\n \"b\" = ,\n \"c\" = ,\n \"h\" = ,\n \"s\" = ,\n \"S\" = type_lines(type = type)$draw\n )\n }\n type_draw(\n ibg = ibg,\n icol = icol,\n ilty = ilty,\n ilwd = ilwd,\n ipch = ipch,\n ix = ix,\n ixmax = ixmax,\n ixmin = ixmin,\n iy = iy,\n iymax = iymax,\n iymin = iymin,\n ilabels = ilabels,\n iz = iz,\n cex = cex,\n dots = dots,\n type = type,\n x_by = x_by,\n by_continuous = by_continuous,\n iby = ii,\n ifacet = i,\n facet_by = facet_by,\n data_facet = idata,\n ngrps = ngrps,\n nfacets = nfacets,\n flip = flip,\n type_info = type_info,\n facet_window_args = facet_window_args\n )\n }\n }\n }\n \n if (!add) {\n # save end pars for possible recall later\n recordGraphics(\n {\n apar = par(no.readonly = TRUE)\n set_saved_par(when = \"after\", apar)\n },\n list = list(), \n env = getNamespace('tinyplot')\n )\n }\n\n}\n\n\n\n\n#' @rdname tinyplot\n#' @importFrom stats as.formula model.frame terms\n#' @export\ntinyplot.formula = function(\n x = NULL,\n data = parent.frame(),\n facet = NULL,\n facet.args = NULL,\n type = NULL,\n xmin = NULL,\n xmax = NULL,\n ymin = NULL,\n ymax = NULL,\n xlim = NULL,\n ylim = NULL,\n # log = \"\",\n main = NULL,\n sub = NULL,\n xlab = NULL,\n ylab = NULL,\n ann = par(\"ann\"),\n axes = TRUE,\n frame.plot = NULL,\n asp = NA,\n grid = NULL,\n pch = NULL,\n col = NULL,\n lty = NULL,\n lwd = NULL,\n restore.par = FALSE,\n formula = NULL,\n subset = NULL,\n na.action = NULL,\n drop.unused.levels = TRUE,\n ...) {\n ## formula for variables must be specified through 'x' or 'formula' but not both\n if (is.null(x)) {\n if (missing(formula)) {\n stop(\"plot formula must be specified by either 'x' or 'formula' argument\")\n }\n } else {\n if (missing(formula)) {\n formula = x\n } else {\n warning(\"only one of the arguments 'x' and 'formula' should be specified, defaulting to the 'formula' argument\")\n }\n }\n\n ## placeholder for legend title\n legend_args = list(x = NULL)\n\n ## turn facet into a formula if it does not evaluate successfully\n if (inherits(try(facet, silent = TRUE), \"try-error\")) {\n facet = as.formula(paste(\"~\", deparse(substitute(facet))))\n environment(facet) = environment(formula)\n }\n\n ## process all formulas\n tf = tinyformula(formula, facet)\n\n ## set up model frame\n m = match.call(expand.dots = FALSE)\n m = m[c(1L, match(c(\"formula\", \"data\", \"subset\", \"na.action\", \"drop.unused.levels\", \"xmin\", \"xmax\", \"ymin\", \"ymax\"), names(m), 0L))]\n m$formula = tf$full\n ## need stats:: for non-standard evaluation\n m[[1L]] = quote(stats::model.frame)\n mf = eval.parent(m)\n\n ## extract x\n x = tinyframe(tf$x, mf)\n xnam = names(x)[[1L]]\n if (length(names(x)) != 1L) warning(\n paste(\"formula should specify exactly one x-variable, using:\", xnam),\n \"\\nif you want to use arithmetic operators, make sure to wrap them inside I()\")\n x = x[[xnam]]\n\n ## extract y (if any)\n y = tinyframe(tf$y, mf)\n if (!is.null(y)) {\n ynam = names(y)[[1L]]\n if (length(names(y)) > 1L) warning(paste(\"formula should specify at most one y-variable, using:\", ynam),\n \"\\nif you want to use arithmetic operators, make sure to wrap them inside I()\")\n y = y[[ynam]]\n }\n\n ## extract by (if any)\n by = tinyframe(tf$by, mf)\n if (!is.null(by)) {\n bynam = names(by)\n by = if (length(bynam) == 1L) by[[bynam]] else interaction(by, sep = \":\")\n }\n\n ## extract x/y facet (if formula)\n if (!is.null(tf$xfacet) || !is.null(tf$yfacet)) {\n xfacet = tinyframe(tf$xfacet, mf)\n yfacet = tinyframe(tf$yfacet, mf)\n if (!is.null(xfacet)) xfacet = if (ncol(xfacet) == 1L) xfacet[[1L]] else interaction(xfacet, sep = \":\")\n if (!is.null(yfacet)) yfacet = if (ncol(yfacet) == 1L) yfacet[[1L]] else interaction(yfacet, sep = \":\")\n if (is.null(yfacet)) {\n facet = xfacet\n } else {\n facet = interaction(xfacet, yfacet, sep = \"~\")\n attr(facet, \"facet_grid\") = TRUE\n attr(facet, \"facet_nrow\") = length(unique(yfacet))\n }\n }\n\n ## nice axis and legend labels\n dens_type = (is.atomic(type) && identical(type, \"density\")) || (!is.atomic(type) && identical(type$name, \"density\"))\n hist_type = (is.atomic(type) && type %in% c(\"hist\", \"histogram\")) || (!is.atomic(type) && identical(type$name, \"histogram\"))\n if (!is.null(type) && dens_type) {\n # if (is.null(ylab)) ylab = \"Density\" ## rather assign ylab as part of internal type_density() logic\n if (is.null(xlab)) xlab = xnam\n } else if (!is.null(type) && hist_type) {\n # if (is.null(ylab)) ylab = \"Frequency\" ## rather assign ylab as part of internal type_histogram() logic\n if (is.null(xlab)) xlab = xnam\n } else if (is.null(y)) {\n if (is.null(ylab)) ylab = xnam\n if (is.null(xlab)) xlab = \"Index\"\n } else {\n if (is.null(ylab)) ylab = ynam\n if (is.null(xlab)) xlab = xnam\n }\n if (!is.null(by)) {\n legend_args[[\"title\"]] = if (length(bynam) == 1L) bynam else sprintf(\"interaction(%s)\", paste(bynam, collapse = \", \"))\n }\n\n tinyplot.default(\n x = x, y = y, by = by,\n facet = facet, facet.args = facet.args,\n data = data,\n type = type,\n xmin = mf[[\"(xmin)\"]],\n xmax = mf[[\"(xmax)\"]],\n ymin = mf[[\"(ymin)\"]],\n ymax = mf[[\"(ymax)\"]],\n xlim = xlim,\n ylim = ylim,\n # log = \"\",\n main = main,\n sub = sub,\n xlab = xlab,\n ylab = ylab,\n ann = ann,\n axes = axes,\n frame.plot = frame.plot,\n asp = asp,\n grid = grid,\n legend_args = legend_args,\n pch = pch,\n col = col,\n lty = lty,\n lwd = lwd,\n restore.par = restore.par,\n ...\n )\n}\n\n#' @rdname tinyplot\n#' @export\ntinyplot.density = function(\n x = NULL,\n type = c(\"l\", \"area\"),\n ...) {\n \n dots = list(...)\n \n if (!is.null(dots[[\"by\"]]) || !is.null(dots[[\"facet\"]])) {\n stop(\n '\\nGrouped and/or faceted plots are no longer supported with the tinyplot.density() method. ',\n '\\nPlease use the dedicated type argument instead, e.g. `tinyplot(..., type = \"density\")`. See `?type_density` for details.',\n '\\n\\nThis breaking change was introduced in tinyplot v0.3.0.'\n )\n }\n \n type = match.arg(type)\n \n ## override if bg = \"by\"\n if (!is.null(dots[[\"bg\"]]) || !is.null(dots[[\"fill\"]])) type = \"area\"\n \n if (inherits(x, \"density\")) {\n object = x\n # legend_args = list(x = NULL)\n # # Grab by label to pass on legend title to tinyplot.default\n # legend_args[[\"title\"]] = deparse(substitute(by))\n } else {\n ## An internal catch for non-density objects that were forcibly\n ## passed to tinyplot.density (e.g., via a one-side formula)\n if (anyNA(x)) {\n x = na.omit(x)\n x = as.numeric(x)\n }\n object = density(x)\n }\n \n x = object$x\n y = object$y\n \n if (type == \"area\") {\n ymin = rep(0, length(y))\n ymax = y\n # # set extra legend params to get bordered boxes with fill\n # legend_args[[\"x.intersp\"]] = 1.25\n # legend_args[[\"lty\"]] = 0\n # legend_args[[\"pt.lwd\"]] = 1\n }\n \n # splice in change arguments\n dots[[\"x\"]] = x\n dots[[\"y\"]] = y\n dots[[\"type\"]] = type\n \n ## axes range\n if (is.null(dots[[\"xlim\"]])) dots[[\"xlim\"]] = range(x)\n if (is.null(dots[[\"ylim\"]])) dots[[\"ylim\"]] = range(y)\n \n ## nice labels and titles\n if (is.null(dots[[\"ylab\"]])) dots[[\"ylab\"]] = \"Density\"\n if (is.null(dots[[\"xlab\"]])) dots[[\"xlab\"]] = paste0(\"N = \", object$n, \" Bandwidth = \", sprintf(\"%.4g\", object$bw))\n if (is.null(dots[[\"main\"]])) dots[[\"main\"]] = paste0(paste(object$call, collapse = \"(x = \"), \")\")\n \n do.call(tinyplot.default, args = dots)\n \n}\n\n\n#' @export\n#' @name plt\n#' @rdname tinyplot\nplt = tinyplot\n"], ["/tinyplot/R/type_spineplot.R", "#' Spineplot and spinogram types\n#'\n#' @description Type function(s) for producing spineplots and spinograms, which\n#' are modified versions of histograms or mosaic plots, and particularly\n#' useful for visualizing factor variables. Note that [`tinyplot`] defaults\n#' to `type_spineplot()` if `y` is a factor variable.\n#' @param xlevels,ylevels a character or numeric vector specifying the ordering of the\n#' levels of the `x` and `y` variables (if character) or the corresponding indexes\n#' (if numeric) for the plot.\n#' @inheritParams graphics::spineplot\n#' @examples\n#' # \"spineplot\" type convenience string\n#' tinyplot(Species ~ Sepal.Width, data = iris, type = \"spineplot\")\n#' \n#' # Aside: specifying the type is redundant for this example, since tinyplot()\n#' # defaults to \"spineplot\" if y is a factor (just like base plot).\n#' tinyplot(Species ~ Sepal.Width, data = iris)\n#' \n#' # Use `type_spineplot()` to pass extra arguments for customization\n#' tinyplot(Species ~ Sepal.Width, data = iris, type = type_spineplot(breaks = 4))\n#' \n#' p = palette.colors(3, \"Pastel 1\")\n#' tinyplot(Species ~ Sepal.Width, data = iris, type = type_spineplot(breaks = 4, col = p))\n#' rm(p)\n#' \n#' # More idiomatic tinyplot way of drawing the previous plot: use y == by\n#' tinyplot(\n#' Species ~ Sepal.Width | Species, data = iris, type = type_spineplot(breaks = 4),\n#' palette = \"Pastel 1\", legend = FALSE\n#' )\n#' \n#' # Grouped and faceted spineplots\n#' \n#' ttnc = as.data.frame(Titanic)\n#' \n#' tinyplot(\n#' Survived ~ Sex, facet = ~ Class, data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq)\n#' )\n#' \n#' # For grouped \"by\" spineplots, it's better visually to facet as well\n#' tinyplot(\n#' Survived ~ Sex | Class, facet = \"by\", data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq)\n#' )\n#' \n#' # Fancier version. Note the smart inheritance of spacing etc.\n#' tinyplot(\n#' Survived ~ Sex | Class, facet = \"by\", data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq),\n#' palette = \"Dark 2\", facet.args = list(nrow = 1), axes = \"t\"\n#' )\n#'\n#' # Reorder x and y variable categories either by their character levels or numeric indexes\n#' tinyplot(\n#' Survived ~ Sex, facet = ~ Class, data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq, xlevels = c(\"Female\", \"Male\"), ylevels = 2:1)\n#' )\n#'\n#' # Note: It's possible to use \"by\" on its own (without faceting), but the\n#' # overlaid result isn't great. We will likely overhaul this behaviour in a\n#' # future version of tinyplot...\n#' tinyplot(Survived ~ Sex | Class, data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq), alpha = 0.3\n#' )\n#' \n#' @export\ntype_spineplot = function(breaks = NULL, tol.ylab = 0.05, off = NULL, xlevels = NULL, ylevels = NULL, col = NULL, xaxlabels = NULL, yaxlabels = NULL, weights = NULL) {\n col = col\n out = list(\n data = data_spineplot(off = off, breaks = breaks, xlevels = xlevels, ylevels = ylevels, xaxlabels = xaxlabels, yaxlabels = yaxlabels, weights = weights),\n draw = draw_spineplot(tol.ylab = tol.ylab, off = off, col = col, xaxlabels = xaxlabels, yaxlabels = yaxlabels),\n name = \"spineplot\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n#' @importFrom grDevices nclass.Sturges\ndata_spineplot = function(off = NULL, breaks = NULL, xlevels = xlevels, ylevels = ylevels, xaxlabels = NULL, yaxlabels = NULL, weights = NULL) {\n fun = function(\n datapoints,\n by = NULL, col = NULL, bg = NULL, palette = NULL,\n facet = NULL, facet.args = NULL,\n xlim = NULL, ylim = NULL,\n axes = TRUE, xaxt = NULL, yaxt = NULL, xaxb = NULL, yaxb = NULL,\n null_by, null_facet, \n ...\n ) {\n \n ## process weights\n if (!is.null(weights)) {\n ny = length(datapoints$y)\n if (length(weights) != ny && length(weights) != 1L) {\n stop(sprintf(\"'weights' must have either length 1 or %s\", ny))\n }\n }\n datapoints$weights = weights\n \n ## process x variable\n if (is.factor(datapoints$x)) {\n breaks = NULL\n off = if(is.null(off)) 0.02 else off/100\n if (is.null(xlim)) xlim = c(0, 1 + (nlevels(datapoints$x) - 1L) * off)\n } else {\n off = 0\n if (is.null(xlim)) xlim = c(0, 1)\n \t x = as.numeric(datapoints$x)\n if (is.null(breaks)) {\n breaks = if (!is.null(xaxb)) xaxb else if (is.null(weights)) nclass.Sturges(x) else ceiling(log2(sum(weights)) + 1)\n\t }\n breaks = as.numeric(breaks)\n if (length(breaks) == 1L) {\n if (!is.numeric(breaks) || !is.finite(breaks) || breaks < 1L) stop(\"invalid number of 'breaks'\")\n if (breaks > 1e6) {\n warning(gettextf(\"'breaks = %g' is too large and set to 1e6\", breaks))\n breaks = 1000000L\n }\n rg = if (is.null(weights)) range(x, na.rm = TRUE) else range(x[weights > 0], na.rm = TRUE)\n breaks = pretty(rg, n = breaks, min.n = 1L) \n }\n }\n\n ## process y variable\n if (!is.factor(datapoints$y)) datapoints$y = factor(datapoints$y)\n if (is.null(ylim)) ylim = c(0, 1)\n\n ## adjust facet margins\n if (!is.null(facet) && is.null(facet.args[[\"fmar\"]])) {\n facet.args[[\"fmar\"]] = c(2, 2, 2, 2)\n }\n \n x_by = identical(datapoints$x, datapoints$by)\n y_by = identical(datapoints$y, datapoints$by)\n \n x.categorical = is.factor(datapoints$x)\n if (!is.null(xlevels) && x.categorical) {\n xlevels = if(is.numeric(xlevels)) levels(datapoints$x)[xlevels] else xlevels\n if (any(is.na(xlevels)) || !all(xlevels %in% levels(datapoints$x))) warning(\"not all 'xlevels' correspond to levels of 'x'\")\n datapoints$x = factor(datapoints$x, levels = xlevels)\n if (x_by) datapoints$by = datapoints$x\n }\n if (!is.null(ylevels)) {\n ylevels = if(is.numeric(ylevels)) levels(datapoints$y)[ylevels] else ylevels\n if (any(is.na(ylevels)) || !all(ylevels %in% levels(datapoints$y))) warning(\"not all 'ylevels' correspond to levels of 'y'\")\n datapoints$y = factor(datapoints$y, levels = ylevels)\n if (y_by) datapoints$by = datapoints$y\n }\n \n x = datapoints$x\n y = datapoints$y\n \n # if either x_by or y_by are TRUE, we'll only split by facets and then\n # use some simple logic to assign colouring on the backend\n if (isTRUE(x_by) || isTRUE(y_by)) {\n datapoints = split(datapoints, list(datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n } else {\n datapoints = split(datapoints, list(datapoints$by, datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n }\n \n # construct spineplot rectangles and breaks points for each by-facet combo\n datapoints = Map(function(dat, x.categorical, off) {\n ## set up frequency table\n x = dat$x\n if(!x.categorical) {\n x = cut(as.numeric(x), breaks = breaks, include.lowest = TRUE)\n }\n ## TODO: process by grouping via: interaction + spacing + labeling\n ## (for now just do interaction)\n ## FIXME: data_facet only contains the first by group?\n ## if (any(dat$by != \"\")) x = interaction(dat$by, x)\n if(is.null(dat$weights)) {\n tab = table(x, dat$y)\n } else {\n tab = as.table(tapply(dat$weights, list(x, dat$y), FUN = sum, na.rm = TRUE))\n tab[is.na(tab)] = 0\n }\n nx = nrow(tab)\n ny = ncol(tab)\n \n ## compute coordinates\n ## cumulative proportions of x (plus off) vs. conditional cumulative proportions of y\n yat = rbind(0, apply(proportions(tab[, ny:1L, drop = FALSE], 1L), 1L, cumsum))\n yat[is.na(yat)] = 1\n xat = c(0, cumsum(proportions(marginSums(tab, 1L)) + off))\n \n ybottom = as.vector(yat[-(ny + 1L),])\n ytop = as.vector(yat[-1L,])\n xleft = rep(xat[1L:nx], rep(ny, nx))\n xright = rep(xat[2L:(nx+1L)] - off, rep(ny, nx))\n \n out = data.frame(\n by = dat$by[1], # already split\n facet = dat$facet[1], # already split\n ymin = ybottom,\n ymax = ytop,\n xmin = xleft,\n xmax = xright\n )\n \n attr(out, \"nx\") = nx\n attr(out, \"ny\") = ny\n attr(out, \"xat\") = xat\n attr(out, \"yat\") = yat\n return(out)\n }, \n dat = datapoints,\n x.categorical = x.categorical,\n off = off\n )\n \n nx = attr(datapoints[[1]], \"nx\") ## should be the same for all by/facet groups\n ny = attr(datapoints[[1]], \"ny\") ## ditto\n xat = lapply(datapoints, attr, \"xat\")\n yat = lapply(datapoints, attr, \"yat\")\n datapoints = do.call(rbind, datapoints)\n \n if (is.null(yaxlabels)) yaxlabels = rev(levels(y))\n \n ## axis labels\n yaxlabels = if(is.null(yaxlabels)) levels(y) else rep_len(yaxlabels, ny)\n if (!is.null(yaxb)) {\n # yaxlabels = yaxlabels[yaxlabels %in% yaxb]\n ## rather use the \"\" assignment workaround below, since otherwise we \n ## get a mismatch between the label names and ticks \n yaxlabels[!(yaxlabels %in% yaxb)] = \"\"\n }\n if(x.categorical) {\n xaxlabels = if(is.null(xaxlabels)) {\n levels(x)\n } else {\n rep_len(xaxlabels, nx)\n }\n } else {\n xaxlabels = if(is.null(xaxlabels)) {\n if(is.numeric(x)) breaks else c(x[1L], x[c(diff(as.numeric(x)) > 0, TRUE)])\n } else {\n rep_len(xaxlabels, nx + 1L)\n }\n }\n \n # catch for x_by / y/by\n if (isTRUE(x_by)) datapoints$by = factor(rep(xaxlabels, each = ny)) # each x label extends over ny rows\n if (isTRUE(y_by)) datapoints$by = factor(rep(yaxlabels, length.out = nrow(datapoints)))\n \n ## grayscale flag\n grayscale = null_by && is.null(palette) && is.null(.tpar[[\"palette.qualitative\"]])\n \n out = list(\n x = c(datapoints$xmin, datapoints$xmax), \n y = c(datapoints$ymin, datapoints$ymax),\n ymin = datapoints$ymin, \n ymax = datapoints$ymax, \n xmin = datapoints$xmin, \n xmax = datapoints$xmax, \n col = col,\n bg = bg,\n datapoints = datapoints,\n by = if (null_by) by else datapoints$by, \n facet = if (null_facet) facet else datapoints$facet,\n axes = FALSE,\n frame.plot = FALSE,\n xaxt = \"n\",\n yaxt = \"n\",\n xaxs = \"i\",\n yaxs = \"i\",\n ylabs = yaxlabels,\n type_info = list(\n off = off,\n x.categorical = x.categorical,\n nx = nx,\n ny = ny,\n xat = xat,\n yat = yat,\n xaxlabels = xaxlabels,\n yaxlabels = yaxlabels,\n breaks = breaks,\n axes = axes,\n xaxt = xaxt, \n yaxt = yaxt,\n grayscale = grayscale,\n x_by = x_by,\n y_by = y_by\n ),\n facet.args = facet.args\n )\n \n return(out)\n \n }\n return(fun)\n}\n\n#' @importFrom grDevices gray.colors\ndraw_spineplot = function(tol.ylab = 0.05, off = NULL, col = NULL, xaxlabels = NULL, yaxlabels = NULL) {\n fun = function(ixmin, iymin, ixmax, iymax, ilty, ilwd, icol, ibg, \n flip,\n facet_window_args,\n type_info,\n ifacet,\n ...) {\n \n if (is.null(off)) off = type_info[[\"off\"]]\n if (is.null(xaxlabels)) xaxlabels = type_info[[\"xaxlabels\"]]\n if (is.null(yaxlabels)) yaxlabels = type_info[[\"yaxlabels\"]]\n xat = type_info[[\"xat\"]][[ifacet]]\n yat = type_info[[\"yat\"]][[ifacet]]\n nx = type_info[[\"nx\"]]\n ny = type_info[[\"ny\"]]\n x.categorical = type_info[[\"x.categorical\"]]\n grayscale = type_info[[\"grayscale\"]]\n x_by = type_info[[\"x_by\"]]\n y_by = type_info[[\"y_by\"]]\n \n ## graphical parameters\n if (is.null(col)) {\n if (is.null(ibg)) ibg = icol\n if (isFALSE(y_by)) {\n ibg = if (isTRUE(grayscale)) gray.colors(ny) else seq_palette(ibg, ny)\n }\n ibg = rep_len(ibg, ny)\n } else {\n ibg = col\n }\n \n if (type_info[[\"xaxt\"]] %in% c(\"l\", \"t\", \"n\") &&\n type_info[[\"yaxt\"]] %in% c(\"l\", \"t\", \"n\") &&\n !all(c(type_info[[\"xaxt\"]], type_info[[\"yaxt\"]]) == \"n\")) ilwd = 0\n \n rect(\n xleft = ixmin, ybottom = iymin, xright = ixmax, ytop = iymax,\n lty = ilty,\n lwd = ilwd,\n border = par(\"fg\"), #icol,\n col = ibg\n )\n \n ## axes\n ## - standard categorical axes (xaxt/yaxt == \"s\") _without_ ticks\n ## - never draw additional axis lines, box always for spinogram\n if(type_info[[\"axes\"]]) {\n if (x.categorical) {\n spine_axis(if (flip) 2 else 1, at = (xat[1L:nx] + xat[2L:(nx+1L)] - off)/2, labels = xaxlabels,\n type = type_info[[\"xaxt\"]], categorical = TRUE)\n } else {\n spine_axis(if (flip) 2 else 1, at = xat, labels = xaxlabels,\n type = type_info[[\"xaxt\"]], categorical = FALSE)\n }\n yat = yat[, if(flip) ncol(yat) else 1L]\n equidist = any(diff(yat) < tol.ylab)\n yat = if(equidist) seq.int(1/(2*ny), 1-1/(2*ny), by = 1/ny) else (yat[-1L] + yat[-length(yat)])/2\n spine_axis(if (flip) 3 else 2, at = yat, labels = yaxlabels,\n type = type_info[[\"yaxt\"]], categorical = TRUE)\n if (is_facet_position(if(flip) \"bottom\" else \"right\", ifacet, facet_window_args)) spine_axis(if (flip) 1 else 4,\n type = type_info[[\"yaxt\"]], categorical = FALSE)\n }\n if(!x.categorical && (is.null(ilwd) || ilwd > 0)) box()\n \n }\n return(fun)\n}\n\n\n\n\nspine_axis = function(side, ..., type = \"standard\", categorical = TRUE) {\n type = match.arg(type, c(\"standard\", \"none\", \"labels\", \"ticks\", \"axis\"))\n ## standard: with axis, ticks (unless categorical), and labels\n ## none: no axes\n ## labels: only labels without ticks and axis line\n ## ticks: only ticks and labels without axis line\n ## axis: only axis line and labels but no ticks\n\n if (type == \"none\") {\n invisible(numeric(0L))\n } else {\n args = list(side = side, ...)\n if (type == \"labels\") {\n args$tick = FALSE\n } else if (type == \"ticks\") {\n args$lwd = 0\n if (!(\"lwd.ticks\" %in% names(args))) args$lwd.ticks = if (categorical) 0 else 1\n } else if (type == \"axis\") {\n if (categorical) {\n args$tick = FALSE\n } else {\n args$lwd.ticks = 0\n }\n } else {\n args$tick = !categorical\n }\n do.call(\"axis\", args)\n }\n}\n\n#' @importFrom grDevices col2rgb convertColor hcl\nto_hcl = function(x) {\n x = t(col2rgb(x, alpha = TRUE)/255)\n alpha = x[, 4]\n x = x[, 1:3]\n x = convertColor(x, from = \"sRGB\", to = \"Luv\")\n x = cbind(H = atan2(x[, 3L], x[, 2L]) * 180/pi, C = sqrt(x[, 2L]^2 + x[, 3L]^2), L = x[, 1L])\n x[is.na(x[, 1L]), 1L] = 0\n x[x[, 1L] < 0, 1L] = x[x[, 1L] < 0, 1L] + 360\n attr(x, \"alpha\") = alpha\n return(x)\n}\n\nseq_palette = function(x, n, power = 1.5) {\n x = drop(to_hcl(x[1L]))\n alpha = attr(x, \"alpha\")\n hcl(\n h = x[1L],\n c = seq.int(from = x[2L]^(1/power), to = 0, length.out = n + 1)[1L:n]^power,\n l = 100 - seq.int(from = (100 - x[3L])^(1/power), to = pmin(8, (100 - x[3L])/2)^(1/power), length.out = n)^power,\n alpha = alpha\n )[1L:n]\n}\n"], ["/tinyplot/R/type_loess.R", "#' Local polynomial regression plot type\n#' \n#' @description Type function for plotting a LOESS (LOcal regrESSion) fit.\n#' Arguments are passed to \\code{\\link[stats]{loess}}.\n#' \n#' @inheritParams stats::loess\n#' @param se logical. If `TRUE` (the default), confidence intervals are drawn.\n#' @param level the confidence level required if `se = TRUE`. Default is 0.95.\n#' @importFrom stats loess loess.control predict\n#' @examples\n#' # \"loess\" type convenience string\n#' tinyplot(dist ~ speed, data = cars, type = \"loess\")\n#' \n#' # Use `type_loess()` to pass extra arguments for customization\n#' tinyplot(dist ~ speed, data = cars, type = type_loess(span = 0.5, degree = 1))\n#' @export\ntype_loess = function(\n span = 0.75,\n degree = 2,\n family = \"gaussian\",\n control = loess.control(),\n se = TRUE,\n level = 0.95\n ) {\n out = list(\n draw = draw_ribbon(),\n data = data_loess(span = span, degree = degree, family = family, control = control, se = se, level = level),\n name = if (isTRUE(se)) \"ribbon\" else \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_loess = function(span, degree, family, control, se, level, ...) {\n fun = function(datapoints, ...) {\n datapoints = split(datapoints, list(datapoints$facet, datapoints$by))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n datapoints = lapply(datapoints, function(dat) {\n fit = loess(y ~ x, data = dat, span = span, degree = degree, family = family, control = control)\n if (se == TRUE) {\n p = predict(fit, newdata = dat, se = TRUE)\n p = ci(p$fit, p$se.fit, conf.level = level, p$df)\n dat$y = p$estimate\n dat$ymax = p$conf.high\n dat$ymin = p$conf.low\n } else {\n dat$y = predict(fit, dat)\n }\n dat\n })\n datapoints = do.call(rbind, datapoints)\n datapoints = datapoints[order(datapoints$facet, datapoints$by, datapoints$x), ]\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_glm.R", "#' Generalized linear model plot type\n#' \n#' @description Type function for plotting a generalized model fit.\n#' Arguments are passed to \\code{\\link[stats]{glm}}.\n#' \n#' @param se logical. If TRUE, confidence intervals are drawn.\n#' @inheritParams stats::glm\n#' @inheritParams stats::predict.glm\n#' @inheritParams stats::confint\n#' @importFrom stats glm predict\n#' @examples\n#' # \"glm\" type convenience string\n#' tinyplot(am ~ mpg, data = mtcars, type = \"glm\")\n#' \n#' # Use `type_glm()` to pass extra arguments for customization\n#' tinyplot(am ~ mpg, data = mtcars, type = type_glm(family = \"binomial\"))\n#' @export\ntype_glm = function(family = \"gaussian\", se = TRUE, level = 0.95, type = \"response\") {\n assert_flag(se)\n out = list(\n draw = draw_ribbon(),\n data = data_glm(family = family, se = se, level = level, type = type),\n name = if (isTRUE(se)) \"ribbon\" else \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_glm = function(family, se, level, type, ...) {\n fun = function(datapoints, ...) {\n dat = split(datapoints, list(datapoints$facet, datapoints$by))\n dat = lapply(dat, function(x) {\n if (nrow(x) == 0) return(x)\n if (nrow(x) < 3) {\n x$y = NA\n return(x)\n }\n fit = glm(y ~ x, data = x, family = family)\n nd = data.frame(x = seq(min(x$x, na.rm = TRUE), max(x$x, na.rm = TRUE), length.out = 100))\n nd$by = x$by[1]\n nd$facet = x$facet[1]\n if (se == TRUE) {\n if (identical(type, \"response\")) {\n p = predict(fit, newdata = nd, type = \"link\", se.fit = TRUE)\n p = ci(p$fit, p$se.fit, conf.level = level, fit$df.residual, backtransform = stats::family(fit)$linkinv)\n nd$y = p$estimate\n nd$ymax = p$conf.high\n nd$ymin = p$conf.low\n\n } else {\n nd$y = predict(fit, newdata = nd, type = type)\n nd = ci(nd$y, nd$se, level, fit$df.residual, backtransform = stats::family(fit)$linkinv)\n }\n } else {\n nd$y = predict(fit, nd, type = type)\n }\n nd\n })\n datapoints = do.call(rbind, dat)\n datapoints = datapoints[order(datapoints$facet, datapoints$by, datapoints$x), ]\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\n\n#' Calculate confidence intervals\n#' @importFrom stats qt\n#' @keywords internal\nci = function(estimate, std.error, conf.level, df, backtransform = identity) {\n crit = qt(1 - (1 - conf.level) / 2, df)\n out = list(\n estimate = backtransform(estimate),\n conf.low = backtransform(estimate - crit * std.error),\n conf.high = backtransform(estimate + crit * std.error)\n )\n return(out)\n}\n"], ["/tinyplot/R/type_lm.R", "#' Linear model plot type\n#'\n#' @description Type function for plotting a linear model fit.\n#' Arguments are passed to \\code{\\link[stats]{lm}}.\n#' \n#' @inheritParams type_glm\n#' @importFrom stats lm predict\n#' @examples\n#' # \"lm\" type convenience string\n#' tinyplot(Sepal.Width ~ Petal.Width, data = iris, type = \"lm\")\n#' \n#' # Grouped model fits (here: illustrating an example of Simpson's paradox)\n#' tinyplot(Sepal.Width ~ Petal.Width | Species, data = iris, type = \"lm\")\n#' tinyplot_add(type = \"p\")\n#' \n#' # Use `type_lm()` to pass extra arguments for customization\n#' tinyplot(Sepal.Width ~ Petal.Width, data = iris, type = type_lm(level = 0.8))\n#' @export\ntype_lm = function(se = TRUE, level = 0.95) {\n assert_flag(se)\n out = list(\n draw = draw_ribbon(),\n data = data_lm(se = se, level = level),\n name = if (isTRUE(se)) \"ribbon\" else \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_lm = function(se, level, ...) {\n fun = function(datapoints, ...) {\n dat = split(datapoints, list(datapoints$facet, datapoints$by))\n dat = lapply(dat, function(x) {\n if (nrow(x) == 0) return(x)\n if (nrow(x) < 3) {\n x$y = NA\n return(x)\n }\n fit = lm(y ~ x, data = x)\n nd = data.frame(x = seq(min(x$x, na.rm = TRUE), max(x$x, na.rm = TRUE), length.out = 100))\n nd$by = x$by[1]\n nd$facet = x$facet[1]\n if (se == TRUE) {\n p = predict(fit, newdata = nd, se.fit = TRUE)\n p = ci(p$fit, p$se.fit, conf.level = level, fit$df.residual)\n nd$y = p$estimate\n nd$ymax = p$conf.high\n nd$ymin = p$conf.low\n } else {\n nd$y = predict(fit, newdata = nd)\n }\n nd\n })\n datapoints = do.call(rbind, dat)\n datapoints = datapoints[order(datapoints$facet, datapoints$by, datapoints$x), ]\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_boxplot.R", "#' Boxplot type\n#' \n#' @description Type function for producing box-and-whisker plots.\n#' Arguments are passed to \\code{\\link[graphics]{boxplot}}, although `tinyplot`\n#' scaffolding allows added functionality such as grouping and faceting.\n#' Box-and-whisker plots are the default plot type if `x` is a factor and `y` is\n#' numeric.\n#'\n#' @inheritParams graphics::boxplot\n#' @examples\n#' # \"boxplot\" type convenience string\n#' tinyplot(count ~ spray, data = InsectSprays, type = \"boxplot\")\n#' \n#' # Note: Specifying the type here is redundant. Like base plot, tinyplot\n#' # automatically produces a boxplot if x is a factor and y is numeric\n#' tinyplot(count ~ spray, data = InsectSprays)\n#' \n#' # Grouped boxplot example\n#' tinyplot(len ~ dose | supp, data = ToothGrowth, type = \"boxplot\")\n#' \n#' # Use `type_boxplot()` to pass extra arguments for customization\n#' tinyplot(\n#' len ~ dose | supp, data = ToothGrowth, lty = 1,\n#' type = type_boxplot(boxwex = 0.3, staplewex = 0, outline = FALSE)\n#' )\n#' @export\ntype_boxplot = function(\n range = 1.5,\n width = NULL,\n varwidth = FALSE,\n notch = FALSE,\n outline = TRUE,\n boxwex = 0.8,\n staplewex = 0.5,\n outwex = 0.5) {\n out = list(\n draw = draw_boxplot(\n range = range,\n width = width,\n varwidth = varwidth,\n notch = notch,\n outline = outline,\n boxwex = boxwex,\n staplewex = staplewex,\n outwex = outwex),\n data = data_boxplot(),\n name = \"boxplot\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\n\ndraw_boxplot = function(range, width, varwidth, notch, outline, boxwex, staplewex, outwex) {\n fun = function(iby, ix, iy, ipch, ilty, icol, ibg, x_by = FALSE, facet_by = FALSE, ngrps = 1, flip, ...) {\n\n at_ix = unique(ix)\n if (isTRUE(x_by)) boxwex = boxwex * 2\n\n # Handle multiple groups\n if (ngrps > 1 && isFALSE(x_by) && isFALSE(facet_by)) {\n boxwex_orig = boxwex\n boxwex = boxwex / ngrps - 0.01\n at_ix = at_ix + seq(\n -((boxwex_orig - boxwex) / 2),\n ((boxwex_orig - boxwex) / 2),\n length.out = ngrps\n )[iby]\n }\n\n boxplot(\n formula = iy ~ ix,\n pch = ipch,\n lty = ilty,\n border = icol,\n col = ibg,\n horizontal = flip,\n add = TRUE, axes = FALSE,\n at = at_ix,\n range = range,\n width = width,\n varwidth = varwidth,\n notch = notch,\n outline = outline,\n boxwex = boxwex,\n staplewex = staplewex,\n outwex = outwex\n )\n }\n return(fun)\n}\n\n\n\ndata_boxplot = function() {\n fun = function(datapoints, bg, col, palette, null_by, null_facet, ...) {\n # Convert x to factor if it's not already\n datapoints$x = as.factor(datapoints$x)\n\n # Handle factor levels and maintain order\n xlvls = levels(datapoints$x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n datapoints$x = as.integer(datapoints$x)\n\n if (null_by && null_facet) {\n xord = order(datapoints$x)\n } else if (null_facet) {\n xord = order(datapoints$by, datapoints$x)\n } else if (null_by) {\n xord = order(datapoints$facet, datapoints$x)\n } else {\n xord = order(datapoints$by, datapoints$facet, datapoints$x)\n }\n\n if (length(unique(datapoints[[\"by\"]])) == 1 && is.null(palette)) {\n if (is.null(col)) col = par(\"fg\")\n if (is.null(bg)) bg = \"lightgray\"\n } else {\n bg = \"by\"\n }\n\n # Reorder x, y, ymin, and ymax based on the order determined\n datapoints = datapoints[xord,]\n\n # Return the result as a list called 'out'\n out = list(\n x = datapoints$x,\n y = datapoints$y,\n ymin = datapoints$ymin,\n ymax = datapoints$ymax,\n xlabs = xlabs,\n datapoints = datapoints,\n col = col,\n bg = bg)\n\n if (length(unique(datapoints$by)) > 1) out[[\"by\"]] = datapoints$by\n if (length(unique(datapoints$facet)) > 1) out[[\"facet\"]] = datapoints$facet\n\n return(out)\n }\n return(fun)\n}\n\n\n\n\n"], ["/tinyplot/R/type_violin.R", "#' Violin plot type\n#' \n#' @md\n#' @description Type function for violin plots, which are an alternative to box\n#' plots for visualizing continuous distributions (by group) in the form of\n#' mirrored densities.\n#' @inheritParams type_density\n#' @param trim logical indicating whether the violins should be trimmed to the\n#' range of the data. Default is `FALSE`.\n#' @param width numeric (ideally in the range `[0, 1]`, although this isn't\n#' enforced) giving the normalized width of the individual violins.\n#' @inherit stats::density details\n#' @details See [`type_density`] for more details and considerations related to\n#' bandwidth selection and kernel types.\n#' \n#' @examples\n#' # \"violin\" type convenience string\n#' tinyplot(count ~ spray, data = InsectSprays, type = \"violin\")\n#' \n#' # aside: to match the defaults of `ggplot2::geom_violin()`, use `trim = TRUE`\n#' # and `joint.bw = FALSE`\n#' tinyplot(count ~ spray, data = InsectSprays, type = \"violin\",\n#' trim = TRUE, joint.bw = FALSE)\n#' \n#' # use flip = TRUE to reorient the axes\n#' tinyplot(count ~ spray, data = InsectSprays, type = \"violin\", flip = TRUE)\n#' \n#' # for flipped plots with long group labels, it's better to use a theme for\n#' # dynamic plot resizing\n#' tinytheme(\"clean\")\n#' tinyplot(weight ~ feed, data = chickwts, type = \"violin\", flip = TRUE)\n#' \n#' # you can group by the x var to add colour (here with the original orientation)\n#' tinyplot(weight ~ feed | feed, data = chickwts, type = \"violin\", legend = FALSE)\n#' \n#' # dodged grouped violin plot example (different dataset)\n#' tinyplot(len ~ dose | supp, data = ToothGrowth, type = \"violin\", fill = 0.2)\n#' \n#' # note: above we relied on `...` argument passing alongside the \"violin\"\n#' # type convenience string. But this won't work for `width`, since it will\n#' # clash with the top-level `tinyplot(..., width = )` arg. To ensure\n#' # correct arg passing, it's safer to use the formal `type_violin()` option.\n#' tinyplot(len ~ dose | supp, data = ToothGrowth, fill = 0.2,\n#' type = type_violin(width = 0.8))\n#' \n#' # reset theme\n#' tinytheme()\n#' \n#' @importFrom stats density weighted.mean\n#' @importFrom stats bw.SJ bw.bcv bw.nrd bw.nrd0 bw.ucv \n#' @export\ntype_violin = function(\n bw = \"nrd0\",\n joint.bw = c(\"mean\", \"full\", \"none\"),\n adjust = 1,\n kernel = c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"),\n n = 512,\n # more args from density here?\n trim = FALSE,\n width = 0.9\n ) {\n kernel = match.arg(kernel, c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"))\n if (is.logical(joint.bw)) {\n joint.bw = ifelse(joint.bw, \"mean\", \"none\")\n }\n joint.bw = match.arg(joint.bw, c(\"mean\", \"full\", \"none\"))\n out = list(\n data = data_violin(bw = bw, adjust = adjust, kernel = kernel, n = n,\n joint.bw = joint.bw, trim = trim, width = width),\n # draw = NULL,\n # name = \"polygon\"\n draw = draw_polygon(density = NULL),\n name = \"violin\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\ndata_violin = function(bw = \"nrd0\", adjust = 1, kernel = \"gaussian\", n = 512,\n joint.bw = \"none\", trim = FALSE, width = 0.9) {\n fun = function(datapoints, by, facet, ylab, col, bg, palette, log, null_by, null_facet, ...) {\n \n # Handle ordering based on by and facet variables\n ngrps = if (null_by) 1 else length(unique(datapoints$by))\n nfacets = if (null_facet) 1 else length(unique(datapoints$facet))\n \n # catch for special cases\n x_by = y_by = facet_by = FALSE\n if (!null_by) {\n x_by = identical(datapoints$x, datapoints$by)\n y_by = identical(datapoints$y, datapoints$by)\n if (!null_facet) facet_by = identical(datapoints$facet, datapoints$by)\n }\n \n # FIXME (once we add support for gradient fill to draw_polygon)\n if (y_by) {\n warning(\"\\n`y` == `by` is not currently supported for `type_violin`. We hope to support this in a future release, but for now `y` grouping will be turned off automatically.\\n\")\n by = NULL\n datapoints$by = \"\"\n ngrps = 1\n null_by = TRUE\n }\n \n # Convert x to factor if it's not already\n datapoints$x = as.factor(datapoints$x)\n if (x_by) datapoints$by = datapoints$x\n\n # Handle factor levels and maintain order\n xlvls = levels(datapoints$x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n # xlabs = levels(datapoints$x)\n datapoints$x = as.integer(datapoints$x)\n\n if (null_by && null_facet) {\n xord = order(datapoints$x)\n } else if (null_facet) {\n xord = order(datapoints$by, datapoints$x)\n } else if (null_by) {\n xord = order(datapoints$facet, datapoints$x)\n } else {\n xord = order(datapoints$by, datapoints$facet, datapoints$x)\n }\n\n if (length(unique(datapoints[[\"by\"]])) == 1 && is.null(palette)) {\n if (is.null(col)) col = par(\"fg\")\n if (is.null(bg)) bg = \"lightgray\"\n } else if (is.null(bg)) {\n bg = \"by\"\n }\n\n # Reorder x, y, ymin, and ymax based on the order determined\n datapoints = datapoints[xord,]\n\n \n datapoints = split(datapoints, list(datapoints$x, datapoints$by, datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n \n if (joint.bw == \"none\" || is.numeric(bw)) {\n dens_bw = bw\n } else {\n if (joint.bw == \"mean\") {\n # Use weighted mean of subgroup bandwidths\n bws = sapply(datapoints, function(dat) bw_fun(kernel = bw, dat$y))\n ws = sapply(datapoints, nrow)\n dens_bw = weighted.mean(bws, ws)\n } else if (joint.bw == \"full\") {\n dens_bw = bw_fun(kernel = bw, unlist(sapply(datapoints, `[[`, \"x\")))\n }\n }\n \n datapoints = lapply(seq_along(datapoints), function(d) {\n dat = datapoints[[d]]\n if (trim) {\n yrng = range(dat$y)\n dens = density(dat$y, bw = dens_bw, kernel = kernel, n = n, from = yrng[1], to = yrng[2])\n } else {\n dens = density(dat$y, bw = dens_bw, kernel = kernel, n = n)\n }\n \n x = dens$y\n y = dens$x\n \n \n if (log %in% c(\"y\", \"xy\")) {\n if (x[1] <= 0) {\n warning(\"\\nNon-positive density values have been trimmed as part of the logarthmic transformation.\\n\")\n xidx = x > 0\n x = x[xidx]\n y = y[xidx]\n } \n }\n \n x = c(x, rev(-x))\n y = c(y, rev(y))\n \n xwidth = xwidth_orig = width\n # dodge groups (if any)\n if ((ngrps > 1) && isFALSE(x_by) && isFALSE(facet_by)) {\n xwidth = xwidth_orig / ngrps - 0.01\n x = rescale_num(x, to = c(0, xwidth))\n x = x + as.numeric(sub(\"^([0-9]+)\\\\..*\", \"\\\\1\", names(datapoints)[d])) - xwidth/2\n x = x + seq(-((xwidth_orig - xwidth) / 2), ((xwidth_orig - xwidth) / 2), length.out = ngrps)[dat$by[1]]\n } else if (nfacets > 1) {\n x = rescale_num(x, to = c(0, xwidth))\n x = x + as.numeric(sub(\"^([0-9]+)\\\\..*\", \"\\\\1\", names(datapoints)[d])) - xwidth/2\n } else {\n x = rescale_num(x, to = c(0, xwidth))\n x = x + d - xwidth/2\n }\n \n x = c(x, NA)\n y = c(y, NA)\n \n out = data.frame(\n by = dat$by[1], # already split\n facet = dat$facet[1], # already split\n y = y,\n x = x\n )\n return(out)\n })\n datapoints = do.call(rbind, datapoints)\n datapoints = datapoints[1:(nrow(datapoints)-1), ]\n \n out = list(\n datapoints = datapoints,\n by = if (length(unique(datapoints$by)) == 1) by else datapoints$by, \n facet = if (length(unique(datapoints$facet)) == 1) facet else datapoints$facet,\n ylab = ylab,\n xlabs = xlabs,\n col = col,\n bg = bg\n )\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_barplot.R", "#' Barplot type\n#'\n#' @description Type function for producing barplots. For formulas of type\n#' `~ x` (without left-hand side) the barplot visualizes the counts (absolute\n#' frequencies) of the levels of `x`. For formulas of type `y ~ x` the value\n#' of `y` within each level of `x` is visualized, if necessary aggregated\n#' using some function (default: mean).\n#'\n#' @param width numeric, optional vector of bar widths. (The distance between\n#' the midpoints of the bars is always 1.)\n#' @param beside logical. In case of a `by` grouping variable, should bars be\n#' juxtaposed? Default is to use stacked bars instead.\n#' @param center logical or numeric. In case of stacked barplots (`beside = FALSE`)\n#' should the bars be centered (or all start at zero, default)? If set to\n#' `TRUE` the center is at the mid-point of the middle category (in case of\n#' uneven number of categories) or between the two middle categories (in case\n#' of an even number). Additionally it is possible to set `center = 2` or\n#' `center = 2.5` to indicate that centering should be after the second category\n#' or the mid-way in the third category, respectively.\n#' @param FUN a function to compute the summary statistic for `y` within each\n#' group of `x` in case of using a two-sided formula `y ~ x` (default: mean).\n#' @param xlevels a character or numeric vector specifying the ordering of the\n#' levels of the `x` variable (if character) or the corresponding indexes\n#' (if numeric) for the plot.\n#' @param xaxlabels a character vector with the axis labels for the `x` variable,\n#' defaulting to the levels of `x`.\n#' @param drop.zeros logical. Should bars with zero height be dropped? If set\n#' to `FALSE` (default) a zero height bar is still drawn for which the border\n#' lines will still be visible.\n#'\n#' @examples\n#' # Basic examples of frequency tables (without y variable)\n#' tinyplot(~ cyl, data = mtcars, type = \"barplot\")\n#' tinyplot(~ cyl | vs, data = mtcars, type = \"barplot\")\n#' tinyplot(~ cyl | vs, data = mtcars, type = \"barplot\", beside = TRUE)\n#' tinyplot(~ cyl | vs, data = mtcars, type = \"barplot\", beside = TRUE, fill = 0.2)\n#' \n#' # Reorder x variable categories either by their character levels or numeric indexes\n#' tinyplot(~ cyl, data = mtcars, type = \"barplot\", xlevels = c(\"8\", \"6\", \"4\"))\n#' tinyplot(~ cyl, data = mtcars, type = \"barplot\", xlevels = 3:1)\n#' \n#' # Note: Above we used automatic argument passing for `beside`. But this\n#' # wouldn't work for `width`, since it would conflict with the top-level\n#' # `tinyplot(..., width = )` argument. It's safer to pass these args\n#' # through the `type_barplot()` functional equivalent.\n#' tinyplot(~ cyl | vs, data = mtcars, fill = 0.2,\n#' type = type_barplot(beside = TRUE, drop.zeros = TRUE, width = 0.65))\n#'\n#' tinytheme(\"clean2\")\n#' \n#' # Example for numeric y aggregated by x (default: FUN = mean) + facets\n#' tinyplot(extra ~ ID | group, facet = \"by\", data = sleep,\n#' type = \"barplot\", fill = 0.6)\n#' \n#' # Fancy frequency table:\n#' tinyplot(Freq ~ Sex | Survived, facet = ~ Class, data = as.data.frame(Titanic),\n#' type = \"barplot\", facet.args = list(nrow = 1), flip = TRUE, fill = 0.6)\n#'\n#' # Centered barplot for conditional proportions of hair color (black/brown vs.\n#' # red/blond) given eye color and sex\n#' tinytheme(\"clean2\", palette.qualitative = c(\"black\", \"sienna\", \"indianred\", \"goldenrod\"))\n#' hec = as.data.frame(proportions(HairEyeColor, 2:3))\n#' tinyplot(Freq ~ Eye | Hair, facet = ~ Sex, data = hec, type = \"barplot\",\n#' center = TRUE, flip = TRUE, facet.args = list(ncol = 1), yaxl = \"percent\")\n#'\n#' tinytheme()\n#' \n#' @export\ntype_barplot = function(width = 5/6, beside = FALSE, center = FALSE, FUN = NULL, xlevels = NULL, xaxlabels = NULL, drop.zeros = FALSE) {\n out = list(\n data = data_barplot(width = width, beside = beside, center = center, FUN = FUN, xlevels = xlevels, xaxlabels = xaxlabels, drop.zeros = drop.zeros),\n draw = draw_rect(),\n name = \"barplot\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n#' @importFrom stats aggregate\ndata_barplot = function(width = 5/6, beside = FALSE, center = FALSE, FUN = NULL, xlevels = NULL, xaxlabels = NULL, drop.zeros = FALSE) {\n fun = function(datapoints, col, bg, lty, lwd, palette, xlab = NULL, ylab = NULL, xlim = NULL, ylim = NULL, xaxt = NULL, yaxl = NULL, yaxt = NULL, axes = TRUE, null_by, facet_by, ...) {\n\n \n ## tabulate/aggregate datapoints\n if (is.null(datapoints$y)) {\n xlab = ylab\n ylab = \"Count\"\n \n datapoints$y = numeric(nrow(datapoints)) \n if (!is.null(FUN)) warning(\"without 'y' variable 'FUN' specification is ignored\")\n FUN = length\n } else {\n if (is.null(FUN)) FUN = function(x, ...) mean(x, ..., na.rm = TRUE)\n }\n if (!is.factor(datapoints$x)) datapoints$x = factor(datapoints$x)\n if (!is.null(xlevels)) {\n xlevels = if(is.numeric(xlevels)) levels(datapoints$x)[xlevels] else xlevels\n if (any(is.na(xlevels)) || !all(xlevels %in% levels(datapoints$x))) warning(\"not all 'xlevels' correspond to levels of 'x'\")\n datapoints$x = factor(datapoints$x, levels = xlevels)\n }\n if (!is.null(xaxlabels)) levels(datapoints$x) <- xaxlabels\n datapoints = aggregate(datapoints[, \"y\", drop = FALSE], datapoints[, c(\"x\", \"by\", \"facet\")], FUN = FUN, drop = FALSE)\n datapoints$y[is.na(datapoints$y)] = 0 #FIXME: always?#\n if (!is.factor(datapoints$by)) datapoints$by = factor(datapoints$by)\n if (!is.factor(datapoints$facet)) datapoints$facet = factor(datapoints$facet)\n \n if (isFALSE(null_by) && isFALSE(facet_by) && !beside && any(datapoints$y < 0)) {\n warning(\"'beside' must be TRUE if there are negative 'y' values\")\n beside = TRUE\n }\n if (beside & !isFALSE(center)) {\n warning(\"'center' is currently only supported for 'beside = FALSE'\")\n }\n offset_sum = function(z, center = TRUE, na.rm = TRUE) {\n n = length(z)\n if (isFALSE(center) || n < 1L) return(0)\n mid = if (isTRUE(center)) n/2 else center\n z[floor(mid) + 1L] = (mid - floor(mid)) * z[floor(mid) + 1L]\n sum(z[0L:floor(mid) + 1L], na.rm = TRUE)\n }\n if (is.null(xlim)) xlim = c(1, length(levels(datapoints$x))) + c(-0.5, 0.5) * width\n if (is.null(ylim)) ylim = if (beside || length(unique(datapoints$by)) == 1L) {\n c(pmin(0, min(datapoints$y, na.rm = TRUE) * 1.02), pmax(0, max(datapoints$y, na.rm = TRUE) * 1.02))\n } else {\n range(unlist(tapply(\n datapoints$y,\n interaction(datapoints$x, datapoints$facet),\n function(z) c(0, sum(z, na.rm = TRUE)) - offset_sum(z, center = center)\n ))) * 1.02\n }\n\n ## default color palette\n ngrps = length(unique(datapoints$by))\n if (ngrps == 1L && is.null(palette)) {\n if (is.null(col)) col = par(\"fg\")\n if (is.null(bg)) bg = \"grey\"\n } else {\n if (is.null(bg)) bg = \"by\"\n }\n\n ## calculate bar rectangles per facet \n sdat = split(datapoints, datapoints$facet)\n datapoints = lapply(sdat, function(df) {\n \n df = df[order(df$x), , drop = FALSE]\n nx = length(levels(df$x))\n nb = length(levels(df$by))\n \n if (beside) { \n xl = as.numeric(df$x) - width/2 + (as.numeric(df$by) - 1) * width/nb * as.numeric(!facet_by)\n xr = if (facet_by) xl + width else xl + width/nb\n yb = 0\n yt = df$y\n } else {\n cs = tapply(df$y, df$x, function(z) cumsum(c(0, z)) - offset_sum(z, center = center))\n xl = as.numeric(df$x) - width/2\n xr = xl + width\n yb = if (facet_by) 0 else unlist(lapply(cs, `[`, -(nb + 1L)))\n yt = if (facet_by) df$y else unlist(lapply(cs, `[`, -1L))\n }\n \n df$xmin = xl\n df$xmax = xr\n df$ymin = yb\n df$ymax = yt\n df$nx = nx\n \n if (drop.zeros) {\n yb = rep_len(yb, length(yt))\n yok = abs(yt - yb) > 0\n df = df[yok, , drop = FALSE]\n }\n \n return(df)\n })\n datapoints = do.call(\"rbind\", datapoints)\n nx = datapoints$nx[1]\n datapoints$nx = NULL\n xlabs = 1L:nx\n names(xlabs) = levels(datapoints$x)\n \n if (!isFALSE(center)) {\n if (is.null(yaxl)) {\n yaxl = abs\n } else if (is.character(yaxl)) {\n yaxl = paste0(\"abs_\", yaxl)\n }\n }\n \n out = list(\n datapoints = datapoints,\n xlab = xlab,\n ylab = ylab,\n xlim = xlim,\n ylim = ylim,\n axes = FALSE, #FIXME\n axes = TRUE,\n xlabs = xlabs, \n frame.plot = FALSE,\n xaxs = \"r\",\n xaxt = if (xaxt == \"s\") \"l\" else xaxt,\n yaxl = yaxl,\n yaxs = \"i\",\n col = col,\n bg = bg\n )\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_spline.R", "#' Spline plot type\n#' \n#' @description Type function for plotting a cubic (or Hermite) spline interpolation.\n#' Arguments are passed to \\code{\\link[stats]{spline}}; see this latter function\n#' for default argument values.\n#' \n#' @inheritParams stats::spline\n#' @inherit stats::spline details\n#' @importFrom stats spline\n#' @examples\n#' # \"spline\" type convenience string\n#' tinyplot(dist ~ speed, data = cars, type = \"spline\")\n#' \n#' # Use `type_spline()` to pass extra arguments for customization\n#' tinyplot(dist ~ speed, data = cars, type = type_spline(method = \"natural\", n = 25),\n#' add = TRUE, lty = 2)\n#' @export\ntype_spline = function(\n n = NULL,\n method = \"fmm\",\n xmin = NULL,\n xmax = NULL,\n xout = NULL,\n ties = mean\n ) {\n out = list(\n draw = draw_lines(),\n data = data_spline(method = method, ties = ties, n = n, xmin = xmin, xmax = xmax, xout = xout),\n name = \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_spline = function(n, method, xmin, xmax, xout, ties, ...) {\n fun = function(datapoints, ...) {\n datapoints = split(datapoints, list(datapoints$facet, datapoints$by), drop = TRUE)\n datapoints = lapply(datapoints, function(dat) {\n if (is.null(n)) n = 3*length(dat$x)\n if (is.null(xmax)) xmax = max(dat$x)\n if (is.null(xmin)) xmin = min(dat$x)\n if (is.null(xout)) {\n fit = spline(x = dat$x, y = dat$y, n = n, method = method, xmin = xmin, xmax = xmax, ties = ties)\n } else {\n fit = spline(x = dat$x, y = dat$y, n = n, method = method, xmin = xmin, xmax = xmax, xout = xout, ties = ties)\n }\n fit = as.data.frame(fit)\n fit$facet = dat$facet[1]\n fit$by = dat$by[1]\n fit\n return(fit)\n })\n datapoints = do.call(rbind, datapoints)\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/by_aesthetics.R", "by_col = function(ngrps = 1L, col = NULL, palette = NULL, gradient = NULL, ordered = NULL, alpha = NULL) {\n if (is.null(alpha)) alpha = 1\n if (is.null(ordered)) ordered = FALSE\n if (is.null(gradient)) gradient = FALSE\n assert_logical(ordered)\n assert_logical(gradient)\n if (gradient) {\n ngrps = 100L\n }\n \n # pal_qual = get_tpar(\"palette.qualitative\", default = NULL)\n pal_theme = get_tpar(\"palette.qualitative\", default = NULL)\n theme_flag = !is.null(pal_theme)\n\n # palette = substitute(palette, env = parent.env(environment()))\n\n # special \"by\" convenience keyword (will treat as NULL & handle grouping below)\n if (!anyNA(col) && !is.null(col) && length(col) == 1 && col == \"by\") col = NULL\n\n #\n ## Base case: If no color or palette provided, pass colors as a sequence of\n ## numbers (will inherit from / cycle over the user's default palette)\n \n if (is.null(col) && (is.null(palette) && !theme_flag)) {\n if (ngrps <= length(palette()) && !ordered) {\n col = palette()[seq_len(ngrps)]\n if (alpha) col = adjustcolor(col, alpha.f = alpha)\n } else {\n # fallback to restricted viridis palette\n col = colorRampPalette(\n hcl.colors(n = 100, palette = \"Viridis\", alpha = alpha)[(100 * 0.1 + 1):(100 * 0.9)],\n alpha = TRUE\n )(ngrps)\n }\n if (gradient || ordered) col = rev(col)\n return(col)\n }\n\n #\n ## Next simplest case: No palette, but color(s) provided directly. We do\n ## some simple sanity checks, apply alpha transparency and return as-is.\n\n if (is.atomic(col) && is.vector(col)) {\n if (length(col) == 1) {\n col = rep(col, ngrps)\n if (alpha) col = adjustcolor(col, alpha.f = alpha)\n return(col)\n } else if (length(col) < ngrps) {\n # if (!gradient) {\n # stop(sprintf(\"`col` must be of length 1, or greater than or equal to %s.\", ngrps), call. = FALSE)\n # } else {\n # # interpolate gradient colors\n # col = colorRampPalette(colors = col, alpha = TRUE)(ngrps)\n # }\n # if manual colours < ngrps, either (1) interpolate for gradient\n # colors, or (2) recycle for discrete colours\n if (gradient) {\n col = colorRampPalette(colors = col, alpha = TRUE)(ngrps)\n } else {\n ncolsstr = paste0(\"(\", length(col), \")\")\n ngrpsstr = paste0(\"(\", ngrps, \")\")\n warning(\n \"\\nFewer colours \", ncolsstr, \" provided than than there are groups \",\n ngrpsstr, \". Recycling to make up the shortfall.\"\n )\n col = rep(col, length.out = ngrps)\n }\n \n }\n if (gradient) {\n col = rev(col)\n } else if (!ordered && is.numeric(col)) {\n # col = palette()[col]\n if (ngrps <= length(palette())) {\n col = palette()[col]\n # if (alpha) col = adjustcolor(col, alpha.f = alpha)\n } else {\n col = hcl.colors(max(col), alpha = alpha)[col]\n }\n }\n if (anyNA(col) || is.character(col)) {\n if (alpha) col = adjustcolor(col, alpha.f = alpha)\n return(col)\n }\n }\n \n \n #\n ## Theme case: No palette provided, but fallback to tinytheme palette\n\n # we need to fix palette string, determine if in palette.pals() and then\n # determine no. of groups, before kicking over to sequential\n if (is.null(palette) && theme_flag) {\n if (length(pal_theme) == 1) {\n qual_match = match_pal(pal_theme, palette.pals())\n if (!is.na(qual_match)) {\n if (ngrps >= get_pal_lens(pal_theme) || ordered) {\n pal_theme = get_tpar(\"palette.sequential\", default = NULL)\n }\n # mostly a catch for x-gradient fills, e.g. type_ridge\n } else if (gradient && !is.na(match_pal(pal_theme, hcl.pals()))) {\n pal_theme = get_tpar(\"palette.sequential\", default = NULL)\n }\n }\n if (length(pal_theme) == 1) {\n palette_fun = gen_pal_fun(pal = pal_theme, gradient = gradient, alpha = alpha)\n args = list(n = ngrps, palette = pal_theme, alpha = alpha)\n }\n palette = pal_theme\n }\n \n if (is.null(palette)) {\n if (ngrps <= length(palette()) && !ordered && !gradient) {\n palette_fun = function(alpha) adjustcolor(palette(), alpha) # must be function to avoid arg ambiguity\n args = list(alpha = alpha)\n } else {\n if (ngrps <= 8 && !ordered) { # ngrps < 100 so we know gradient is FALSE too\n palette = \"R4\"\n palette_fun = palette.colors\n } else {\n palette = \"Viridis\"\n if (!gradient && !ordered) {\n palette_fun = hcl.colors\n } else {\n palette_fun_gradient = function(n, palette, from = 0.1, to = 0.9, alpha = 1) {\n colorRampPalette(\n hcl.colors(n = 100, palette = palette, alpha = alpha)[(100 * from + 1):(100 * to)],\n alpha = TRUE\n )(n)\n }\n palette_fun = palette_fun_gradient\n }\n }\n args = list(n = ngrps, palette = palette, alpha = alpha)\n }\n } else {\n if (is.character(palette)) {\n # special case: if vector of character strings, we assume that the user\n # must have passed a vector of colours (e.g., c(\"red\", \"blue\")) rather\n # than a known/named colour palette (e.g. \"Harmonic\")\n if (length(palette) > 1) {\n palette_fun = \"c\"\n if (!is.null(alpha)) palette = adjustcolor(palette, alpha.f = alpha)\n args = as.list(palette)\n if (length(args) < ngrps && length(args) != 1) {\n # if manual colours < ngrps, either (1) interpolate for gradient\n # colors, or (2) recycle for discrete colours\n if (gradient) {\n args = list(colorRampPalette(args, alpha = TRUE)(ngrps))\n } else {\n ncolsstr = paste0(\"(\", length(args), \")\")\n ngrpsstr = paste0(\"(\", ngrps, \")\")\n warning(\n \"\\nFewer colours \", ncolsstr, \" provided than than there are groups \",\n ngrpsstr, \". Recycling to make up the shortfall.\"\n )\n args = rep(args, length.out = ngrps)\n }\n }\n } else {\n palette_fun = gen_pal_fun(palette, gradient = gradient, alpha = alpha, n = ngrps)\n args = list(n = ngrps, palette = palette, alpha = alpha)\n }\n } else if (inherits(palette, c(\"call\", \"name\"))) {\n # catch for when using passes palette as named object (e.g,\n # pal26 = palette.colors(\"Alphabet\"))\n if (inherits(palette, \"name\") && is.character(eval(palette))) {\n args = as.list(eval(palette))\n palette_fun = \"c\"\n } else {\n args = as.list(palette)\n palette_fun = paste(args[[1]])\n args[[1]] = NULL\n }\n # catch for direct vector or list\n if (palette_fun %in% c(\"c\", \"list\")) {\n if (palette_fun == \"list\") palette_fun = \"c\"\n if (!is.null(alpha)) args = lapply(args, function(a) adjustcolor(a, alpha.f = alpha))\n if (length(args) < ngrps && length(args) != 1) {\n # if manual colours < ngrps, either (1) interpolate for gradient\n # colors, or (2) recycle for discrete colours\n if (gradient) {\n args = list(colorRampPalette(args, alpha = TRUE)(ngrps))\n } else {\n ncolsstr = paste0(\"(\", length(args), \")\")\n ngrpsstr = paste0(\"(\", ngrps, \")\")\n warning(\n \"\\nFewer colours \", ncolsstr, \" provided than than there are groups \",\n ngrpsstr, \". Recycling to make up the shortfall.\"\n )\n args = rep(args, length.out = ngrps)\n }\n }\n } else {\n args[[\"n\"]] = ngrps\n # remove unnamed arguments to prevent unintentional argument sliding\n if (any(names(args) == \"\")) args[[which(names(args) == \"\")]] = NULL\n }\n } else if (inherits(palette, \"function\")) {\n args = list()\n palette_fun = palette\n } else {\n stop(\n \"\\nInvalid palette argument. Must be a recognized keyword, or a \",\n \"palette-generating function with named arguments.\\n\"\n )\n }\n }\n\n cols = tryCatch(\n do.call(palette_fun, args),\n error = function(e) do.call(eval(palette), args) # catch for bespoke palette generating funcs\n )\n\n if (length(cols) > ngrps) cols = cols[1:ngrps]\n\n # For gradient and ordered colors, we'll run high to low\n if (gradient || ordered) cols = rev(cols)\n\n return(cols)\n}\n\n# Some utility functions for palette matching, etc.\n\nmatch_pal = function(pal, pals) {\n fx = function(x) tolower(gsub(\"[-, _, \\\\,, (, ), \\\\ , \\\\.]\", \"\", x))\n charmatch(fx(pal), fx(pals))\n}\n\nget_pal_lens = function(pal) {\n pal_lens = c(\n R3 = 8L, R4 = 8L, ggplot2 = 8L, `Okabe-Ito` = 9L, Accent = 8L,\n `Dark 2` = 8L, Paired = 12L, `Pastel 1` = 9L, `Pastel 2` = 8L, \n `Set 1` = 9L, `Set 2` = 8L, `Set 3` = 12L, `Tableau 10` = 10L, \n `Classic Tableau` = 10L, `Polychrome 36` = 36L, Alphabet = 26L\n )\n pal_lens[pal]\n}\n\n# take a character string, match to either palette.pals() pr hcl.pals(), and\n# generate the corresponding function factor with alpha transparency\ngen_pal_fun = function(pal, gradient = FALSE, alpha = NULL, n = NULL) {\n pal_match = match_pal(pal, palette.pals())\n if (!is.na(pal_match)) {\n if (pal_match < 1L) stop(\"'palette' is ambiguous\")\n pal_fun = palette.colors\n if (!is.null(n) && n >= get_pal_lens(pal_match)) {\n warning(\n \"\\nFewer colours \", get_pal_lens(pal_match), \" provided than than there are groups \",\n n, \". Recycling to make up the shortfall.\"\n )\n pal_fun = function(n, palette, alpha) palette.colors(n = n, palette = pal, alpha = alpha, recycle = TRUE)\n }\n if (gradient) {\n pal_fun = function(n, palette, alpha) colorRampPalette(palette.colors(palette = pal, alpha = alpha))(n)\n }\n } else {\n pal_match = match_pal(pal, hcl.pals())\n if (!is.na(pal_match)) {\n if (pal_match < 1L) stop(\"'palette' is ambiguous\")\n pal_fun = hcl.colors\n } else {\n stop(\n \"\\nPalette string not recogized. Must be a value produced by either\",\n \"`palette.pals()` or `hcl.pals()`.\\n\",\n call. = FALSE\n )\n }\n }\n return(pal_fun)\n}\n\n\nby_pch = function(ngrps, type, pch = NULL) {\n no_pch = FALSE\n if (identical(type, \"text\")) {\n pch <- rep(15, ngrps)\n } else if (!type %in% c(\"p\", \"b\", \"o\", \"pointrange\", \"errorbar\", \"boxplot\", \"qq\")) {\n no_pch = TRUE\n pch = NULL\n\n # special \"by\" convenience keyword\n } else if (!is.null(pch) && length(pch) == 1 && pch == \"by\") {\n no_pch = TRUE # skip checks below\n pch = 1:ngrps + par(\"pch\") - 1\n # correctly recycle if over max pch type\n pch_ceiling = 25 # see ?pch\n if (max(pch) > pch_ceiling) {\n pch_below = pch[pch <= pch_ceiling]\n pch_above = pch[pch > pch_ceiling]\n pch_above = rep_len(0:pch_ceiling, length(pch_above))\n pch = c(pch_below, pch_above)\n }\n\n # return NULL if not a valid point type\n } else if (is.null(pch)) {\n pch = par(\"pch\")\n }\n\n if (!no_pch) {\n if (!is.atomic(pch) || !is.vector(pch) || !(is.numeric(pch) || is.character(pch)) || (length(pch) != 1 && length(pch) != ngrps)) {\n # if (!is.atomic(pch) || !is.vector(pch) || !is.numeric(pch) || (length(pch) != 1 && length(pch) != ngrps)) {\n stop(sprintf(\"`pch` must be `NULL`, or a numeric or character vector of length 1 or %s.\", ngrps), call. = FALSE)\n }\n\n if (length(pch) == 1) {\n pch = rep(pch, ngrps)\n }\n }\n\n return(pch)\n}\n\n\nby_lty = function(ngrps, type, lty = NULL) {\n # We only care about line types, otherwise return NULL\n if (!type %in% c(\"l\", \"b\", \"o\", \"c\", \"h\", \"s\", \"S\", \"ribbon\", \"barplot\", \"boxplot\", \"rect\", \"segments\", \"qq\", \"abline\", \"hline\", \"vline\")) {\n out = NULL\n\n # special \"by\" convenience keyword\n } else if (!is.null(lty) && length(lty) == 1 && lty == \"by\") {\n lty_dict = c(\"solid\", \"dashed\", \"dotted\", \"dotdash\", \"longdash\", \"twodash\")\n par_lty = par(\"lty\")\n\n if (!par_lty %in% lty_dict) {\n warning(\n \"\\nBesoke lty specifications (i.e., using string combinations) are not\",\n \"currently supported alongside the lty='by' keyword argument.\",\n \"Defaulting to 1 and looping from there.\\n\"\n )\n par_lty = 1\n } else {\n par_lty = which(par_lty == lty_dict)\n }\n out = 1:ngrps + par_lty - 1\n # correctly recycle if over max pch type\n lty_ceiling = 6 # see ?pch\n if (max(out) > lty_ceiling) {\n lty_below = out[out <= lty_ceiling]\n lty_above = out[out > lty_ceiling]\n lty_above = rep_len(1:lty_ceiling, length(lty_above))\n out = c(lty_below, lty_above)\n }\n\n # NULL -> solid (or default) line\n } else if (is.null(lty)) {\n if (identical(type, \"boxplot\")) {\n out = NULL\n } else {\n out = rep(par(\"lty\"), ngrps)\n }\n\n # atomic vector: sanity check length\n } else if (is.atomic(lty) && is.vector(lty)) {\n if (length(lty) == 1) {\n out = rep(lty, ngrps)\n } else {\n if (length(lty) != ngrps) {\n stop(sprintf(\"`lty` must be `NULL` or a numeric vector of length 1 or %s.\", ngrps), call. = FALSE)\n }\n out = lty\n }\n }\n\n return(out)\n}\n\n\nby_lwd = function(ngrps, type, lwd = NULL) {\n lwd_base = par(\"lwd\")\n lwd_floor = lwd_base / min(5, max((ngrps - 1), 1))\n lwd_ceiling = lwd_base * min(5, ngrps)\n\n no_lwd = FALSE\n # special \"by\" convenience keyword\n if (!is.null(lwd) && length(lwd) == 1 && lwd == \"by\") {\n no_lwd = TRUE # skip checks below\n lwd = seq(lwd_floor, lwd_ceiling, length.out = ngrps)\n } else if (is.null(lwd)) {\n no_lwd = TRUE\n lwd = NULL\n }\n\n if (!no_lwd) {\n if (!is.atomic(lwd) || !is.vector(lwd) || !is.numeric(lwd) || (length(lwd) != 1 && length(lwd) != ngrps)) {\n stop(sprintf(\"`lwd` must be `NULL` or a numeric vector of length 1 or %s.\", ngrps), call. = FALSE)\n }\n if (length(lwd) == 1) {\n lwd = rep(lwd, ngrps)\n }\n }\n\n return(lwd)\n}\n\n\nby_bg = function(\n adjustcolor,\n alpha,\n bg,\n by,\n by_continuous,\n by_ordered,\n col,\n fill,\n ngrps,\n palette,\n ribbon.alpha,\n type) {\n if (is.null(bg) && !is.null(fill)) bg = fill\n if (!is.null(bg) && length(bg) == 1 && is.numeric(bg) && bg >= 0 && bg <= 1) {\n alpha = bg\n bg = \"by\"\n }\n if (!is.null(bg) && length(bg) == 1 && bg == \"by\") {\n bg = by_col(\n ngrps = ngrps,\n col = NULL,\n palette = palette,\n gradient = by_continuous,\n ordered = by_ordered,\n alpha = alpha\n )\n } else if (length(bg) != ngrps) {\n bg = rep(bg, ngrps)\n }\n if (type == \"ribbon\" || (type == \"boxplot\" && !is.null(by))) {\n if (!is.null(bg)) {\n bg = adjustcolor(bg, ribbon.alpha)\n } else if (!is.null(col)) {\n bg = adjustcolor(col, ribbon.alpha)\n }\n }\n\n return(bg)\n}\n"], ["/tinyplot/R/type_pointrange.R", "#' @rdname type_errorbar\n#' @export\ntype_pointrange = function() {\n out = list(\n draw = draw_pointrange(),\n data = data_pointrange(),\n name = \"p\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\n\ndraw_pointrange = function() {\n fun = function(ix, iy, ixmin, iymin, ixmax, iymax, icol, ibg, ipch, ilwd, cex, ...) {\n segments(\n x0 = ixmin,\n y0 = iymin,\n x1 = ixmax,\n y1 = iymax,\n col = icol,\n lwd = ilwd\n )\n draw_points()(ix = ix, iy = iy, icol = icol, ibg = ibg, ipch = ipch, ilwd = ilwd, cex = cex)\n }\n return(fun)\n}\n\n\ndata_pointrange = function() {\n fun = function(datapoints, xlabs, ...) {\n if (is.character(datapoints$x)) datapoints$x = as.factor(datapoints$x)\n if (is.factor(datapoints$x)) {\n ## original data (i.e., no new sorting by factor)\n xlvls = unique(datapoints$x)\n datapoints$x = factor(datapoints$x, levels = xlvls)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n datapoints$x = as.integer(datapoints$x)\n }\n datapoints$xmin = datapoints$x\n datapoints$xmax = datapoints$x\n out = list(\n x = datapoints$x,\n xlabs = xlabs,\n datapoints = datapoints)\n\n return(out)\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_points.R", "#' Points plot type\n#'\n#' @description Type function for plotting points, i.e. a scatter plot.\n#' \n#' @examples\n#' # \"p\" type convenience character string\n#' tinyplot(Sepal.Length ~ Petal.Length, data = iris, type = \"p\")\n#' \n#' # Same result with type_points()\n#' tinyplot(Sepal.Length ~ Petal.Length, data = iris, type = type_points())\n#' \n#' # Note: Specifying the type here is redundant. Like base plot, tinyplot\n#' # automatically produces a scatter plot if x and y are numeric\n#' tinyplot(Sepal.Length ~ Petal.Length, data = iris)\n#' \n#' # Grouped scatter plot example\n#' tinyplot(Sepal.Length ~ Petal.Length | Species, data = iris)\n#' \n#' # Continuous grouping (with gradient legend)\n#' tinyplot(Sepal.Length ~ Petal.Length | Sepal.Width, data = iris, pch = 19)\n#' \n#' @export\ntype_points = function() {\n out = list(\n draw = draw_points(),\n data = data_points(),\n name = \"p\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\ndata_points = function() {\n fun = function(datapoints, ...) {\n # catch for factors (we should still be able to \"force\" plot these with points)\n if (is.factor(datapoints$x)) {\n xlvls = levels(datapoints$x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n datapoints$x = as.integer(datapoints$x)\n } else {\n xlabs = NULL\n }\n if (is.factor(datapoints$y)) {\n ylvls = levels(datapoints$y)\n ylabs = seq_along(ylvls)\n names(ylabs) = ylvls\n datapoints$y = as.integer(datapoints$y)\n } else {\n ylabs = NULL\n }\n \n out = list(\n datapoints = datapoints,\n xlabs = xlabs,\n ylabs = ylabs\n )\n return(out)\n }\n}\n\ndraw_points = function() {\n fun = function(ix, iy, icol, ibg, ipch, ilwd, cex, ...) {\n points(\n x = ix,\n y = iy,\n col = icol,\n bg = ibg,\n type = \"p\",\n pch = ipch,\n lwd = ilwd,\n cex = cex\n )\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_jitter.R", "#' Jittered points plot type\n#'\n#' @description Type function for plotting jittered points.\n#' Arguments are passed to \\code{\\link[base]{jitter}}.\n#'\n#' @inheritParams base::jitter\n#' @inherit base::jitter details\n#' @examples\n#' # \"jitter\" type convenience string\n#' tinyplot(Sepal.Length ~ Species, data = iris, type = \"jitter\")\n#' \n#' # Use `type_jitter()` to pass extra arguments for customization\n#' tinyplot(Sepal.Length ~ Species, data = iris, type = type_jitter(factor = 0.5))\n#' @export\ntype_jitter = function(factor = 1, amount = NULL) {\n out = list(\n draw = draw_points(),\n data = data_jitter(factor = factor, amount = amount),\n name = \"p\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_jitter = function(factor, amount) {\n fun = function(datapoints, ...) {\n x = datapoints$x\n y = datapoints$y\n if (is.factor(x)) {\n xlvls = levels(x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n x = as.integer(x)\n } else {\n xlabs = NULL\n }\n if (is.factor(y)) {\n ylvls = levels(y)\n ylabs = seq_along(ylvls)\n names(ylabs) = ylvls\n y = as.integer(y)\n } else {\n ylabs = NULL\n }\n x = jitter(x, factor = factor, amount = amount)\n y = jitter(y, factor = factor, amount = amount)\n\n datapoints$x = x\n datapoints$y = y\n\n out = list(\n datapoints = datapoints,\n x = x,\n y = y,\n xlabs = xlabs,\n ylabs = ylabs\n )\n return(out)\n }\n}\n\n"], ["/tinyplot/R/sanitize.R", "sanitize_ribbon.alpha = function(ribbon.alpha) {\n assert_numeric(ribbon.alpha, len = 1, lower = 0, upper = 1, null.ok = TRUE)\n if (is.null(ribbon.alpha)) ribbon.alpha = .tpar[[\"ribbon.alpha\"]]\n return(ribbon.alpha)\n}\n\n\n\nsanitize_type = function(type, x, y, dots) {\n if (inherits(type, \"tinyplot_type\")) {\n return(type)\n }\n\n known_types = c(\n \"p\", \"l\", \"o\", \"b\", \"c\", \"h\", \"j\", \"s\", \"S\", \"n\", \n \"abline\",\n \"area\",\n \"bar\", \"barplot\",\n \"box\", \"boxplot\",\n \"density\",\n \"errorbar\",\n \"function\",\n \"glm\",\n \"hist\", \"histogram\",\n \"hline\",\n \"j\", \"jitter\",\n \"lines\",\n \"lm\",\n \"loess\",\n \"pointrange\",\n \"points\",\n \"polygon\", \"polypath\",\n \"qq\",\n \"rect\",\n \"ribbon\",\n \"ridge\",\n \"rug\",\n \"segments\",\n \"spine\", \"spineplot\",\n \"spline\",\n \"summary\",\n \"text\",\n \"violin\",\n \"vline\"\n )\n assert_choice(type, known_types, null.ok = TRUE)\n\n if (is.null(type)) {\n if (!is.null(x) && (is.factor(x) || is.character(x)) && !(is.factor(y) || is.character(y))) {\n # enforce boxplot type for y ~ factor(x)\n type = type_boxplot\n } else if (is.factor(y) || is.character(y)) {\n # enforce spineplot type for factor(y) ~ x\n type = type_spineplot\n } else {\n type = \"p\"\n }\n }\n\n if (is.character(type)) type = switch(type,\n \"abline\" = type_abline,\n \"area\" = type_area,\n \"bar\" = type_barplot,\n \"barplot\" = type_barplot,\n \"box\" = type_boxplot,\n \"boxplot\" = type_boxplot,\n \"density\" = type_density,\n \"errorbar\" = type_errorbar,\n \"function\" = type_function,\n \"glm\" = type_glm,\n \"hist\" = type_histogram,\n \"histogram\" = type_histogram,\n \"hline\" = type_hline,\n \"j\" = type_jitter,\n \"jitter\" = type_jitter,\n \"lines\" = type_lines,\n \"lm\" = type_lm,\n \"loess\" = type_loess,\n \"p\" = type_points,\n \"pointrange\" = type_pointrange,\n \"points\" = type_points,\n \"polygon\" = type_polygon,\n \"polypath\" = type_polypath,\n \"qq\" = type_qq,\n \"rect\" = type_rect,\n \"ribbon\" = type_ribbon,\n \"ridge\" = type_ridge,\n \"rug\" = type_rug,\n \"segments\" = type_segments,\n \"spine\" = type_spineplot,\n \"spineplot\" = type_spineplot,\n \"spline\" = type_spline,\n \"summary\" = type_summary,\n \"text\" = type_text,\n \"violin\" = type_violin,\n \"vline\" = type_vline,\n type # default case\n )\n \n if (is.function(type)) {\n args = intersect(names(formals(type)), names(dots))\n args = if (length(args) >= 1L) dots[args] else list()\n type = do.call(type, args)\n type$dots = dots[setdiff(names(dots), names(args))]\n }\n \n if (inherits(type, \"tinyplot_type\")) return(type)\n\n out = list(draw = NULL, data = NULL, name = type)\n return(out)\n}\n"], ["/tinyplot/R/type_qq.R", "#' Quantile-Quantile plot (QQ)\n#'\n#' @description Plots the theoretical quantiles of `x` on the horizontal axis\n#' against observed values of `x` on the vertical axis.\n#'\n#' @param distribution Distribution function to use.\n#' @examples\n#' tinyplot(~mpg, data = mtcars, type = type_qq())\n#'\n#' # suppress the line\n#' tinyplot(~mpg, data = mtcars, lty = 0, type = type_qq())\n#' @importFrom stats qnorm ppoints quantile\n#' @export\ntype_qq = function(distribution = qnorm) {\n data_qq = function(distribution) {\n fun = function(datapoints, ...) {\n y = sort(datapoints$y)\n x = datapoints$x\n x = distribution(ppoints(x))\n datapoints$x = x\n datapoints$y = y\n out = list(datapoints = datapoints)\n return(out)\n }\n }\n\n draw_qq = function() {\n fun = function(ix, iy, icol, ibg, ipch, ilwd, ilty, cex, xlab, ...) {\n points(\n x = ix,\n y = iy,\n col = icol,\n bg = ibg,\n type = \"p\",\n pch = ipch,\n lwd = ilwd,\n cex = cex\n )\n\n if (!is.null(ilty)) {\n iy <- quantile(iy, c(0.25, 0.75))\n ix <- quantile(ix, c(0.25, 0.75))\n slope <- diff(iy) / diff(ix)\n intercept <- iy[1] - slope * ix[1]\n abline(a = intercept, b = slope, lty = ilty, col = icol, lwd = ilwd)\n }\n }\n return(fun)\n }\n\n out = list(\n draw = draw_qq(),\n data = data_qq(distribution = distribution),\n name = \"qq\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/tpar.R", "#' @title Set or query graphical parameters\n#'\n#' @description Extends \\code{\\link[graphics]{par}}, serving as a (near) drop-in\n#' replacement for setting or querying graphical parameters. The key\n#' differences is that, beyond supporting the standard group of R graphical\n#' parameters in \\code{\\link[graphics]{par}}, `tpar` also supports additional\n#' graphical parameters that are provided by `tinyplot`. Similar to\n#' \\code{\\link[graphics]{par}}, parameters are set by passing appropriate\n#' `key = value` argument pairs, and multiple parameters can be set or queried\n#' at the same time.\n#'\n#' @param ... arguments of the form `key = value`. This includes all of the\n#' parameters typically supported by \\code{\\link[graphics]{par}}, as well as\n#' the `tinyplot`-specific ones described in the 'Graphical Parameters'\n#' section below.\n#' @param hook Logical. If `TRUE`, base graphical parameters persist across \n#' plots via a hook applied before each new plot (see `?setHook`).\n#'\n#' @md\n#' @details The `tinyplot`-specific parameters are saved in an internal\n#' environment called `.tpar` for performance and safety reasons. However,\n#' they can also be set at package load time via \\code{\\link[base]{options}},\n#' which may prove convenient for users that want to enable different default\n#' behaviour at startup (e.g., through an `.Rprofile` file). These options all\n#' take a `tinyplot_*` prefix, e.g.\n#' `options(tinyplot_grid = TRUE, tinyplot_facet.bg = \"grey90\")`.\n#'\n#' For their part, any \"base\" graphical parameters are caught dynamically and\n#' passed on to \\code{\\link[graphics]{par}} as appropriate. Technically, only\n#' parameters that satisfy `par(..., no.readonly = TRUE)` are evaluated.\n#'\n#' However, note the important distinction: `tpar` only evaluates parameters\n#' from \\code{\\link[graphics]{par}} if they are passed _explicitly_ by the\n#' user. This means that `tpar` should not be used to capture the (invisible)\n#' state of a user's entire set of graphics parameters, i.e. `tpar()` !=\n#' `par()`. If you want to capture the _all_ existing graphics settings, then\n#' you should rather use `par()` instead.\n#'\n#' @returns When parameters are set, their previous values are returned in an\n#' invisible named list. Such a list can be passed as an argument to `tpar` to\n#' restore the parameter values.\n#'\n#' When just one parameter is queried, the value of that parameter is returned\n#' as (atomic) vector. When two or more parameters are queried, their values\n#' are returned in a list, with the list names giving the parameters.\n#'\n#' Note the inconsistency: setting one parameter returns a list, but querying\n#' one parameter returns a vector.\n#'\n#' @section Additional Graphical Parameters:\n#'\n#' * `adj.xlab`: Numeric value between 0 and 1 controlling the alignment of the x-axis label.\n#' * `adj.ylab`: Numeric value between 0 and 1 controlling the alignment of the y-axis label.\n#' * `cairo`: Logical indicating whether \\code{\\link[grDevices]{cairo_pdf}} should be used when writing plots to PDF. If `FALSE`, then \\code{\\link[grDevices]{pdf}} will be used instead, with implications for embedding (non-standard) fonts. Only used if `tinyplot(..., file = \".pdf\")` is called. Defaults to the value of `capabilities(\"cairo\")`.\n#' * `dynmar`: Logical indicating whether `tinyplot` should attempt dynamic adjustment of margins to reduce whitespace and/or account for spacing of text elements (e.g., long horizontal y-axis labels). Note that this parameter is tightly coupled to internal `tinythemes()` logic and should _not_ be adjusted manually unless you really know what you are doing or don't mind risking unintended consequences to your plot.\n#' * `facet.bg`: Character or integer specifying the facet background colour. If an integer, will correspond to the user's default colour palette (see `palette`). Passed to `rect`. Defaults to `NULL` (none).\n#' * `facet.border`: Character or integer specifying the facet border colour. If an integer, will correspond to the user's default colour palette (see `palette`). Passed to `rect`. Defaults to `NA` (none).\n#' * `facet.cex`: Expansion factor for facet titles. Defaults to `1`.\n#' * `facet.col`: Character or integer specifying the facet text colour. If an integer, will correspond to the user's default global colour palette (see `palette`). Defaults to `NULL`, which is equivalent to \"black\".\n#' * `facet.font`: An integer corresponding to the desired font face for facet titles. For most font families and graphics devices, one of four possible values: `1` (regular), `2` (bold), `3` (italic), or `4` (bold italic). Defaults to `NULL`, which is equivalent to `1` (i.e., regular).\n#' * `file.height`: Numeric specifying the height (in inches) of any plot that is written to disk using the `tinyplot(..., file = X)` argument. Defaults to `7`.\n#' * `file.res`: Numeric specifying the resolution (in dots per square inch) of any plot that is written to disk in bitmap format (i.e., PNG or JPEG) using the `tinyplot(..., file = X)` argument. Defaults to `300`.\n#' * `file.width`: Numeric specifying the width (in inches) of any plot that is written to disk using the `tinyplot(..., file = X)` argument. Defaults to `7`.\n#' * `fmar`: A numeric vector of form `c(b,l,t,r)` for controlling the (base) margin padding, in terms of lines, between the individual facets in a faceted plot. Defaults to `c(1,1,1,1)`. If more than three facets are detected, the `fmar` parameter is scaled by 0.75 to reduce excess whitespace. For 2x2 plots, the padding better matches the `cex` expansion logic of base graphics.\n#' * `grid.col`: Character or (integer) numeric that specifies the color of the panel grid lines. Defaults to `\"lightgray\"`.\n#' * `grid.lty`: Character or (integer) numeric that specifies the line type of the panel grid lines. Defaults to `\"dotted\"`.\n#' * `grid.lwd`: Non-negative numeric giving the line width of the panel grid lines. Defaults to `1`.\n#' * `grid`: Logical indicating whether a background panel grid should be added to plots automatically. Defaults to `NULL`, which is equivalent to `FALSE`.\n#' * `lmar`: A numeric vector of form `c(inner, outer)` that gives the margin padding, in terms of lines, around the automatic `tinyplot` legend. Defaults to `c(1.0, 0.1)`. The inner margin is the gap between the legend and the plot region, and the outer margin is the gap between the legend and the edge of the graphics device.\n#' * `palette.qualitative`: Palette for qualitative colors. See the `palette` argument in `?tinyplot`.\n#' * `palette.sequential`: Palette for sequential colors. See the `palette` argument in `?tinyplot`.\n#' * `ribbon.alpha`: Numeric factor in the range `[0,1]` for modifying the opacity alpha of \"ribbon\" and \"area\" type plots. Default value is `0.2`.\n#'\n#' @importFrom graphics par\n#' @importFrom utils modifyList\n#' \n#' @seealso [`graphics::par`] which `tpar` builds on top of. [`get_saved_par`]\n#' is a convenience function for retrieving graphical parameters at different\n#' stages of a `tinyplot` call (and used for internal accounting purposes).\n#' [`tinytheme`] allows users to easily set a group of graphics parameters\n#' in a single function call, according to a variety of predefined themes.\n#' \n#' @examples\n#' # Return a list of existing base and tinyplot graphic params\n#' tpar(\"las\", \"pch\", \"facet.bg\", \"facet.cex\", \"grid\")\n#'\n#' # Simple facet plot with these default values\n#' tinyplot(mpg ~ wt, data = mtcars, facet = ~am)\n#'\n#' # Set params to something new. Similar to graphics::par(), note that we save\n#' # the existing values at the same time by assigning to an object.\n#' op = tpar(\n#' las = 1,\n#' pch = 2,\n#' facet.bg = \"grey90\",\n#' facet.cex = 2,\n#' grid = TRUE\n#' )\n#'\n#' # Re-plot with these new params\n#' tinyplot(mpg ~ wt, data = mtcars, facet = ~am)\n#'\n#' # Reset back to original values\n#' tpar(op)\n#'\n#' # Important: tpar() only evalutes parameters that have been passed explicitly\n#' # by the user. So it it should not be used to query and set (restore)\n#' # parameters that weren't explicitly requested, i.e. tpar() != par().\n#'\n#' # Note: The tinyplot-specific parameters can also be be set via `options`\n#' # with a `tinyplot_*` prefix, which can be convenient for enabling\n#' # different default behaviour at startup time (e.g., via an .Rprofile\n#' # file). Example:\n#' # options(tinyplot_grid = TRUE, tinyplot_facet.bg = \"grey90\")\n#'\n#' @export\ntpar = function(..., hook = FALSE) {\n\n opts = list(...)\n if (length(opts) == 1 && is.null(names(opts))) {\n if (inherits(opts[[1]], \"list\") && !is.null(names(opts[[1]]))) {\n opts = opts[[1]]\n }\n }\n\n ###### Assign parameters\n\n # assign tinyplot-specific arguments with known names to .tpar\n assign_tpar(opts)\n\n # return informative error messages if the input is invalid\n assert_tpar(.tpar)\n\n # if tpar(...) includes arguments that are not known to be tinyplot-specific,\n # we set a hook to set them using par() when the graphic device is started\n nam = names(opts)\n if (!is.null(nam)) {\n base_par = setdiff(nam, known_tpar)\n base_par = opts[base_par]\n if (length(base_par) > 0) {\n if (isTRUE(hook)) {\n # append new hook to existing ones\n new_hooks = list(\"before.plot.new\" = function() par(base_par))\n set_hooks(new_hooks, action = \"append\")\n # save new hook to tinyplot environment for later removal\n old_hooks = get_environment_variable(\".tpar_hooks\")\n set_environment_variable(\".tpar_hooks\", c(old_hooks, new_hooks))\n } else {\n par_names = names(par(no.readonly = TRUE))\n base_par = base_par[names(base_par) %in% par_names]\n base_par_old = par(base_par)\n par(base_par)\n }\n }\n }\n\n\n ###### Retrieve parameters\n\n # User didn't assign any new values, but may have requested explicit (print\n # of) some existing value(s)\n tpar_old = as.list(.tpar)\n if (is.null(nam)) {\n known_par = names(par(no.readonly = TRUE))\n if (!is.null(nam)) {\n used_par = intersect(nam, known_par)\n } else {\n used_par = intersect(opts, known_par)\n }\n if (length(used_par)) {\n if (!is.null(nam)) used_par = opts[used_par]\n used_par_old = par(used_par)\n tpar_old = modifyList(as.list(.tpar), used_par_old, keep.null = TRUE)\n }\n if (!is.null(opts) && length(opts) != 0) {\n # specific values requested\n opts = Filter(is.character, opts)\n ret = (`names<-`(lapply(opts, function(x) .tpar[[x]]), opts))\n if (length(used_par)) {\n ret_par = par(used_par)\n ret = modifyList(ret, ret_par, keep.null = TRUE)\n }\n if (length(ret) == 1) ret = ret[[1]]\n return(ret)\n } else {\n # no specific request; return all existing values invisibly\n return(invisible(tpar_old))\n }\n # assign new values, but still return old values for saving existing settings\n # a la `oldpar = par(param = new_value)`\n } else {\n `names<-`(lapply(nam, function(x) .tpar[[x]]), nam)\n if (length(base_par) > 0 && isFALSE(hook)) tpar_old = modifyList(tpar_old, base_par_old, keep.null = TRUE)\n return(invisible(tpar_old))\n }\n}\n\n\n# Two levels of priority: .tpar[[\"name\"]] -> par(\"name\")\nget_tpar = function(opts, default = NULL) {\n # parameter priority\n # .tpar[[\"name\"]] -> par(\"name\")\n for (o in opts) {\n tp = .tpar[[o]]\n if (!is.null(tp)) {\n return(tp)\n } else {\n p = suppressWarnings(par(o))\n if (!is.null(p)) {\n return(p)\n }\n }\n\n }\n return(default)\n}\n\n\nknown_tpar = c(\n \"adj.main\",\n \"adj.sub\",\n \"adj.xlab\",\n \"adj.ylab\",\n \"cex.xlab\",\n \"cex.ylab\",\n \"col.xaxs\",\n \"col.yaxs\",\n \"cairo\",\n \"dynmar\",\n \"facet.bg\",\n \"facet.border\",\n \"facet.cex\",\n \"facet.col\",\n \"facet.font\",\n \"file.height\",\n \"file.res\",\n \"file.width\",\n \"fmar\",\n \"grid\",\n \"grid.bg\",\n \"grid.col\",\n \"grid.lty\",\n \"grid.lwd\",\n \"lmar\",\n \"lty.xaxs\",\n \"lty.yaxs\",\n \"lwd.xaxs\",\n \"lwd.yaxs\",\n \"lwd.axis\",\n \"pch\",\n \"palette.qualitative\",\n \"palette.sequential\",\n \"ribbon.alpha\",\n \"side.sub\",\n \"tinytheme\",\n \"xaxt\",\n \"yaxt\"\n)\n\n\nassign_tpar = function(opts) {\n for (n in intersect(names(opts), known_tpar)) {\n .tpar[[n]] = opts[[n]]\n }\n}\n\n\nassert_tpar = function(.tpar) {\n assert_numeric(.tpar[[\"adj.main\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"adj.main\")\n assert_numeric(.tpar[[\"adj.sub\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"adj.sub\")\n assert_numeric(.tpar[[\"adj.xlab\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"adj.xlab\")\n assert_numeric(.tpar[[\"adj.ylab\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"adj.ylab\")\n assert_flag(.tpar[[\"cairo\"]], name = \"cairo\")\n assert_flag(.tpar[[\"dynmar\"]], null.ok = FALSE, name = \"dynmar\")\n assert_numeric(.tpar[[\"lmar\"]], len = 2, null.ok = TRUE, name = \"lmar\")\n assert_numeric(.tpar[[\"ribbon.alpha\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"ribbon.alpha\")\n assert_numeric(.tpar[[\"grid.lwd\"]], len = 1, lower = 0, null.ok = TRUE, name = \"grid.lwd\")\n assert_flag(.tpar[[\"grid\"]], null.ok = TRUE, name = \"grid\")\n assert_numeric(.tpar[[\"file.res\"]], len = 1, lower = 0, null.ok = TRUE, name = \"file.res\")\n assert_numeric(.tpar[[\"file.height\"]], len = 1, lower = 0, null.ok = TRUE, name = \"file.height\")\n assert_numeric(.tpar[[\"file.width\"]], len = 1, lower = 0, null.ok = TRUE, name = \"file.width\")\n assert_numeric(.tpar[[\"facet.font\"]], len = 1, null.ok = TRUE, name = \"facet.font\")\n assert_numeric(.tpar[[\"facet.cex\"]], len = 1, null.ok = TRUE, name = \"facet.cex\")\n assert_numeric(.tpar[[\"side.sub\"]], len = 1, null.ok = TRUE, name = \"side.sub\")\n assert_string(.tpar[[\"grid.bg\"]], null.ok = TRUE, name = \"grid.bg\")\n assert_numeric(.tpar[[\"fmar\"]], len = 4, null.ok = TRUE, name = \"fmar\")\n\n facet.col = .tpar[[\"facet.col\"]]\n if (!is.null(facet.col)) {\n if (!is.null(facet.col) && !is.numeric(facet.col) && !is.character(facet.col)) {\n stop(\"facet.col needs to be NULL, or a numeric or character\", call. = FALSE)\n }\n assert_true(length(facet.col) == 1, name = \"length(facet.col)==1\")\n }\n\n facet.bg = .tpar$facet.bg\n if (!is.null(facet.bg)) {\n if (!is.numeric(facet.bg) && !is.character(facet.bg)) {\n stop(\"facet.bg needs to be NULL, or a numeric or character\", call. = FALSE)\n }\n assert_true(length(facet.bg) == 1, name = \"length(facet.bg)==1\")\n }\n\n facet.border = .tpar$facet.border\n if (!is.null(facet.border)) {\n if (!is.numeric(facet.border) && !is.character(facet.border) && !is.na(facet.border)) {\n stop(\"facet.border needs to be NULL, or a numeric, character, or NA\", call. = FALSE)\n }\n assert_true(length(facet.border) == 1, name = \"length(facet.border)==1\")\n }\n}\n\n\ninit_tpar = function(rm_hook = FALSE) {\n rm(list = names(.tpar), envir = .tpar)\n\n if (isTRUE(rm_hook)) {\n old_hooks = get_environment_variable(\".tpar_hooks\")\n if (length(old_hooks) > 0) {\n remove_hooks(old_hooks)\n set_environment_variable(\".tpar_hooks\", NULL)\n }\n }\n\n .tpar$cairo = if (is.null(getOption(\"tinyplot_cairo\"))) capabilities(\"cairo\") else as.logical(getOption(\"tinyplot_cairo\"))\n \n \n .tpar$dynmar = if (is.null(getOption(\"tinyplot_dynmar\"))) FALSE else as.logical(getOption(\"tinyplot_dynmar\"))\n \n # Figure output options if written to file\n .tpar$file.width = if (is.null(getOption(\"tinyplot_file.width\"))) 7 else as.numeric(getOption(\"tinyplot_file.width\"))\n .tpar$file.height = if (is.null(getOption(\"tinyplot_file.height\"))) 7 else as.numeric(getOption(\"tinyplot_file.height\"))\n .tpar$file.res = if (is.null(getOption(\"tinyplot_file.res\"))) 300 else as.numeric(getOption(\"tinyplot_file.res\"))\n\n # Facet margin, i.e. gap between the individual facet windows\n .tpar$fmar = if (is.null(getOption(\"tinyplot_fmar\"))) c(1, 1, 1, 1) else as.numeric(getOption(\"tinyplot_fmar\"))\n\n # Other facet options\n .tpar$facet.cex = if (is.null(getOption(\"tinyplot_facet.cex\"))) 1 else as.numeric(getOption(\"tinyplot_facet.cex\"))\n .tpar$facet.font = if (is.null(getOption(\"tinyplot_facet.font\"))) NULL else as.numeric(getOption(\"tinyplot_facet.font\"))\n .tpar$facet.col = if (is.null(getOption(\"tinyplot_facet.col\"))) NULL else getOption(\"tinyplot_facet.col\")\n .tpar$facet.bg = if (is.null(getOption(\"tinyplot_facet.bg\"))) NULL else getOption(\"tinyplot_facet.bg\")\n .tpar$facet.border = if (is.null(getOption(\"tinyplot_facet.border\"))) NA else getOption(\"tinyplot_facet.border\")\n\n # Plot grid\n .tpar$grid = if (is.null(getOption(\"tinyplot_grid\"))) FALSE else as.logical(getOption(\"tinyplot_grid\"))\n .tpar$grid.col = if (is.null(getOption(\"tinyplot_grid.col\"))) \"lightgray\" else getOption(\"tinyplot_grid.col\")\n .tpar$grid.lty = if (is.null(getOption(\"tinyplot_grid.lty\"))) \"dotted\" else getOption(\"tinyplot_grid.lty\")\n .tpar$grid.lwd = if (is.null(getOption(\"tinyplot_grid.lwd\"))) 1 else as.numeric(getOption(\"tinyplot_grid.lwd\"))\n\n # Legend margin, i.e. gap between the legend and the plot elements\n .tpar$lmar = if (is.null(getOption(\"tinyplot_lmar\"))) c(1.0, 0.1) else as.numeric(getOption(\"tinyplot_lmar\"))\n\n # Alpha fill (transparency) default for ribbon and area plots\n .tpar$ribbon.alpha = if (is.null(getOption(\"tinyplot_ribbon.alpha\"))) 0.2 else as.numeric(getOption(\"tinyplot_ribbon.alpha\"))\n}\n"], ["/tinyplot/R/type_summary.R", "#' Plot summary values of `y` at unique values of `x`\n#'\n#' @md\n#' @description\n#' Applies a summary function to `y` along unique values of `x`. For example,\n#' plot the mean `y` value for each `x` value. Internally,\n#' `type_summary()` applies a thin wrapper around \\code{\\link[stats]{ave}} and\n#' then passes the result to [`type_lines`] for drawing.\n#'\n#' @param fun summarizing function. Should be compatible with\n#' \\code{\\link[stats]{ave}}. Defaults to \\code{\\link[base]{mean}}.\n#' @param ... Additional arguments are passed to the `lines()` function,\n#' ex: `type=\"p\"`, `col=\"pink\"`.\n#' @seealso [`ave`] which performs the summarizing (averaging) behind the\n#' scenes.\n#' @examples\n#' # Plot the mean chick weight over time\n#' tinyplot(weight ~ Time, data = ChickWeight, type = \"summary\")\n#' \n#' # Note: \"mean\" is the default function, so these are also equivalent:\n#' # tinyplot(weight ~ Time, data = ChickWeight, type = type_summary())\n#' # tinyplot(weight ~ Time, data = ChickWeight, type = type_summary(mean))\n#' \n#' # Plot the median instead\n#' tinyplot(weight ~ Time, data = ChickWeight, type = type_summary(median))\n#' \n#' # Works with groups and/or facets too\n#' tinyplot(weight ~ Time | Diet, facet = \"by\", data = ChickWeight, type = \"summary\")\n#'\n#' # Custom/complex function example\n#' tinyplot(\n#' weight ~ Time | Diet, facet = \"by\", data = ChickWeight,\n#' type = type_summary(function(y) quantile(y, probs = 0.9)/max(y))\n#' )\n#' \n#' @importFrom stats ave\n#' @export\ntype_summary = function(fun = mean, ...) {\n assert_function(fun)\n lines_args = list(...)\n data_summary = function(fun) {\n funky = function(datapoints, ...) {\n datapoints = split(datapoints, list(datapoints$facet, datapoints$by), drop = TRUE)\n datapoints = lapply(datapoints, function(dat) {\n newy = ave(dat$y, dat$x, FUN = fun)\n dat$y = newy\n dat = dat[order(dat$x), ]\n return(dat)\n })\n datapoints = do.call(rbind, datapoints)\n out = list(datapoints = datapoints)\n return(out)\n }\n return(funky)\n }\n out = list(\n draw = draw_lines(...),\n data = data_summary(fun = fun),\n name = \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_text.R", "#' Text annotations plot type\n#'\n#' @description Type function for adding text annotations to a plot. This function allows\n#' you to draw text at specified (x,y) coordinates.\n#'\n#' @param labels Character vector of length 1 or of the same length as the\n#' number of x,y coordinates.\n#' @param font Font to be used, following [graphics::par()].\n#' @param xpd Logical value or `NA` denoting text clipping behaviour, following\n#' [graphics::par()].\n#' @param srt Numeric giving the desired string rotation in degrees.\n#' @inheritParams graphics::text\n#' @examples\n#' tinyplot(mpg ~ hp | factor(cyl),\n#' data = mtcars,\n#' type = type_text(\n#' labels = row.names(mtcars),\n#' font = 2,\n#' adj = 0\n#' )\n#' )\n#' \n#' # to avoid clipping text at the plot region, we can use xpd = NA\n#' tinyplot(mpg ~ hp | factor(cyl),\n#' data = mtcars,\n#' type = type_text(\n#' labels = row.names(mtcars),\n#' font = 2,\n#' adj = 0,\n#' xpd = NA\n#' )\n#' )\n#'\n#' @export\ntype_text = function(labels, adj = NULL, pos = NULL, offset = 0.5, vfont = NULL, font = NULL, xpd = NULL, srt = 0) {\n out = list(\n draw = draw_text(adj = adj, pos = pos, offset = offset, vfont = vfont, font = font, xpd = xpd, srt = srt),\n data = data_text(labels = labels),\n name = \"text\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\ndata_text = function(labels) {\n fun = function(datapoints, ...) {\n if (length(labels) != 1 && length(labels) != nrow(datapoints)) {\n msg <- sprintf(\"`labels` must be of length 1 or %s.\", nrow(datapoints))\n stop(msg, call. = FALSE)\n }\n datapoints$labels = labels\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\ndraw_text = function(adj = NULL, pos = NULL, offset = 0.5, vfont = NULL, font = NULL, xpd = NULL, srt = 0) {\n if (is.null(xpd)) xpd = par(\"xpd\")\n fun = function(ix, iy, ilabels, icol, cex, ...) {\n text(\n x = ix, y = iy, labels = ilabels, col = icol,\n adj = adj, pos = pos, offset = offset,\n vfont = vfont, font = font,\n xpd = xpd,\n srt = srt,\n cex = cex\n )\n }\n}\n"], ["/tinyplot/R/type_vline.R", "#' @param v x-value(s) for vertical line(s). Numeric of length 1, or equal to\n#' the number of groups or number of facets (or the product thereof).\n#' @rdname type_abline\n#' @export\ntype_vline = function(v = 0) {\n assert_numeric(v)\n data_vline = function(datapoints, lwd, lty, col, ...) {\n if (nrow(datapoints) == 0) {\n msg = \"`type_vline() only works on existing plots with x and y data points.\"\n stop(msg, call. = FALSE)\n }\n # keep track of unique lty and lwd (needed for group catch / escape hatch\n # later in draw_hline)\n ul_lwd = length(unique(lwd))\n ul_lty = length(unique(lty))\n ul_col = length(unique(col))\n return(list(type_info = list(ul_lty = ul_lty, ul_lwd = ul_lwd, ul_col = ul_col)))\n }\n draw_vline = function() {\n fun = function(\n ifacet, iby, data_facet, icol, ilty, ilwd,\n ngrps, nfacets, by_continuous, facet_by,\n type_info,\n ...\n ) {\n\n # flag for aesthetics by groups\n grp_aes = type_info[[\"ul_col\"]] == 1 || type_info[[\"ul_lty\"]] == ngrps || type_info[[\"ul_lwd\"]] == ngrps\n \n if (length(v) != 1) {\n if (!length(v) %in% c(ngrps, nfacets, ngrps*nfacets)) {\n msg = \"Length of 'v' must be 1, or equal to the number of facets or number of groups (or product thereof).\"\n stop(msg, call. = FALSE)\n }\n if (!facet_by && length(v) == nfacets) {\n v = v[ifacet]\n if (!grp_aes && type_info[[\"ul_col\"]]!=ngrps) {\n icol = 1\n } else if (by_continuous) {\n icol = 1\n }\n } else if (!by_continuous && length(v) == ngrps * nfacets) {\n v = v[ifacet * ngrps - c(ngrps - iby)]\n } else if (!by_continuous) {\n v = v[iby]\n }\n } else if (!grp_aes) {\n icol = 1\n }\n \n abline(v = v, col = icol, lty = ilty, lwd = ilwd)\n }\n return(fun)\n }\n out = list(\n draw = draw_vline(),\n data = data_vline,\n name = \"vline\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_hline.R", "#' @rdname type_abline\n#' @param h y-value(s) for horizontal line(s). Numeric of length 1, or equal to\n#' the number of groups or number of facets (or the product thereof).\n#' @export\ntype_hline = function(h = 0) {\n assert_numeric(h)\n data_hline = function(datapoints, lwd, lty, col, ...) {\n if (nrow(datapoints) == 0) {\n msg = \"`type_hline() only works on existing plots with x and y data points.\"\n stop(msg, call. = FALSE)\n }\n # keep track of unique lty and lwd (needed for group catch / escape hatch\n # later in draw_hline)\n ul_lwd = length(unique(lwd))\n ul_lty = length(unique(lty))\n ul_col = length(unique(col))\n return(list(type_info = list(ul_lty = ul_lty, ul_lwd = ul_lwd, ul_col = ul_col)))\n }\n draw_hline = function() {\n fun = function(\n ifacet, iby, data_facet, icol, ilty, ilwd,\n ngrps, nfacets, by_continuous, facet_by,\n type_info,\n ...\n ) {\n \n # flag for aesthetics by groups\n grp_aes = type_info[[\"ul_col\"]] == 1 || type_info[[\"ul_lty\"]] == ngrps || type_info[[\"ul_lwd\"]] == ngrps\n \n if (length(h) != 1) {\n if (!length(h) %in% c(ngrps, nfacets, ngrps*nfacets)) {\n msg = \"Length of 'h' must be 1, or equal to the number of facets or number of groups (or product thereof).\"\n stop(msg, call. = FALSE)\n }\n if (!facet_by && length(h) == nfacets) {\n h = h[ifacet]\n if (!grp_aes && type_info[[\"ul_col\"]]!=ngrps) {\n icol = 1\n } else if (by_continuous) {\n icol = 1\n }\n } else if (!by_continuous && length(h) == ngrps * nfacets) {\n h = h[ifacet * ngrps - c(ngrps - iby)]\n } else if (!by_continuous) {\n h = h[iby]\n }\n } else if (!grp_aes) {\n icol = 1\n }\n\n abline(h = h, col = icol, lty = ilty, lwd = ilwd)\n }\n return(fun)\n }\n out = list(\n draw = draw_hline(),\n data = data_hline,\n name = \"hline\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_function.R", "#' Plot a function\n#'\n#' @details\n#' When using `type_function()` in a `tinyplot()` call, the `x` value indicates\n#' the range of values to plot on the x-axis.\n#'\n#' @param fun Function of `x` to plot. Defaults to \\code{\\link[stats]{dnorm}}.\n#' @param args List of additional arguments to be passed to `fun`.\n#' @param n Number of points to interpolate on the x axis.\n#' @param ... Additional arguments are passed to the `lines()` function,\n#' ex: `type=\"p\"`, `col=\"pink\"`.\n#' @importFrom stats dnorm\n#' \n#' @examples\n#' # Plot the normal density (default function)\n#' tinyplot(x = -4:4, type = \"function\")\n#' # tinyplot(x = -4:4, type = type_function()) # same\n#'\n#' # Customize by passing explicit arguments to your function\n#' tinyplot(x = -1:10, type = type_function(\n#' fun = dnorm, args = list(mean = 3)\n#' ))\n#'\n#' # Additional arguments are passed to the `lines()` function.\n#' tinyplot(x = -4:4, type = type_function(\n#' fun = dnorm,\n#' col = \"pink\", type = \"p\", pch = 3\n#' ))\n#' \n#' # Custom function example\n#' ## (Here using `function(x)`, but you could also use the shorter `\\(x)`\n#' ## anonymous function syntax introduced in R 4.1.0)\n#' tinyplot(x = -4:4, type = type_function(fun = function(x) 0.5 * exp(-abs(x))))\n#'\n#' @export\ntype_function = function(fun = dnorm, args = list(), n = 101, ...) {\n assert_function(fun)\n lines_args = list(...)\n data_function = function(args, fun) {\n funky = function(xlim, ylim, datapoints, ...) {\n if (nrow(datapoints) == 0 || !\"x\" %in% names(datapoints)) {\n stop(\"Need to provide x values to plot the function.\", call. = FALSE)\n }\n if (is.null(xlim)) {\n xlim = range(datapoints[[\"x\"]])\n }\n if (is.null(ylim)) {\n tmp = c(list(datapoints[[\"x\"]]), args)\n tmp = range(tmp)\n tmp = seq(tmp[1], tmp[2], length.out = n)\n tmp = c(list(tmp), args)\n tmp = do.call(fun, tmp)\n ylim = c(min(tmp), max(tmp))\n }\n out = list(xlim = xlim, ylim = ylim)\n return(out)\n }\n }\n draw_function = function() {\n funky = function(ifacet, data_facet, ...) {\n xrange = range(data_facet[[ifacet]][[\"x\"]])\n x = seq(xrange[1], xrange[2], length.out = n)\n y = do.call(fun, c(list(x), args))\n tmp = c(list(x, y), lines_args)\n do.call(lines, tmp)\n }\n return(funky)\n }\n out = list(\n draw = draw_function(),\n data = data_function(args = args, fun = fun),\n name = \"function\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/lim.R", "# calculate limits of each plot\n\nlim_args = function(\n datapoints,\n xlim, ylim,\n xaxb = NULL, yaxb = NULL,\n xlim_user = FALSE, ylim_user = FALSE,\n type\n) {\n \n if (is.null(xlim)) {\n xlim = range(c(datapoints[[\"x\"]], datapoints[[\"xmin\"]],\n datapoints[[\"xmax\"]]), finite = TRUE)\n }\n if (is.null(ylim)) {\n ylim = range(c(datapoints[[\"y\"]], datapoints[[\"ymin\"]],\n datapoints[[\"ymax\"]]), finite = TRUE)\n }\n\n if (identical(type, \"boxplot\")) {\n xlim = xlim + c(-0.5, 0.5)\n }\n \n if (!xlim_user && !is.null(xaxb) && type != \"spineplot\") xlim = range(c(xlim, xaxb))\n if (!ylim_user && !is.null(yaxb) && type != \"spineplot\") ylim = range(c(ylim, yaxb))\n\n out = list(xlim = xlim, ylim = ylim)\n return(out)\n}\n\n"], ["/tinyplot/R/draw_legend.R", "#' @title Calculate placement of legend and draw it\n#' \n#' @description Function used to calculate the placement of (including\n#' outside the plotting area) and drawing of legend.\n#' \n#' @md\n#' @param legend Legend placement keyword or list, passed down from [tinyplot].\n#' @param legend_args Additional legend arguments to be passed to\n#' \\code{\\link[graphics]{legend}}.\n#' @param by_dep The (deparsed) \"by\" grouping variable name.\n#' @param lgnd_labs The labels passed to `legend(legend = ...)`.\n#' @param type Plotting type(s), passed down from [tinyplot].\n#' @param pch Plotting character(s), passed down from [tinyplot].\n#' @param lty Plotting linetype(s), passed down from [tinyplot].\n#' @param lwd Plotting line width(s), passed down from [tinyplot].\n#' @param col Plotting colour(s), passed down from [tinyplot].\n#' @param bg Plotting character background fill colour(s), passed down from [tinyplot].\n#' @param cex Plotting character expansion(s), passed down from [tinyplot].\n#' @param gradient Logical indicating whether a continuous gradient swatch\n#' should be used to represent the colors.\n#' @param lmar Legend margins (in lines). Should be a numeric vector of the form\n#' `c(inner, outer)`, where the first number represents the \"inner\" margin\n#' between the legend and the plot, and the second number represents the\n#' \"outer\" margin between the legend and edge of the graphics device. If no\n#' explicit value is provided by the user, then reverts back to `tpar(\"lmar\")`\n#' for which the default values are `c(1.0, 0.1)`.\n#' @param has_sub Logical. Does the plot have a sub-caption. Only used if\n#' keyword position is \"bottom!\", in which case we need to bump the legend\n#' margin a bit further.\n#' @param new_plot Logical. Should we be calling plot.new internally?\n#' @param draw Logical. If `FALSE`, no legend is drawn but the sizes are\n#' returned. Note that a new (blank) plot frame will still need to be started\n#' in order to perform the calculations. \n#' \n#' @returns No return value, called for side effect of producing a(n empty) plot\n#' with a legend in the margin.\n#' \n#' @importFrom graphics grconvertX grconvertY rasterImage strwidth\n#' @importFrom grDevices as.raster recordGraphics\n#' @importFrom utils modifyList\n#' \n#' @examples\n#' oldmar = par(\"mar\")\n#' \n#' draw_legend(\n#' legend = \"right!\", ## default (other options incl, \"left(!)\", \"\"bottom(!)\", etc.)\n#' legend_args = list(title = \"Key\", bty = \"o\"),\n#' lgnd_labs = c(\"foo\", \"bar\"),\n#' type = \"p\",\n#' pch = 21:22,\n#' col = 1:2\n#' )\n#' \n#' # The legend is placed in the outer margin...\n#' box(\"figure\", col = \"cyan\", lty = 4)\n#' # ... and the plot is proportionally adjusted against the edge of this\n#' # margin.\n#' box(\"plot\")\n#' # You can add regular plot objects per normal now\n#' plot.window(xlim = c(1,10), ylim = c(1,10))\n#' points(1:10)\n#' points(10:1, pch = 22, col = \"red\")\n#' axis(1); axis(2)\n#' # etc.\n#' \n#' # Important: A side effect of draw_legend is that the inner margins have been\n#' # adjusted. (Here: The right margin, since we called \"right!\" above.)\n#' par(\"mar\")\n#' \n#' # To reset you should call `dev.off()` or just reset manually.\n#' par(mar = oldmar)\n#' \n#' # Note that the inner and outer margin of the legend itself can be set via\n#' # the `lmar` argument. (This can also be set globally via\n#' # `tpar(lmar = c(inner, outer))`.)\n#' draw_legend(\n#' legend_args = list(title = \"Key\", bty = \"o\"),\n#' lgnd_labs = c(\"foo\", \"bar\"),\n#' type = \"p\",\n#' pch = 21:22,\n#' col = 1:2,\n#' lmar = c(0, 0.1) ## set inner margin to zero\n#' )\n#' box(\"figure\", col = \"cyan\", lty = 4)\n#' \n#' par(mar = oldmar)\n#' \n#' # Continuous (gradient) legends are also supported\n#' draw_legend(\n#' legend = \"right!\",\n#' legend_args = list(title = \"Key\"),\n#' lgnd_labs = LETTERS[1:5],\n#' col = hcl.colors(5),\n#' gradient = TRUE ## enable gradient legend\n#' )\n#' \n#' par(mar = oldmar)\n#' \n#' @export\ndraw_legend = function(\n legend = NULL,\n legend_args = NULL,\n by_dep = NULL,\n lgnd_labs = NULL,\n type = NULL,\n pch = NULL,\n lty = NULL,\n lwd = NULL,\n col = NULL,\n bg = NULL,\n cex = NULL,\n gradient = FALSE,\n lmar = NULL,\n has_sub = FALSE,\n new_plot = TRUE,\n draw = TRUE\n) {\n \n if (is.null(lmar)) {\n lmar = tpar(\"lmar\")\n } else {\n if (!is.numeric(lmar) || length(lmar)!=2) stop (\"lmar must be a numeric of length 2.\")\n }\n \n assert_logical(gradient)\n assert_logical(has_sub)\n assert_logical(new_plot)\n assert_logical(draw)\n \n #\n ## legend args ----\n \n if (is.null(legend_args[[\"x\"]])) {\n if (is.null(legend)) {\n legend_args[[\"x\"]] = \"right!\"\n } else if (is.character(legend)) {\n legend_args = utils::modifyList(legend_args, list(x = legend))\n } else if (class(legend) %in% c(\"call\", \"name\")) {\n largs = as.list(legend)\n if (is.null(largs[[\"x\"]])) {\n lnms = names(largs)\n # check second position b/c first will be a symbol \n if (is.null(lnms)) {\n largs = stats::setNames(largs, c(\"\", \"x\"))\n } else if (length(largs)>=2 && lnms[2] == \"\") {\n lnms[2] = \"x\"\n largs = stats::setNames(largs, lnms)\n } else {\n largs[[\"x\"]] = \"right!\"\n }\n }\n # Finally, combine with any pre-existing legend args (e.g., title from the by label)\n legend_args = utils::modifyList(legend_args, largs, keep.null = TRUE)\n }\n }\n \n ## Use `!exists` rather than `is.null` for title in case user specified no title\n if (!exists(\"title\", where = legend_args)) legend_args[[\"title\"]] = by_dep\n \n legend_args[[\"pch\"]] = legend_args[[\"pch\"]] %||% pch\n legend_args[[\"lty\"]] = legend_args[[\"lty\"]] %||% lty\n legend_args[[\"col\"]] = legend_args[[\"col\"]] %||% col\n legend_args[[\"bty\"]] = legend_args[[\"bty\"]] %||% \"n\"\n legend_args[[\"horiz\"]] = legend_args[[\"horiz\"]] %||% FALSE\n legend_args[[\"xpd\"]] = legend_args[[\"xpd\"]] %||% NA\n \n if (!isTRUE(type %in% c(\"p\", \"ribbon\", \"polygon\", \"polypath\"))) {\n legend_args[[\"lwd\"]] = legend_args[[\"lwd\"]] %||% lwd\n }\n \n if (isTRUE(type %in% c(\"p\", \"pointrange\", \"errorbar\")) && (length(col) == 1 || length(cex) == 1)) {\n legend_args[[\"pt.cex\"]] = legend_args[[\"pt.cex\"]] %||% cex\n }\n \n # turn off inner line for \"barplot\" type\n if (identical(type, \"barplot\")) {\n legend_args[[\"lty\"]] = 0\n }\n \n if (isTRUE(type %in% c(\"rect\", \"ribbon\", \"polygon\", \"polypath\", \"boxplot\", \"hist\", \"histogram\", \"spineplot\", \"ridge\", \"barplot\", \"violin\")) || gradient) {\n legend_args[[\"pch\"]] = 22\n legend_args[[\"pt.cex\"]] = legend_args[[\"pt.cex\"]] %||% 3.5\n legend_args[[\"y.intersp\"]] = legend_args[[\"y.intersp\"]] %||% 1.25\n legend_args[[\"seg.len\"]] = legend_args[[\"seg.len\"]] %||% 1.25\n }\n \n if (isTRUE(type %in% c(\"ribbon\", \"hist\", \"histogram\", \"spineplot\"))) {\n legend_args[[\"pt.lwd\"]] = legend_args[[\"pt.lwd\"]] %||% 0\n }\n \n if (identical(type, \"p\")) {\n legend_args[[\"pt.lwd\"]] = legend_args[[\"pt.lwd\"]] %||% lwd\n }\n \n if (identical(type, \"n\") && isFALSE(gradient)) {\n legend_args[[\"pch\"]] = legend_args[[\"pch\"]] %||% par(\"pch\")\n }\n \n if (identical(type, \"spineplot\")) {\n legend_args[[\"pt.bg\"]] = legend_args[[\"pt.bg\"]] %||% legend_args[[\"col\"]]\n }\n \n if (identical(type, \"ridge\") && isFALSE(gradient)) {\n legend_args[[\"pt.bg\"]] = legend_args[[\"pt.bg\"]] %||% sapply(legend_args[[\"col\"]], function(ccol) seq_palette(ccol, n = 2)[2])\n }\n \n legend_args[[\"pt.bg\"]] = legend_args[[\"pt.bg\"]] %||% bg\n \n legend_args[[\"legend\"]] = legend_args[[\"legend\"]] %||% lgnd_labs\n if (length(lgnd_labs) != length(eval(legend_args[[\"legend\"]]))) {\n warning(\n \"\\nUser-supplied legend labels do not match the number of groups.\\n\",\n \"Defaulting to automatic labels determined by the group splits in `by`,\\n\"\n )\n legend_args[[\"legend\"]] = lgnd_labs\n }\n \n if (isTRUE(gradient)) {\n legend_args[[\"ncol\"]] = NULL\n }\n \n #\n ## legend placement ----\n \n # Note: \"side\" = left/right ; \"end\" = top/bottom\n outer_side = outer_end = outer_right = outer_bottom = FALSE ## placeholders\n \n ooma = par(\"oma\")\n omar = par(\"mar\")\n topmar_epsilon = 0.1\n \n # Catch to avoid recursive offsets, e.g. repeated tinyplot calls with\n # \"bottom!\" legend position.\n \n ## restore inner margin defaults\n ## (in case the plot region/margins were affected by the preceding tinyplot call)\n dynmar = isTRUE(.tpar[[\"dynmar\"]])\n if (any(ooma != 0) && !dynmar) {\n if ( ooma[1] != 0 & omar[1] == par(\"mgp\")[1] + 1*par(\"cex.lab\") ) omar[1] = 5.1\n if ( ooma[2] != 0 & omar[2] == par(\"mgp\")[1] + 1*par(\"cex.lab\") ) omar[2] = 4.1\n if ( ooma[3] == topmar_epsilon & omar[3] != 4.1 ) omar[3] = 4.1\n if ( ooma[4] != 0 & omar[4] == 0 ) omar[4] = 2.1\n par(mar = omar)\n }\n ## restore outer margin defaults\n par(omd = c(0,1,0,1))\n ooma = par(\"oma\")\n \n ## Legend to outer side (either right or left) of plot\n if (grepl(\"right!$|left!$\", legend_args[[\"x\"]])) {\n \n outer_side = TRUE\n outer_right = grepl(\"right!$\", legend_args[[\"x\"]])\n \n # extra bump for spineplot if outer_right legend (to accommodate secondary y-axis)\n if (identical(type, \"spineplot\")) lmar[1] = lmar[1] + 1.1\n \n ## Switch position anchor (we'll adjust relative to the _opposite_ side below)\n if (outer_right) legend_args[[\"x\"]] = gsub(\"right!$\", \"left\", legend_args[[\"x\"]])\n if (!outer_right) legend_args[[\"x\"]] = gsub(\"left!$\", \"right\", legend_args[[\"x\"]])\n \n ## We have to set the inner margins of the plot before the (fake) legend is\n ## drawn, otherwise the inset calculation---which is based in the legend\n ## width---will be off the first time.\n if (outer_right) {\n omar[4] = 0\n } else {\n # For outer left we have to account for the y-axis label too, which\n # requires additional space\n omar[2] = par(\"mgp\")[1] + 1*par(\"cex.lab\")\n }\n par(mar = omar)\n \n if (new_plot && draw) {\n plot.new()\n # For themed + dynamic plots, we need to make sure the adjusted plot\n # margins for the legend are reinstated (after being overwritten by\n # the before.plot.new hook.\n if (dynmar) {\n omar = par(\"mar\")\n if (outer_right) {\n omar[4] = 0\n } else {\n omar[2] = par(\"mgp\")[1] + 1*par(\"cex.lab\")\n }\n par(mar = omar)\n }\n }\n \n legend_args[[\"horiz\"]] = FALSE\n \n ## Legend at the outer top or bottom of plot\n } else if (grepl(\"bottom!$|top!$\", legend_args[[\"x\"]])) {\n\n outer_end = TRUE\n outer_bottom = grepl(\"bottom!$\", legend_args[[\"x\"]])\n\n ## Switch position anchor (we'll adjust relative to the _opposite_ side below)\n if (outer_bottom) legend_args[[\"x\"]] = gsub(\"bottom!$\", \"top\", legend_args[[\"x\"]])\n if (!outer_bottom) legend_args[[\"x\"]] = gsub(\"top!$\", \"bottom\", legend_args[[\"x\"]])\n\n ## We have to set the inner margins of the plot before the (fake) legend is\n ## drawn, otherwise the inset calculation---which is based in the legend\n ## width---will be off the first time.\n if (outer_bottom) {\n omar[1] = par(\"mgp\")[1] + 1*par(\"cex.lab\")\n if (has_sub && (is.null(.tpar[[\"side.sub\"]]) || .tpar[[\"side.sub\"]]==1)) omar[1] = omar[1] + 1*par(\"cex.sub\")\n } else {\n ## For \"top!\", the logic is slightly different: We don't expand the outer\n ## margin b/c we need the legend to come underneath the main title. So\n ## we rather expand the existing inner margin.\n ooma[3] = ooma[3] + topmar_epsilon\n par(oma = ooma)\n }\n par(mar = omar)\n\n if (new_plot && draw) {\n plot.new()\n # For themed + dynamic plots, we need to make sure the adjusted plot\n # margins for the legend are reinstated (after being overwritten by\n # the before.plot.new hook.\n if (dynmar) {\n omar = par(\"mar\")\n if (outer_bottom) {\n # omar[1] = par(\"mgp\")[1] + 1*par(\"cex.lab\")\n omar[1] = theme_clean$mgp[1] + 1*par(\"cex.lab\") ## bit of a hack\n if (has_sub && (is.null(.tpar[[\"side.sub\"]]) || .tpar[[\"side.sub\"]]==1)) omar[1] = omar[1] + 1*par(\"cex.sub\")\n } else {\n ooma[3] = ooma[3] + topmar_epsilon\n par(oma = ooma)\n }\n par(mar = omar)\n }\n }\n\n # enforce horizontal legend if user hasn't specified ncol arg\n # (exception: gradient legends at bottom/top are always horizontal)\n if (is.null(legend_args[[\"ncol\"]]) || gradient) legend_args[[\"horiz\"]] = TRUE\n\n } else {\n \n legend_args[[\"inset\"]] = 0\n if (new_plot && draw) plot.new()\n \n }\n \n # Additional tweaks for horiz and/or multi-column legends\n if (isTRUE(legend_args[[\"horiz\"]]) || !is.null(legend_args[[\"ncol\"]])) {\n # tighter horizontal labelling\n # See: https://github.com/grantmcdermott/tinyplot/issues/434\n if (!gradient) {\n legend_args[[\"text.width\"]] = NA\n # Add a space to all labs except the outer most right ones\n nlabs = length(legend_args[[\"legend\"]])\n nidx = nlabs\n if (!is.null(legend_args[[\"ncol\"]])) nidx = tail(1:nlabs, (nlabs %/% legend_args[[\"ncol\"]]))\n legend_args[[\"legend\"]][-nidx] = paste(legend_args[[\"legend\"]][-nidx], \" \")\n }\n # catch for horizontal ribbon legend spacing\n if (type==\"ribbon\") {\n if (legend_args[[\"pt.lwd\"]] == 1) {\n legend_args[[\"x.intersp\"]] = 1\n } else {\n legend_args[[\"x.intersp\"]] = 0.5\n }\n } else if (gradient) {\n legend_args[[\"x.intersp\"]] = 0.5\n }\n }\n \n #\n ## draw the legend ----\n \n # Legend drawing is handled by the internal `tinylegend()` function, which:\n # 1. calculates appropriate insets for \"outer\" legend placement\n # 2. can draw gradient legends (via `gradient_legend()` below)\n #\n # Note: We wrap everything in `recordGraphics()` to preserve legend spacing\n # if the plot is resized (also necessary for Positron graphics logic regardless)\n recordGraphics(\n tinylegend(\n legend_args = legend_args,\n ooma = ooma,\n omar = omar,\n lmar = lmar,\n topmar_epsilon = topmar_epsilon,\n outer_side = outer_side,\n outer_right = outer_right,\n outer_end = outer_end,\n outer_bottom = outer_bottom,\n gradient = gradient,\n draw = draw\n ),\n list = list(\n legend_args = legend_args,\n ooma = ooma,\n omar = omar,\n lmar = lmar,\n topmar_epsilon = topmar_epsilon,\n outer_side = outer_side,\n outer_right = outer_right,\n outer_end = outer_end,\n outer_bottom = outer_bottom,\n gradient = gradient,\n draw = draw\n ),\n env = getNamespace(\"tinyplot\")\n )\n \n}\n\n\n# tinylegend ----\n\n## Internal workhorse function that draws the legend, given a set of legend\n## arguments and other graphical parameters. It does this in three steps:\n## 1) draw a fake legend, 2) calculate the associated inset and adjust the plot\n## margins accordingly, 3) draw the real legend\n\ntinylegend = function(\n legend_args,\n ooma, omar, lmar, topmar_epsilon,\n outer_side, outer_right, outer_end, outer_bottom,\n gradient,\n draw\n) {\n \n #\n ## Step 1: \"draw\" fake legend\n \n fklgnd.args = modifyList(\n legend_args,\n list(plot = FALSE),\n keep.null = TRUE\n )\n \n if (gradient) {\n lgnd_labs_tmp = na.omit(fklgnd.args[[\"legend\"]])\n if (length(lgnd_labs_tmp) < 5L) {\n nmore = 5L - length(lgnd_labs_tmp)\n lgnd_labs_tmp = c(lgnd_labs_tmp, rep(\"\", nmore))\n }\n fklgnd.args = modifyList(\n fklgnd.args,\n list(legend = lgnd_labs_tmp),\n keep.null = TRUE\n )\n if (outer_end) fklgnd.args = modifyList(fklgnd.args, list(title = NULL), keep.null = TRUE)\n }\n \n if (draw) {\n fklgnd = do.call(\"legend\", fklgnd.args)\n } else {\n plot.new()\n fklgnd = do.call(\"legend\", fklgnd.args)\n return(fklgnd)\n }\n \n #\n ## Step 2: Calculate legend inset (for outer placement in plot region)\n \n # calculate outer margin width in lines\n soma = 0\n if (outer_side) {\n soma = grconvertX(fklgnd$rect$w, to=\"lines\") - grconvertX(0, to=\"lines\")\n } else if (outer_end) {\n soma = grconvertY(fklgnd$rect$h, to=\"lines\") - grconvertY(0, to=\"lines\")\n }\n # Add legend margins to the outer margin\n soma = soma + sum(lmar)\n \n ## differing outer margin adjustments depending on side\n if (outer_side) {\n if (outer_right) {\n ooma[4] = soma\n } else {\n ooma[2] = soma\n }\n } else if (outer_end) {\n if (outer_bottom) {\n ooma[1] = soma\n } else {\n omar[3] = omar[3] + soma - topmar_epsilon\n par(mar = omar)\n }\n }\n par(oma = ooma)\n \n # determine legend inset\n inset = 0\n if (outer_side) {\n inset = grconvertX(lmar[1], from=\"lines\", to=\"npc\") - grconvertX(0, from = \"lines\", to = \"npc\")\n # extra space needed for \"left!\" b/c of lhs inner margin\n if (!outer_right) {\n inset_bump = grconvertX(par(\"mar\")[2], from = \"lines\", to = \"npc\") - grconvertX(0, from = \"lines\", to = \"npc\")\n inset = inset + inset_bump\n }\n inset = c(1+inset, 0)\n } else if (outer_end) {\n inset = grconvertY(lmar[1], from=\"lines\", to=\"npc\") - grconvertY(0, from=\"lines\", to=\"npc\")\n if (outer_bottom) {\n # extra space needed for \"bottom!\" b/c of lhs inner margin\n inset_bump = grconvertY(par(\"mar\")[1], from=\"lines\", to=\"npc\") - grconvertY(0, from=\"lines\", to=\"npc\")\n inset = inset + inset_bump\n } else {\n epsilon_bump = grconvertY(topmar_epsilon, from=\"lines\", to=\"npc\") - grconvertY(0, from=\"lines\", to=\"npc\")\n inset = inset + epsilon_bump\n }\n inset = c(0, 1+inset)\n }\n \n # GM: The legend inset spacing only works _exactly_ if we refresh the plot\n # area. I'm not sure why (and it works properly if we use the same\n # parameters manually while debugging), but this hack seems to work.\n ## v0.3.0 update: Using (temporary) hook instead of direct par(new = TRUE)\n ## assignment to play nice with tinytheme logic.\n oldhook = getHook(\"before.plot.new\")\n setHook(\"before.plot.new\", function() par(new = TRUE), action = \"append\")\n setHook(\"before.plot.new\", function() par(mar = omar), action = \"append\")\n plot.new()\n setHook(\"before.plot.new\", oldhook, action = \"replace\")\n \n # Finally, set the inset as part of the legend args.\n legend_args[[\"inset\"]] = inset\n \n #\n ## Step 3: Draw the legend\n\n if (gradient) {\n if (!more_than_n_unique(legend_args[[\"col\"]], 1)) {\n if (!is.null(legend_args[[\"pt.bg\"]]) && length(legend_args[[\"pt.bg\"]])==100) {\n legend_args[[\"col\"]] = legend_args[[\"pt.bg\"]]\n }\n }\n gradient_legend(\n legend_args = legend_args,\n fklgnd = fklgnd,\n lmar = lmar,\n outer_side = outer_side,\n outer_end = outer_end,\n outer_right = outer_right,\n outer_bottom = outer_bottom\n )\n } else {\n do.call(\"legend\", legend_args)\n }\n \n}\n\n\n# gradient legend ----\n\n# For gradient (i.e., continuous color) legends, we'll role our own bespoke\n# legend function based on grDevices::as.raster\n\ngradient_legend = function(legend_args, fklgnd, lmar, outer_side, outer_end, outer_right, outer_bottom) {\n pal = legend_args[[\"col\"]]\n lgnd_labs = legend_args[[\"legend\"]]\n if (!is.null(legend_args[[\"horiz\"]])) horiz = legend_args[[\"horiz\"]] else horiz = FALSE\n if (isTRUE(horiz)) {\n rasterlgd = as.raster(matrix(pal, nrow = 1))\n } else {\n rasterlgd = as.raster(matrix(rev(pal), ncol = 1))\n }\n \n corners = par(\"usr\")\n rasterbox = rep(NA_real_, 4)\n \n inner = !any(c(outer_side, outer_end))\n inner_right = inner_bottom = FALSE\n if (inner) {\n if (!is.null(legend_args[[\"x\"]]) && grepl(\"left$|right$\", legend_args[[\"x\"]])) {\n inner_right = grepl(\"right$\", legend_args[[\"x\"]])\n }\n if (!is.null(legend_args[[\"x\"]]) && grepl(\"^bottoml|^top\", legend_args[[\"x\"]])) {\n inner_bottom = grepl(\"^bottom\", legend_args[[\"x\"]])\n }\n }\n \n if (inner) {\n \n fklgnd$rect$h = fklgnd$rect$h - (grconvertY(1.5 + 0.4, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\"))\n \n rasterbox[1] = fklgnd$rect$left\n if (isFALSE(inner_right)) rasterbox[1] = rasterbox[1] + (grconvertX(0.2, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\"))\n rasterbox[2] = fklgnd$rect$top - fklgnd$rect$h - (grconvertY(1.5 + 0.2, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\"))\n rasterbox[3] = rasterbox[1] + (grconvertX(1.25, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\"))\n rasterbox[4] = rasterbox[2] + fklgnd$rect$h\n \n } else if (outer_side) {\n \n rb1_adj = grconvertX(lmar[1] + 0.2, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\")\n rb3_adj = grconvertX(1.25, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\")\n rb2_adj = (corners[4] - corners[3] - (grconvertY(5+1 + 2.5, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\"))) / 2\n # override if top or bottom\n if (!is.null(legend_args[[\"x\"]])) {\n if (grepl(\"^bottom\", legend_args[[\"x\"]])) {\n rb2_adj = corners[3]\n }\n if (grepl(\"^top\", legend_args[[\"x\"]])) {\n rb2_adj = corners[4] - (grconvertY(5+1 + 2.5, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\"))\n }\n }\n rb4_adj = grconvertY(5+1, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n \n if (outer_right) {\n rasterbox[1] = corners[2] + rb1_adj\n rasterbox[2] = rb2_adj \n rasterbox[3] = rasterbox[1] + rb3_adj\n rasterbox[4] = rasterbox[2] + rb4_adj\n } else {\n rb1_adj = rb1_adj + grconvertX(par(\"mar\")[2] + 1, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\")\n rasterbox[1] = corners[1] - rb1_adj\n rasterbox[2] = rb2_adj \n rasterbox[3] = rasterbox[1] - rb3_adj\n rasterbox[4] = rasterbox[2] + rb4_adj\n }\n \n } else if (outer_end) {\n \n rb1_adj = (corners[2] - corners[1] - (grconvertX(5+1, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\"))) / 2\n rb3_adj = grconvertX(5+1, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\")\n rb2_adj = grconvertY(lmar[1], from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n rb4_adj = grconvertY(1.25, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n \n if (outer_bottom) {\n rb2_adj = rb2_adj + grconvertY(par(\"mar\")[2], from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n rasterbox[1] = rb1_adj\n rasterbox[2] = corners[3] - rb2_adj \n rasterbox[3] = rasterbox[1] + rb3_adj\n rasterbox[4] = rasterbox[2] - rb4_adj\n } else {\n rb2_adj = rb2_adj + grconvertY(1.25 + 1, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n rasterbox[1] = rb1_adj\n rasterbox[2] = corners[4] + rb2_adj \n rasterbox[3] = rasterbox[1] + rb3_adj\n rasterbox[4] = rasterbox[2] - rb4_adj\n }\n \n }\n \n #\n ## Draw the gradient swatch\n \n rasterImage(\n rasterlgd,\n rasterbox[1], #x1\n rasterbox[2], #y1\n rasterbox[3], #x2\n rasterbox[4], #y2\n xpd = NA\n ) \n \n #\n ## Add the labels, tick marks, and title \n \n if (isFALSE(horiz)) {\n labs_idx = !is.na(lgnd_labs)\n lgnd_labs[labs_idx] = paste0(\" \", format(lgnd_labs[labs_idx]))\n lbl_x_anchor = rasterbox[3]\n ttl_x_anchor = rasterbox[1]\n lbl_adj = c(0, 0.5)\n tck_adj = c(1, 0.5)\n ttl_adj = c(0, 0)\n if (!inner && !outer_right) {\n lbl_x_anchor = rasterbox[1]\n ttl_x_anchor = ttl_x_anchor + max(strwidth(lgnd_labs[labs_idx]))\n ttl_adj = c(1, 0)\n }\n text(\n x = lbl_x_anchor,\n y = seq(rasterbox[2], rasterbox[4], length.out = length(lgnd_labs)),\n labels = lgnd_labs,\n xpd = NA, \n adj = lbl_adj\n )\n # legend tick marks\n lgnd_ticks = lgnd_labs\n lgnd_ticks[labs_idx] = \"- -\"\n text(\n x = lbl_x_anchor,\n y = seq(rasterbox[2], rasterbox[4], length.out = length(lgnd_labs)),\n labels = lgnd_ticks, col = \"white\",\n xpd = NA, adj = tck_adj\n )\n # legend title\n text(\n x = ttl_x_anchor,\n y = rasterbox[4] + grconvertY(1, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\"),\n labels = legend_args[[\"title\"]],\n xpd = NA, adj = ttl_adj\n )\n } else {\n lbl_y_anchor = rasterbox[4]\n ttl_y_anchor = rasterbox[4]\n lbl_adj = c(0.5, 1.25)\n tck_adj = c(0, 0.5)\n ttl_adj = c(1, -0.5)\n # legend labs\n text(\n x = seq(rasterbox[1], rasterbox[3], length.out = length(lgnd_labs)),\n y = lbl_y_anchor,\n labels = lgnd_labs,\n xpd = NA, adj = lbl_adj\n )\n # legend tick marks\n lgnd_ticks = lgnd_labs\n lgnd_ticks[!is.na(lgnd_ticks)] = \"- -\"\n text(\n x = seq(rasterbox[1], rasterbox[3], length.out = length(lgnd_labs)),\n y = lbl_y_anchor,\n labels = lgnd_ticks, col = \"white\",\n xpd = NA, adj = tck_adj, srt = 90\n )\n # legend title\n text(\n x = rasterbox[1],\n y = ttl_y_anchor,\n labels = paste0(legend_args[[\"title\"]], \" \"),\n xpd = NA, adj = ttl_adj\n )\n }\n}\n\n\n"], ["/tinyplot/R/facet.R", "#' Draw facet windows\n#' \n#' @description Internal functions called from `tinyplot` in order to draw the\n#' plot window with different facets, grids, axes, etc. \n#' \n#' `facet_layout` determines the layout of the facets, based on a set of inputs.\n#' \n#' `draw_facet_window` is the main workhorse function for setting the exterior\n#' plot elements as part of a `tinyplot` call, including adjustment of margins\n#' for dynamic themes, etc.\n#' \n#' @keywords internal\n#' @rdname facet\ndraw_facet_window = function(\n # add arg first, since that determines what happens (if at all)\n add,\n # facet-specific args\n cex_fct_adj,\n facet.args,\n facet_newlines, facet_font, facet_rect, facet_text,\n facet_col, facet_bg, facet_border,\n facet, facets, ifacet,\n nfacets, nfacet_cols, nfacet_rows,\n # axes args\n axes, flip, frame.plot, oxaxis, oyaxis,\n xlabs, xlim, xlim_user, xaxt, xaxs, xaxb, xaxl,\n ylabs, ylim, ylim_user, yaxt, yaxs, yaxb, yaxl,\n asp, log,\n # other args (in approx. alphabetical + group ordering)\n dots,\n draw,\n grid,\n has_legend,\n type,\n x, xmax, xmin,\n y, ymax, ymin\n ) {\n \n # if add is TRUE, just return inputs without any calculations\n if (isTRUE(add)) {\n return(as.list(environment()))\n }\n \n # if breaks are provided use these (but only if x/ylabs are null)\n if (!is.null(xaxb) && !is.null(xlabs)) xlabs = xaxb\n if (!is.null(yaxb) && !is.null(ylabs)) ylabs = yaxb\n \n # draw background color only in the grid rectangle\n grid.bg = get_tpar(\"grid.bg\")\n if (!is.null(grid.bg)) {\n corners = par(\"usr\")\n rect(corners[1], corners[3], corners[2], corners[4], col = grid.bg, border = NA)\n }\n\n ## dynamic margins flag\n dynmar = isTRUE(.tpar[[\"dynmar\"]])\n \n ## optionally allow to modify the style of axis interval calculation\n if (!is.null(xaxs)) par(xaxs = xaxs)\n if (!is.null(yaxs)) par(yaxs = yaxs)\n\n if (nfacets > 1) {\n # Set facet margins (i.e., gaps between facets)\n if (is.null(facet.args[[\"fmar\"]])) {\n fmar = tpar(\"fmar\")\n } else {\n if (length(facet.args[[\"fmar\"]]) != 4) {\n warning(\n \"`fmar` has to be a vector of length four, e.g.\",\n \"`facet.args = list(fmar = c(b,l,t,r))`.\",\n \"\\n\",\n \"Resetting to fmar = c(1,1,1,1) default.\",\n \"\\n\"\n )\n fmar = tpar(\"fmar\")\n } else {\n fmar = facet.args[[\"fmar\"]]\n }\n }\n # We need to adjust for n>=3 facet cases for correct spacing...\n if (nfacets >= 3) {\n ## ... exception for 2x2 cases\n if (!(nfacet_rows == 2 && nfacet_cols == 2)) fmar = fmar * .75\n }\n # Extra reduction if no plot frame to reduce whitespace\n if (isFALSE(frame.plot) && !isTRUE(facet.args[[\"free\"]])) {\n fmar = fmar - 0.5\n }\n\n ooma = par(\"oma\")\n\n # Bump top margin down for facet titles\n fmar[3] = fmar[3] + 1\n if (isTRUE(attr(facet, \"facet_grid\"))) {\n fmar[3] = max(0, fmar[3] - 1)\n # Indent for RHS facet_grid title strip if \"right!\" legend\n if (has_legend && ooma[4] > 0) ooma[4] = ooma[4] + 1\n }\n fmar[3] = fmar[3] + facet_newlines * facet_text / cex_fct_adj\n\n omar = par(\"mar\")\n \n ## Dynamic plot margin adjustments\n if (dynmar) {\n if (par(\"las\") %in% 1:2) {\n # extra whitespace bump on the y axis\n ## overrides for ridge and some types that use integer spacing with (named) axis labels ## FXIME\n if (type == \"ridge\") {\n yaxlabs = levels(y)\n } else if (!is.null(ylabs)) {\n yaxlabs = if (!is.null(names(ylabs))) names(ylabs) else ylabs \n } else if (type == \"boxplot\" && isTRUE(flip) && !is.null(xlabs)) {\n yaxlabs = if (!is.null(names(xlabs))) names(xlabs) else xlabs \n } else {\n # yaxl = axTicks(2)\n yaxlabs = axisTicks(usr = extendrange(ylim, f = 0.04), log = par(\"ylog\"))\n }\n if (!is.null(yaxl)) yaxlabs = tinylabel(yaxlabs, yaxl)\n # whtsbp = grconvertX(max(strwidth(yaxl, \"figure\")), from = \"nfc\", to = \"lines\") - 1\n whtsbp = grconvertX(max(strwidth(yaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - grconvertX(0, from = \"nfc\", to = \"lines\") - 1\n if (whtsbp > 0) {\n omar = omar + c(0, whtsbp, 0, 0) * cex_fct_adj\n fmar[2] = fmar[2] + whtsbp * cex_fct_adj\n }\n # Extra reduction if no plot frame to reduce whitespace\n if (isFALSE(frame.plot) && !isTRUE(facet.args[[\"free\"]])) {\n fmar[2] = fmar[2] - (whtsbp * cex_fct_adj)\n }\n }\n if (par(\"las\") %in% 2:3) {\n # extra whitespace bump on the x axis\n # xaxlabs = axTicks(1)\n xaxlabs = if (is.null(xlabs)) axisTicks(usr = extendrange(xlim, f = 0.04), log = par(\"xlog\")) else \n if (!is.null(names(xlabs))) names(xlabs) else xlabs\n if (!is.null(xaxl)) xaxlabs = tinylabel(xaxlabs, xaxl)\n whtsbp = grconvertX(max(strwidth(xaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - 1\n if (whtsbp > 0) {\n omar = omar + c(whtsbp, 0, 0, 0) * cex_fct_adj\n fmar[1] = fmar[1] + whtsbp * cex_fct_adj\n }\n # Extra reduction if no plot frame to reduce whitespace\n if (isFALSE(frame.plot) && !isTRUE(facet.args[[\"free\"]])) {\n fmar[1] = fmar[1] - (whtsbp * cex_fct_adj)\n }\n }\n # FIXME: Is this causing issues for lhs legends with facet_grid?\n # catch for missing rhs legend\n if (isTRUE(attr(facet, \"facet_grid\")) && !has_legend) {\n omar[4] = omar[4] + 1\n }\n }\n\n # Now we set the margins. The trick here is that we simultaneously adjust\n # inner (mar) and outer (oma) margins by the same amount, but in opposite\n # directions, to preserve the overall facet and plot centroids.\n nmar = (fmar + .1) / cex_fct_adj\n noma = (ooma + omar - fmar - .1) / cex_fct_adj\n # Catch in case of negative oma values. (Probably only occurs with some\n # user-supplied tpar(lmar) values and a \"left!\" positioned legend.)\n if (any(noma < 0)) {\n noma_orig = noma\n noma[noma < 0] = 0\n # noma_diff = noma-noma_orig\n # nmar = nmar + noma_diff\n }\n # apply changes\n par(oma = noma)\n par(mar = nmar)\n\n # Now that the margins have been set, arrange facet rows and columns based\n # on our earlier calculations.\n par(mfrow = c(nfacet_rows, nfacet_cols))\n } else if (dynmar) {\n # Dynamic plot margin adjustments\n omar = par(\"mar\")\n omar = omar - c(0, 0, 1, 0) # reduce top whitespace since no facet (title)\n if (type == \"spineplot\") omar[4] = 2.1 # FIXME catch for spineplot RHS axis labs\n if (par(\"las\") %in% 1:2) {\n # extra whitespace bump on the y axis\n ## overrides for ridge and some types that use integer spacing with (named) axis labels ## FXIME\n if (type == \"ridge\") {\n yaxlabs = levels(y)\n } else if (!is.null(ylabs)) {\n yaxlabs = if (!is.null(names(ylabs))) names(ylabs) else ylabs \n } else if (type == \"boxplot\" && isTRUE(flip) && !is.null(xlabs)) {\n yaxlabs = if (!is.null(names(xlabs))) names(xlabs) else xlabs \n } else {\n # yaxl = axTicks(2)\n yaxlabs = axisTicks(usr = extendrange(ylim, f = 0.04), log = par(\"ylog\"))\n }\n if (!is.null(yaxl)) yaxlabs = tinylabel(yaxlabs, yaxl)\n # whtsbp = grconvertX(max(strwidth(yaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - 1\n whtsbp = grconvertX(max(strwidth(yaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - grconvertX(0, from = \"nfc\", to = \"lines\") - 1\n if (whtsbp > 0) {\n omar[2] = omar[2] + whtsbp\n }\n }\n if (par(\"las\") %in% 2:3) {\n # extra whitespace bump on the x axis\n # xaxl = axTicks(1)\n xaxlabs = if (is.null(xlabs)) axisTicks(usr = extendrange(xlim, f = 0.04), log = par(\"xlog\")) else \n if (!is.null(names(xlabs))) names(xlabs) else xlabs\n if (!is.null(xaxl)) xaxlabs = tinylabel(xaxlabs, xaxl)\n whtsbp = grconvertX(max(strwidth(xaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - 1\n if (whtsbp > 0) {\n omar[1] = omar[1] + whtsbp\n }\n }\n par(mar = omar)\n }\n\n ## Loop over the individual facet windows and draw the plot region\n ## components (axes, titles, box, grid, etc.)\n for (ii in ifacet) {\n # See: https://github.com/grantmcdermott/tinyplot/issues/65\n if (nfacets > 1) {\n mfgi = ceiling(ii / nfacet_cols)\n mfgj = ii %% nfacet_cols\n if (mfgj == 0) mfgj = nfacet_cols\n par(mfg = c(mfgi, mfgj))\n }\n\n ## Set the plot window\n ## Problem: Passing extra args through ... (e.g., legend_args) to plot.window\n ## triggers an annoying warning about unrecognized graphical params.\n # plot.window(\n # xlim = xlim, ylim = ylim,\n # asp = asp, log = log,\n # # ...\n # )\n ## Solution: Only pass on relevant args using name checking and do.call.\n ## Idea borrowed from here: https://stackoverflow.com/a/4128401/4115816\n pdots = dots[names(dots) %in% names(formals(plot.default))]\n ## catch for flipped boxplots...\n if (type == \"boxplot\" && isTRUE(flip)) {\n log_flip = log\n if (!is.null(log)) {\n if (log == \"x\") log_flip = \"y\"\n if (log == \"y\") log_flip = \"x\"\n }\n do.call(\n \"plot.window\",\n c(list(xlim = ylim, ylim = xlim, asp = asp, log = log_flip), pdots)\n )\n xside = 2\n yside = 1\n } else {\n ## ... standard plot window for all other cases\n do.call(\n \"plot.window\",\n c(list(xlim = xlim, ylim = ylim, asp = asp, log = log), pdots)\n )\n xside = 1\n yside = 2\n }\n\n\n # axes, frame.plot and grid\n if (isTRUE(axes) || isTRUE(facet.args[[\"free\"]])) {\n args_x = list(x,\n side = xside,\n type = xaxt,\n labeller = xaxl,\n cex = get_tpar(c(\"cex.xaxs\", \"cex.axis\"), 0.8),\n lwd = get_tpar(c(\"lwd.xaxs\", \"lwd.axis\"), 1),\n lty = get_tpar(c(\"lty.xaxs\", \"lty.axis\"), 1)\n )\n args_y = list(y,\n side = yside,\n type = yaxt,\n labeller = yaxl,\n cex = get_tpar(c(\"cex.yaxs\", \"cex.axis\"), 0.8),\n lwd = get_tpar(c(\"lwd.yaxs\", \"lwd.axis\"), 1),\n lty = get_tpar(c(\"lty.yaxs\", \"lty.axis\"), 1)\n )\n if (!is.null(xaxb)) args_x$at = xaxb\n if (!is.null(yaxb)) args_y$at = yaxb\n type_range_x = type %in% c(\"barplot\", \"pointrange\", \"errorbar\", \"ribbon\", \"boxplot\", \"p\", \"violin\") && !is.null(xlabs)\n type_range_y = !is.null(ylabs) && (type == \"p\" || (isTRUE(flip) && type %in% c(\"barplot\", \"pointrange\", \"errorbar\", \"ribbon\", \"boxplot\", \"violin\")))\n if (type_range_x) {\n args_x = modifyList(args_x, list(at = xlabs, labels = names(xlabs)))\n }\n if (type_range_y) {\n args_y = modifyList(args_y, list(at = ylabs, labels = names(ylabs)))\n }\n\n if (isTRUE(facet.args[[\"free\"]]) && (par(\"xlog\") || par(\"ylog\"))) {\n warning(\n \"\\nFree scale axes for faceted plots are currently not supported if the axes are logged. Reverting back to fixed scales.\",\n \"\\nIf support for this feature is important to you, please raise an issue on our GitHub repo:\",\n \"\\nhttps://github.com/grantmcdermott/tinyplot/issues\\n\"\n )\n facet.args[[\"free\"]] = FALSE\n }\n\n # Special logic if facets are free...\n if (isTRUE(facet.args[[\"free\"]])) {\n # First, we need to calculate the plot extent and axes range of each\n # individual facet.\n xfree = split(c(x, xmin, xmax), facet)[[ii]]\n yfree = split(c(y, ymin, ymax), facet)[[ii]]\n if (!xlim_user) xlim = range(xfree, na.rm = TRUE)\n if (!ylim_user) ylim = range(yfree, na.rm = TRUE)\n xext = extendrange(xlim, f = 0.04)\n yext = extendrange(ylim, f = 0.04)\n # We'll save this in a special .fusr env var (list) that we'll re-use\n # when it comes to plotting the actual elements later\n if (ii == 1) {\n fusr = replicate(4, vector(\"double\", length = nfacets), simplify = FALSE)\n assign(\".fusr\", fusr, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n }\n fusr = get(\".fusr\", envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n fusr[[ii]] = c(xext, yext)\n assign(\".fusr\", fusr, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n # Explicitly set (override) the current facet extent\n par(usr = fusr[[ii]])\n # if plot frame is true then print axes per normal...\n if (type %in% c(\"barplot\", \"pointrange\", \"errorbar\", \"ribbon\", \"boxplot\", \"p\", \"violin\") && !is.null(xlabs)) {\n tinyAxis(xfree, side = xside, at = xlabs, labels = names(xlabs), type = xaxt, labeller = xaxl)\n } else {\n tinyAxis(xfree, side = xside, type = xaxt, labeller = xaxl)\n }\n if (isTRUE(flip) && type %in% c(\"barplot\", \"pointrange\", \"errorbar\", \"ribbon\", \"boxplot\", \"p\", \"violin\") && !is.null(ylabs)) {\n tinyAxis(yfree, side = yside, at = ylabs, labels = names(ylabs), type = yaxt, labeller = yaxl)\n } else {\n tinyAxis(yfree, side = yside, type = yaxt, labeller = yaxl)\n }\n\n # For fixed facets we can just reuse the same plot extent and axes limits\n } else if (isTRUE(frame.plot)) {\n # if plot frame is true then print axes per normal...\n do.call(tinyAxis, args_x)\n do.call(tinyAxis, args_y)\n } else {\n # ... else only print the \"outside\" axes.\n if (ii %in% oxaxis) do.call(tinyAxis, args_x)\n if (ii %in% oyaxis) do.call(tinyAxis, args_y)\n }\n }\n\n # facet titles\n ## Note: facet titles could be done more simply with mtext... but then we\n ## couldn't adjust background features (e.g., fill), or rotate the rhs\n ## facet grid text. So we're rolling our own \"manual\" versions with text\n ## and rect.\n if (!is.null(facet)) {\n # Get the four corners of plot area (x1, x2, y1, y2)\n corners = par(\"usr\")\n # catch for logged axes\n xlog = isTRUE(par(\"xlog\"))\n ylog = isTRUE(par(\"ylog\"))\n if (xlog) corners[1:2] = 10^(corners[1:2])\n if (ylog) corners[3:4] = 10^(corners[3:4])\n # special logic for facet grids\n if (is.null(facet_newlines) || facet_newlines == 0) {\n facet_title_lines = 1\n } else {\n facet_title_lines = 1 + facet_newlines\n }\n # different logic for facet grids versus regular facets\n if (isTRUE(attr(facet, \"facet_grid\"))) {\n ## top facet strips\n if (ii %in% 1:nfacet_cols) {\n if (isTRUE(facet_rect)) {\n line_height = (facet_title_lines + .1) * facet_text / cex_fct_adj\n if (ylog) {\n line_height = grconvertY(line_height, from = \"lines\", to = \"user\") / grconvertY(0, from = \"lines\", to = \"user\")\n rect_height = corners[4] * line_height\n } else {\n line_height = grconvertY(line_height, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\")\n rect_height = corners[4] + line_height\n }\n rect(\n corners[1], corners[4], corners[2], rect_height,\n col = facet_bg, border = facet_border,\n xpd = NA\n )\n }\n xpos = if (xlog) 10^(mean(log10(corners[1:2]))) else mean(corners[1:2])\n if (ylog) {\n ypos = grconvertY(0.4, from = \"lines\", to = \"user\") / grconvertY(0, from = \"lines\", to = \"user\")\n ypos = corners[4] * ypos\n } else {\n ypos = grconvertY(0.4, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\")\n ypos = corners[4] + ypos\n }\n text(\n x = xpos,\n y = ypos,\n labels = sub(\"^(.*?)~.*\", \"\\\\1\", facets[[ii]]),\n adj = c(0.5, 0),\n cex = facet_text / cex_fct_adj,\n col = facet_col,\n font = facet_font,\n xpd = NA,\n )\n }\n ## right facet strips\n if (ii %% nfacet_cols == 0 || ii == nfacets) {\n if (isTRUE(facet_rect)) {\n line_height = (facet_title_lines + .1) * facet_text / cex_fct_adj\n if (xlog) {\n line_height = grconvertX(line_height, from = \"lines\", to = \"user\") / grconvertX(0, from = \"lines\", to = \"user\")\n rect_width = corners[2] * line_height\n } else {\n line_height = grconvertX(line_height, from = \"lines\", to = \"user\") - grconvertX(0, from = \"lines\", to = \"user\")\n rect_width = corners[2] + line_height\n }\n rect(\n corners[2], corners[3], rect_width, corners[4],\n col = facet_bg, border = facet_border,\n xpd = NA\n )\n }\n if (xlog) {\n xpos = grconvertX(0.4, from = \"lines\", to = \"user\") / grconvertX(0, from = \"lines\", to = \"user\")\n xpos = corners[2] * xpos\n } else {\n xpos = grconvertX(0.4, from = \"lines\", to = \"user\") - grconvertX(0, from = \"lines\", to = \"user\")\n xpos = corners[2] + xpos\n }\n ypos = if (ylog) 10^(mean(log10(corners[3:4]))) else mean(corners[3:4])\n text(\n x = xpos,\n y = ypos,\n labels = sub(\"^.*?~(.*)\", \"\\\\1\", facets[[ii]]),\n srt = 270,\n adj = c(0.5, 0),\n cex = facet_text / cex_fct_adj,\n col = facet_col,\n font = facet_font,\n xpd = NA\n )\n }\n } else {\n if (isTRUE(facet_rect)) {\n line_height = (facet_title_lines + .1) * facet_text / cex_fct_adj\n if (ylog) {\n line_height = grconvertY(line_height, from = \"lines\", to = \"user\") / grconvertY(0, from = \"lines\", to = \"user\")\n rect_height = corners[4] * line_height\n } else {\n line_height = grconvertY(line_height, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\")\n rect_height = corners[4] + line_height\n }\n rect(\n corners[1], corners[4], corners[2], rect_height,\n col = facet_bg, border = facet_border,\n xpd = NA\n )\n }\n xpos = if (xlog) 10^(mean(log10(corners[1:2]))) else mean(corners[1:2])\n if (ylog) {\n ypos = grconvertY(0.4, from = \"lines\", to = \"user\") / grconvertY(0, from = \"lines\", to = \"user\")\n ypos = corners[4] * ypos\n } else {\n ypos = grconvertY(0.4, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\")\n ypos = corners[4] + ypos\n }\n text(\n x = xpos,\n y = ypos,\n labels = paste(facets[[ii]]),\n adj = c(0.5, 0),\n cex = facet_text / cex_fct_adj,\n col = facet_col,\n font = facet_font,\n xpd = NA\n )\n }\n }\n\n # plot frame\n if (frame.plot) box()\n\n # panel grid lines\n if (is.null(grid)) grid = .tpar[[\"grid\"]]\n if (!is.null(grid)) {\n if (is.logical(grid)) {\n ## If grid is TRUE create a default grid. Rather than just calling the default grid()\n ## abline(... = pretty(extendrange(...)), ...) is used. Reason: pretty() is generic\n ## and works better for axes based on date/time classes. Exception: For axes in logs,\n ## resort to using grid() which is likely better handled there.\n if (isTRUE(grid)) {\n gnx = gny = NULL\n if (!is.null(xaxb)) {\n abline(v = xaxb, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n gnx = NA\n } else if (!any(c(par(\"xlog\"), type == \"boxplot\"))) {\n xg = if (!inherits(x, c(\"POSIXt\", \"Date\"))) axTicks(side = 1) else axTicksDateTime(side = 1, x = x)\n abline(v = xg, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n gnx = NA\n }\n if (!is.null(yaxb)) {\n abline(h = yaxb, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n gny = NA\n } else if (!any(c(par(\"ylog\"), type == \"boxplot\"))) {\n yg = if (!inherits(y, c(\"POSIXt\", \"Date\"))) axTicks(side = 2) else axTicksDateTime(side = 2, x = x)\n abline(h = yg, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n gny = NA\n }\n grid(nx = gnx, ny = gny, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n }\n } else {\n grid\n }\n }\n\n # add any drawn elements\n if (!is.null(draw)) eval(draw)\n } # end of ii facet loop\n\n return(as.list(environment()))\n}\n\n\n#' @rdname facet\n#' @keywords internal\nfacet_layout = function(facet, add = FALSE, facet.args = list()) {\n nfacet_rows = 1\n nfacet_cols = 1\n if (!is.null(facet)) {\n facets = if (is.factor(facet)) levels(facet) else sort(unique(facet))\n ifacet = seq_along(facets)\n nfacets = length(facets)\n if (isTRUE(add)) {\n omfrow = par(\"mfrow\")\n nfacet_rows = omfrow[1]\n nfacet_cols = omfrow[2]\n } else {\n if (isTRUE(attr(facet, \"facet_grid\"))) {\n facet.args[[\"nrow\"]] = attr(facet, \"facet_nrow\")\n }\n if (!is.null(facet.args[[\"nrow\"]])) {\n nfacet_rows = facet.args[[\"nrow\"]]\n nfacet_cols = ceiling(nfacets / nfacet_rows)\n } else if (!is.null(facet.args[[\"ncol\"]])) {\n nfacet_cols = facet.args[[\"ncol\"]]\n nfacet_rows = ceiling(nfacets / nfacet_cols)\n } else {\n if (nfacets > 3) {\n nfacet_cols = ceiling(sqrt(nfacets))\n nfacet_rows = ceiling(nfacets / nfacet_cols)\n } else {\n nfacet_rows = 1L\n nfacet_cols = nfacets\n }\n }\n }\n\n oxaxis = tail(ifacet, nfacet_cols)\n oyaxis = seq(1, nfacets, by = nfacet_cols)\n\n if (nfacet_rows >= 3 || nfacet_cols >= 3) {\n cex_fct_adj = 0.66\n } else if (nfacet_rows == 2 && nfacet_cols == 2) {\n cex_fct_adj = 0.83\n } else {\n cex_fct_adj = 1\n }\n } else {\n facets = ifacet = nfacets = oxaxis = oyaxis = 1\n cex_fct_adj = 1\n }\n\n list(\n facets = facets,\n ifacet = ifacet,\n nfacets = nfacets,\n nfacet_rows = nfacet_rows,\n nfacet_cols = nfacet_cols,\n oxaxis = oxaxis,\n oyaxis = oyaxis,\n cex_fct_adj = cex_fct_adj\n )\n}\n\n\n\n#\n# helper functions\n#\n\n\n# utility function for converting facet formulas into variables\nget_facet_fml = function(formula, data = NULL) {\n xfacet = yfacet = NULL\n\n ## catch one-sided formula ~ x or ~ x | z with no \"y\" variable\n if (!inherits(formula, \"formula\")) formula = as.formula(formula)\n no_yfacet = length(formula) == 2L\n fml_rhs = if (no_yfacet) 2L else 3L\n\n ## set up model frame\n m = match.call(expand.dots = FALSE)\n\n if (!is.null(data)) {\n m = m[c(1L, match(c(\"formula\", \"data\", \"subset\", \"na.action\", \"drop.unused.levels\"), names(m), 0L))]\n }\n\n m$formula = formula\n ## need stats:: for non-standard evaluation\n m[[1L]] = quote(stats::model.frame)\n mf = eval.parent(m)\n\n ## extract variables: x, y (if any)\n if (no_yfacet) {\n yfacet_loc = NULL\n xfacet_loc = 1L\n } else {\n yfacet_loc = 1L\n xfacet_loc = 2L\n }\n if (NCOL(mf) < xfacet_loc) stop(\"formula should specify at least one variable on the right-hand side\")\n yfacet = if (no_yfacet) NULL else mf[, yfacet_loc]\n xfacet = mf[, xfacet_loc:NCOL(mf)]\n\n ## return object\n xfacet = interaction(xfacet, sep = \":\")\n if (no_yfacet) {\n ret = xfacet\n } else {\n # yfacet = interaction(yfacet, sep = \":\")\n ## NOTE: We \"swap\" the formula LHS and RHS since mfrow plots rowwise\n ret = interaction(xfacet, yfacet, sep = \"~\")\n attr(ret, \"facet_grid\") = TRUE\n attr(ret, \"facet_nrow\") = length(unique(yfacet))\n }\n\n return(ret)\n}\n\n\n## internal convenience function to determine whether the current facet panel\n## has the position \"left\", \"right\", \"top\", or \"bottom\" in the facet grid\nis_facet_position = function(position, ifacet, facet_window_args) {\n id = facet_window_args$ifacet\n nc = facet_window_args$nfacet_cols\n ni = tail(id, 1L)\n switch(position,\n \"left\" = ifacet %in% seq(1L, ni, by = nc),\n \"right\" = ifacet %in% pmin(ni, seq(1L, ni, by = nc) + nc - 1L),\n \"top\" = ifacet %in% head(id, nc),\n \"bottom\" = ifacet %in% tail(id, nc),\n NA\n )\n}\n"], ["/tinyplot/R/type_abline.R", "#' Add straight lines to a plot\n#' @description\n#' These functions add straight line(s) through the current plot.\n#' @details\n#' While `type_abline`, `type_hline`, and `type_vline` can be called in a base\n#' plot layer, we expect that they will typically be called as subsequent\n#' layers via [`tinyplot_add`].\n#' @section Recycling logic: \n#' The recycling behaviour of the line parameters (i.e., `a`, `b`, `h`, or `v`)\n#' is adaptive, depending on whether `by` or `facet` grouping is detected. While\n#' this leads to different recycling scenarios, the underlying code logic\n#' follows sensible heuristics designed to match user expectations.\n#' \n#' Parameter lengths must equal one of four options:\n#' \n#' 1. Single value (i.e., length = 1), i.e. simplest case where the same line is\n#' applied uniformly across all groups and facets. Uses the default user colour\n#' (e.g. `\"black\"`, or `tpar(\"palette.qualitative\")[1]` if a theme is set).\n#' 2. Number of `by` groups, i.e. one parameter per group. For example,\n#' `tinyplot(mpg ~ wt | factor(cyl), data = mtcars, type = type_hline(h = 21:23))`\n#' will give three horizontal lines, with colours matching the user's qualitative\n#' palette.\n#' 3. Number of `facet` groups, i.e. one parameter per facet panel. For example:\n#' `tinyplot(mpg ~ wt, facet = ~am, data = mtcars, type = type_hline(h = c(20,30)))`\n#' would give separate horizontal lines per facet, but both using the same\n#' default color.\n#' 4. Product of `by` and `facet` groups, i.e. one parameter for each unique\n#' by-facet combination. Orders over facets first and then, within that, by\n#' group. For example:\n#' `tinyplot(mpg ~ wt | factor(cyl), facet = ~am, data = mtcars, type = type_hline(h = 21:26))`\n#' will give six separate lines, with the first three (`21:23`) coloured by\n#' group in the first facet, and second three (`24:26`) coloured by by group\n#' in the second facet.\n#' \n#' Alongside these general rules, we also try to accomodate special cases when\n#' other aesthetic parameters like `lwd` or `lty` are invoked by the user. See\n#' Examples.\n#' \n#' @param a,b the intercept (default: `a` = 0) and slope (default: `b` = 1)\n#' terms. Numerics of length 1, or equal to the number of groups or number of\n#' facets (or the product thereof).\n#' @examples\n#' #\n#' ## abline\n#' \n#' tinyplot(x = -10:10, y = rnorm(21) + -10:10, grid = TRUE)\n#' tinyplot_add(type = \"abline\")\n#' # same as...\n#' # tinyplot_add(type = type_abline(a = 0, b = 1))\n#' \n#' # customize by passing bespoke intercept and slope values\n#' tinyplot_add(type = type_abline(a = -1, b = -0.5))\n#' \n#' # note that calling as abline & co. as a base plot layer will still lead to\n#' # axes limits that respect the range of the data\n#' tinyplot(x = -10:10, y = -10:10, grid = TRUE, type = \"abline\")\n#' \n#' #\n#' ## hline and vline\n#'\n#' # Base plot layer\n#' tinyplot(mpg ~ hp | cyl, facet = \"by\", data = mtcars, ylim = c(0, 40))\n#' \n#' # Add horizontal lines at the (default) 0 y-intercept\n#' tinyplot_add(type = \"hline\", col = \"grey\")\n#' \n#' # Note that group+facet aesthetics will be inherited. We can use this to\n#' # add customized lines (here: the mean `mpg` for each `cyl` group) \n#' tinyplot_add(type = type_hline(with(mtcars, tapply(mpg, cyl, mean))), lty = 2)\n#' \n#' # Similar idea for vline\n#' tinyplot_add(type = type_vline(with(mtcars, tapply(hp, cyl, mean))), lty = 2)\n#' \n#' #\n#' ## Recycling logic\n#' \n#' # length(h) == no. of groups\n#' tinyplot(mpg ~ wt | factor(cyl), data = mtcars, type = type_hline(h = 21:23))\n#' \n#' # length(h) == no. of facets\n#' tinyplot(mpg ~ wt, facet = ~am, data = mtcars, type = type_hline(h = c(20, 30)))\n#' \n#' # length(h) == no. of groups x no. of facets\n#' tinyplot(mpg ~ wt | factor(cyl), facet = ~am, data = mtcars,\n#' type = type_hline(h = 21:26))\n#' \n#' # special adjustment case (here: lwd by group)\n#' tinyplot(mpg ~ wt | factor(cyl), facet = ~am, data = mtcars,\n#' type = type_hline(c(20, 30)), lwd = c(21, 14, 7))\n#' \n#' @export\ntype_abline = function(a = 0, b = 1) {\n data_abline = function(datapoints, lwd, lty, col, ...) {\n if (nrow(datapoints) == 0) {\n msg = \"`type_abline() only works on existing plots with x and y data points.\"\n stop(msg, call. = FALSE)\n }\n # keep track of unique lty and lwd (needed for group catch / escape hatch\n # later in draw_hline)\n ul_lwd = length(unique(lwd))\n ul_lty = length(unique(lty))\n ul_col = length(unique(col))\n return(list(type_info = list(ul_lty = ul_lty, ul_lwd = ul_lwd, ul_col = ul_col)))\n }\n draw_abline = function() {\n fun = function(\n ifacet, iby, data_facet, icol, ilty, ilwd,\n ngrps, nfacets, by_continuous, facet_by,\n type_info,\n ...\n ) {\n \n # flag for aesthetics by groups\n grp_aes = type_info[[\"ul_col\"]] == 1 || type_info[[\"ul_lty\"]] == ngrps || type_info[[\"ul_lwd\"]] == ngrps\n \n if (length(a) != 1) {\n if (!length(a) %in% c(ngrps, nfacets, ngrps*nfacets)) {\n msg = \"Length of 'a' must be 1, or equal to the number of facets or number of groups (or product thereof).\"\n stop(msg, call. = FALSE)\n }\n if (!facet_by && length(a) == nfacets) {\n a = a[ifacet]\n if (!grp_aes && type_info[[\"ul_col\"]]!=ngrps) {\n icol = 1\n } else if (by_continuous) {\n icol = 1\n }\n } else if (!by_continuous && length(a) == ngrps * nfacets) {\n a = a[ifacet * ngrps - c(ngrps - iby)]\n } else if (!by_continuous) {\n a = a[iby]\n }\n } else if (!grp_aes) {\n icol = 1\n }\n \n if (length(b) != 1) {\n if (!length(b) %in% c(ngrps, nfacets, ngrps*nfacets)) {\n msg = \"Length of 'b' must be 1, or equal to the number of facets or number of groups (or product thereof).\"\n stop(msg, call. = FALSE)\n }\n if (!facet_by && length(b) == nfacets) {\n b = b[ifacet]\n if (!grp_aes && type_info[[\"ul_col\"]]!=ngrps) {\n icol = 1\n } else if (by_continuous) {\n icol = 1\n }\n } else if (!by_continuous && length(b) == ngrps * nfacets) {\n b = b[ifacet * ngrps - c(ngrps - iby)]\n } else if (!by_continuous) {\n b = b[iby]\n }\n } else if (!grp_aes) {\n icol = 1\n }\n \n if (type_info[[\"ul_col\"]]!=1 && !(type_info[[\"ul_lty\"]]==ngrps || type_info[[\"ul_lwd\"]]==ngrps)) {\n icol = 1\n }\n\n abline(a = a, b = b, col = icol, lty = ilty, lwd = ilwd)\n }\n return(fun)\n }\n out = list(\n draw = draw_abline(),\n data = data_abline,\n name = \"abline\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_rug.R", "#' Add a rug to a plot\n#' \n#' @description\n#' Adds a rug representation (1-d plot) of the data to the plot.\n#' \n#' @details\n#' This function should only be used as part of [`tinyplot_add()`], i.e. adding\n#' to an existing plot.\n#' \n#' In most cases, determining which variable receives the rug representation\n#' will be based on the `side` argument (i.e., x-variable if side is 1 or 3, and\n#' y-variable if side is 2 or 4). An exception is if the preceding plot type was\n#' either `\"density\"` or `\"histogram\"`; for these latter cases, the x-variable\n#' will always be used. See Examples.\n#' \n#' @inheritParams graphics::rug\n#' @param jitter Logical. Add jittering to separate ties? Default is `FALSE`.\n#' @param amount Numeric. Amount of jittering (see \\code{\\link[base]{jitter}}).\n#' Only used if `jitter` is `TRUE`.\n#' @examples\n#' tinyplot(~wt | am, data = mtcars, type = \"density\", facet = \"by\", fill = \"by\")\n#' tinyplot_add(type = \"rug\")\n#' # use type_rug() to pass extra options\n#' tinyplot_add(type = type_rug(side = 3, ticksize = 0.05))\n#' \n#' # For ties, use jittering\n#' tinyplot(eruptions ~ waiting, data = faithful, type = \"lm\")\n#' tinyplot_add(type = type_rug(jitter = TRUE, amount = 0.3))\n#' tinyplot_add(type = type_rug(jitter = TRUE, amount = 0.1, side = 2))\n#' # Add original points just for reference\n#' tinyplot_add(type = \"p\")\n#' \n#' @importFrom graphics rug\n#' @export\ntype_rug = function(ticksize = 0.03, side = 1, quiet = getOption(\"warn\") < 0, jitter = FALSE, amount = NULL) {\n data_rug = function(datapoints, ...) {\n if (nrow(datapoints) == 0) {\n msg = \"`type_rug() only works on existing plots with x and y data points.\"\n stop(msg, call. = FALSE)\n }\n return(datapoints)\n }\n draw_rug = function(.ticksize = ticksize, .side = side, .quiet = quiet, .jitter = jitter, .amount = amount) {\n fun = function(ix, iy, icol, ilwd, ...) {\n lc = getOption(\"tinyplot_last_call\", default = NULL)\n swapy = !is.null(lc$type) && lc$type %in% c(\"density\", \"hist\", \"histogram\")\n rugx = if (swapy) iy else if (side %in% c(1, 3)) ix else iy\n if (isTRUE(jitter)) rugx = jitter(rugx, amount = .amount)\n rug(\n x = rugx,\n col = icol,\n lwd = ilwd,\n ticksize = .ticksize,\n side = .side,\n quiet = .quiet\n )\n }\n return(fun)\n }\n\n out = list(\n draw = draw_rug(),\n data = data_rug,\n name = \"rug\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_segments.R", "#' Line segments plot type\n#'\n#' @description Type function for plotting line segments.\n#' \n#' @details Contrary to base \\code{\\link[graphics]{segments}}, line segments in\n#' [tinyplot] must be specified using the `xmin`, `ymin`,`xmax`, and `ymax`\n#' arguments. \n#' \n#' @examples\n#' # \"segments\" type convenience character string\n#' tinyplot(\n#' xmin = c(0,.1), ymin = c(.2,1), xmax = c(1,.9), ymax = c(.75,0),\n#' type = \"segments\"\n#' )\n#' \n#' # Same result with type_segments()\n#' tinyplot(\n#' xmin = c(0,.1), ymin = c(.2,1), xmax = c(1,.9), ymax = c(.75,0),\n#' type = type_segments()\n#' )\n#' \n#' @export\ntype_segments = function() {\n out = list(\n draw = draw_segments(),\n data = NULL,\n name = \"segments\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_segments = function() {\n fun = function(ixmin, iymin, ixmax, iymax, ilty, ilwd, icol, ...) {\n segments(\n x0 = ixmin, y0 = iymin, x1 = ixmax, y1 = iymax,\n lty = ilty,\n lwd = ilwd,\n col = icol\n )\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_rect.R", "#' Rectangle plot type\n#'\n#' @description Type function for plotting rectangles.\n#' \n#' @details Contrary to base \\code{\\link[graphics]{rect}}, rectangles in\n#' [tinyplot] must be specified using the `xmin`, `ymin`,`xmax`, and `ymax`\n#' arguments. \n#' \n#' @examples\n#' i = 4*(0:10)\n#' \n#' # \"rect\" type convenience character string\n#' tinyplot(\n#' xmin = 100+i, ymin = 300+i, xmax = 150+i, ymax = 380+i,\n#' by = i, fill = 0.2,\n#' type = \"rect\"\n#' )\n#' \n#' # Same result with type_rect()\n#' tinyplot(\n#' xmin = 100+i, ymin = 300+i, xmax = 150+i, ymax = 380+i,\n#' by = i, fill = 0.2,\n#' type = type_rect()\n#' )\n#' \n#' @export\ntype_rect = function() {\n out = list(\n draw = draw_rect(),\n data = NULL,\n name = \"rect\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_rect = function() {\n fun = function(ixmin, iymin, ixmax, iymax, ilty, ilwd, icol, ibg, ...) {\n rect(\n xleft = ixmin, ybottom = iymin, xright = ixmax, ytop = iymax,\n lty = ilty,\n lwd = ilwd,\n border = icol,\n col = ibg\n )\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_errorbar.R", "#' Error bar and pointrange plot types\n#' \n#' @description Type function(s) for producing error bar and pointrange plots.\n#' \n#' @inheritParams graphics::arrows\n#' @examples\n#' mod = lm(mpg ~ wt * factor(am), mtcars)\n#' coefs = data.frame(names(coef(mod)), coef(mod), confint(mod))\n#' colnames(coefs) = c(\"term\", \"est\", \"lwr\", \"upr\")\n#' \n#' op = tpar(pch = 19)\n#' \n#' # \"errorbar\" and \"pointrange\" type convenience strings\n#' tinyplot(est ~ term, ymin = lwr, ymax = upr, data = coefs, type = \"errorbar\")\n#' tinyplot(est ~ term, ymin = lwr, ymax = upr, data = coefs, type = \"pointrange\")\n#' \n#' # Use `type_errorbar()` to pass extra arguments for customization\n#' tinyplot(est ~ term, ymin = lwr, ymax = upr, data = coefs, type = type_errorbar(length = 0.2))\n#' \n#' tpar(op)\n#' \n#' @export\ntype_errorbar = function(length = 0.05) {\n out = list(\n draw = draw_errorbar(length = length),\n data = data_pointrange(),\n name = \"p\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_errorbar = function(length = 0.05) {\n fun = function(ix, iy, ixmin, iymin, ixmax, iymax, icol, ibg, ipch, ilwd, cex, ...) {\n arrows(\n x0 = ixmin,\n y0 = iymin,\n x1 = ixmax,\n y1 = iymax,\n col = icol,\n lwd = ilwd,\n length = length,\n angle = 90,\n code = 3\n )\n draw_points()(ix = ix, iy = iy, icol = icol, ibg = ibg, ipch = ipch, ilwd = ilwd, cex = cex)\n }\n return(fun)\n}\n\n\n"], ["/tinyplot/R/zzz.R", "#' Operations on package load\n#' @importFrom utils globalVariables\n#' @param libname library name\n#' @param pkgname package name name\n#' @keywords internal\n#' @noRd\n.onLoad = function(libname, pkgname) {\n # https://stackoverflow.com/questions/12598242/global-variables-in-packages-in-r\n # https://stackoverflow.com/questions/49056642/r-how-to-make-variable-available-to-namespace-at-loading-time?noredirect=1&lq=1\n init_environment()\n init_tpar()\n set_environment_variable(\".saved_par_before\", NULL)\n set_environment_variable(\".saved_par_after\", NULL)\n set_environment_variable(\".saved_par_first\", NULL)\n set_environment_variable(\".last_call\", NULL)\n set_environment_variable(\".tpar_hooks\", NULL)\n\n globalVariables(c(\n \"add\",\n \"asp\",\n \"axes\",\n \"by_continuous\",\n \"by_ordered\",\n \"cex_fct_adj\",\n \"dots\",\n \"draw\",\n \"facet_bg\",\n \"facet_border\",\n \"facet_col\",\n \"facet_font\",\n \"facet_newlines\",\n \"facet_rect\",\n \"facet_text\",\n \"facet.args\",\n \"facet\",\n \"facets\",\n \"fill\",\n \"flip\",\n \"frame.plot\",\n \"has_legend\",\n \"iby\",\n \"ifacet\",\n \"nfacet_cols\",\n \"nfacet_rows\",\n \"nfacets\",\n \"ngrps\",\n \"oxaxis\",\n \"oyaxis\",\n \"ribbon.alpha\",\n \"split_data\",\n \"type\",\n \"x\",\n \"xaxl\",\n \"xaxs\",\n \"xaxt\",\n \"xlabs\",\n \"xlim\",\n \"xlim_user\",\n \"xlvls\",\n \"xmax\",\n \"xmin\",\n \"y\",\n \"yaxl\",\n \"yaxs\",\n \"yaxt\",\n \"ylabs\",\n \"ylim\",\n \"ylim_user\",\n \"ymax\",\n \"ymin\"\n ))\n}\n"], ["/tinyplot/R/type_polygon.R", "#' Polygon plot type\n#'\n#' @description Type function for plotting polygons.\n#' Arguments are passed to \\code{\\link[graphics]{polygon}}.\n#' \n#' @inheritParams graphics::polygon\n#' \n#' @examples\n#' # \"polygon\" type convenience character string\n#' tinyplot(1:9, c(2,1,2,1,NA,2,1,2,1), type = \"polygon\")\n#' \n#' # Use `type_polygon()` to pass extra arguments for customization\n#' tinyplot(1:9, c(2,1,2,1,NA,2,1,2,1), type = type_polygon(density = c(10, 20)))\n#' \n#' @export\ntype_polygon = function(density = NULL, angle = 45) {\n out = list(\n draw = draw_polygon(density = density, angle = angle),\n data = NULL,\n name = \"polygon\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_polygon = function(density = density, angle = 45) {\n fun = function(ix, iy, icol, ibg, ilty = par(\"lty\"), ilwd = par(\"lwd\"), ...) {\n polygon(\n x = ix,\n y = iy,\n border = icol,\n col = ibg,\n lty = ilty,\n lwd = ilwd,\n density = density,\n angle = angle\n )\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_polypath.R", "#' Polypath polygon type\n#' \n#' @description Type function for plotting polygons.\n#' Arguments are passed to \\code{\\link[graphics]{polypath}}.\n#' \n#' @inheritParams graphics::polypath\n#' \n#' @examples\n#' # \"polypath\" type convenience character string\n#' tinyplot(\n#' c(.1, .1, .6, .6, NA, .4, .4, .9, .9),\n#' c(.1, .6, .6, .1, NA, .4, .9, .9, .4),\n#' type = \"polypath\", fill = \"grey\"\n#' )\n#' \n#' # Use `type_polypath()` to pass extra arguments for customization\n#' tinyplot(\n#' c(.1, .1, .6, .6, NA, .4, .4, .9, .9),\n#' c(.1, .6, .6, .1, NA, .4, .9, .9, .4),\n#' type = type_polypath(rule = \"evenodd\"), fill = \"grey\"\n#' )\n#' @export\ntype_polypath = function(rule = \"winding\") {\n draw_polypath = function() {\n fun = function(ix, iy, icol, ibg, ilty, ilwd, dots, ...) {\n polypath(\n x = ix,\n y = iy,\n border = icol,\n col = ibg,\n lty = ilty,\n lwd = ilwd,\n rule = rule\n )\n }\n return(fun)\n }\n\n out = list(\n draw = draw_polypath(),\n data = NULL,\n name = \"polypath\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n"], ["/tinyplot/R/type_lines.R", "#' Lines plot type\n#'\n#' @description Type function for plotting lines.\n#' \n#' @inheritParams graphics::plot.default\n#' \n#' @examples\n#' # \"l\" type convenience character string\n#' tinyplot(circumference ~ age | Tree, data = Orange, type = \"l\")\n#' \n#' # Use `type_lines()` to pass extra arguments for customization\n#' tinyplot(circumference ~ age | Tree, data = Orange, type = type_lines(type = \"s\"))\n#' \n#' @export\ntype_lines = function(type = \"l\") {\n out = list(\n draw = draw_lines(type = type),\n data = NULL,\n name = type\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_lines = function(type = \"l\") {\n fun = function(ix, iy, icol, ipch, ibg, ilty, ilwd, cex = 1, ...) {\n lines(\n x = ix,\n y = iy,\n col = icol,\n type = type,\n pch = ipch,\n bg = ibg,\n lty = ilty,\n lwd = ilwd,\n cex = cex\n )\n }\n return(fun)\n}\n"], ["/tinyplot/R/tinyAxis.R", "#' @title Generic function for adding an axis to a (tiny)plot\n#' \n#' @description Internal function used for adding an axis to a [`tinyplot`]\n#' call.\n#' @details `tinyAxis` provides a thin(ish) wrapper around\n#' \\code{\\link[graphics]{Axis}}, but with enhanced flexibility to (i) match\n#' parameter combinations based on the axis type and plotting theme, (ii)\n#' provide better support for date-time variables, and (iii) enable convenient\n#' formatting of axis tick labels.\n#' @inheritParams graphics::Axis\n#' @param type the type of axis to be drawn; inherited from the `xaxt` or `yaxt`\n#' arguments of the parent [`tinyplot()`] call. One of either: `\"standard\"`\n#' (default that draws the axis, ticks, and labels), `\"none\"` (no axes),\n#' `\"ticks\"` (only ticks and labels without axis line), `\"labels\"` (only\n#' labels without ticks and axis line), or `\"axis\"` (only axis line and labels\n#' but no ticks). Partial matching is allowed, e.g. `type = \"s\"`.\n#' @inheritParams tinylabel\n#' @examples\n#' \\dontrun{\n#' \n#' # plot without axes\n#' tinyplot(0:10, axes = \"n\")\n#' # add x-axis (labels only)\n#' tinyplot:::tinyAxis(x = 0:10, side = 1, type = \"l\")\n#' # add y-axis (with custom label formatting)\n#' tinyplot:::tinyAxis(x = 0:10, side = 2, type = \"s\", labeller = \"$\")\n#' }\n#' @keywords internal\ntinyAxis = function(x = NULL, ..., type = \"standard\", labeller = NULL) {\n type = match.arg(type, c(\"standard\", \"none\", \"labels\", \"ticks\", \"axis\"))\n if (type == \"none\") {\n invisible(numeric(0L))\n } else {\n args = list(x = x, ...)\n if (type == \"labels\") {\n args$tick = FALSE\n } else if (type == \"ticks\") {\n args$lwd = 0\n if (!(\"lwd.ticks\" %in% names(args))) args$lwd.ticks = 1\n } else if (type == \"axis\") {\n args$lwd.ticks = 0\n } else {\n args$tick = TRUE\n }\n if (!is.null(labeller)) {\n if (!is.null(args$at)) {\n args$labels = if (!is.null(args$labels)) tinylabel(args$labels, labeller) else tinylabel(args$at, labeller)\n } else {\n args$at = if (!inherits(x, c(\"POSIXt\", \"Date\"))) axTicks(args$side) else axTicksDateTime(args$side, x = x) \n args$labels = tinylabel(args$at, labeller)\n }\n }\n do.call(\"Axis\", args)\n }\n}\n\n# Special case for Date-Time, adapted/simplified from axis.date()\naxTicksDateTime = function(side, x, ...) {\n if (inherits(x, \"POSIXt\")) {\n tz = attr(x, \"tz\")\n range = extendrange(x)\n rangeDateTime = .POSIXct(range, tz = tz)\n } else {\n range = sort(par(\"usr\")[if (side%%2) 1L:2L else 3:4L])\n range[1L] = ceiling(range[1L])\n range[2L] = floor(range[2L])\n rangeDateTime = range\n class(rangeDateTime) = \"Date\"\n }\n z = pretty(rangeDateTime, n = par(\"lab\")[2 - side%%2])\n keep = z >= range[1L] & z <= range[2L]\n z = z[keep]\n return(z)\n}\n"], ["/tinyplot/R/tinylabel.R", "#' Format labels\n#' \n#' @description Function for formatting label appearance, e.g. axis\n#' ticks labels. This is what the top-level `xaxl` and `yaxl` arguments\n#' from [`tinyplot`] ultimately get passed to.\n#' @param x a numeric or character vector\n#' @param labeller a formatting function to be applied to `x`, e.g. [`format`],\n#' [`toupper`], [`abs`], or other custom function (including from the popular\n#' **scales** package). Can also be one of the following convenience strings\n#' (symbols), for which common formatting transformations are provided:\n#' `\"percent\"` (`\"%\"`), `\"comma\"` (`\",\"`), `\"log\"` (`\"l\"`), `\"dollar\"`\n#' (`\"$\"`), `\"euro\"` (`\"€\"`), or `\"sterling\"` (`\"£\"`).\n#' @examples\n#' x = 1e4\n#' tinylabel(x, \"comma\")\n#' tinylabel(x, \",\") # same\n#' tinylabel(x, \"$\") # or \"dollar\"\n#' \n#' # pass to xaxl/yaxl for adjusting axes tick labels in a tinyplot call\n#' tinyplot(I(mpg/hp) ~ hp, data = mtcars, yaxl = \"%\")\n#' \n#' # log example (combined with axis scaling)\n#' tinyplot(x = 10^c(10:0), y = 0:10, type = \"b\", log = \"x\", xaxl = \"log\")\n#' \n#' # combine with `x/yaxb` to adjust the actual tick marks (\"break points\")\n#' # at the same time\n#' tinyplot(x = 10^c(10:0), y = 0:10, type = \"b\", log = \"x\", xaxl = \"log\",\n#' xaxb = 10^c(1,3,5,7,9))\n#' \n#' #\n#' ## custom function examples\n#' \n#' ## example I: date formatting\n#' \n#' dat = data.frame(\n#' date = seq(as.Date(\"2000/1/1\"), by = \"month\", length.out = 12),\n#' trend = 1:12 + rnorm(12, sd = 1)\n#' )\n#' \n#' tinyplot(trend ~ date, data = dat, xaxl = function(x) format(x, \"%b, %Y\"))\n#' \n#' ## example II: string wrapping \n#' \n#' # create a \"vectorised\" version of `base::strwrap` that breaks long\n#' # strings into new lines every 18 characters\n#' strwrap18 = function(x) sapply(\n#' strwrap(x, width = 18, simplify = FALSE),\n#' paste,\n#' collapse = \"\\n\"\n#' )\n#' \n#' # now demonstrate on a dataset with long y-tick labels\n#' dat2 = data.frame(\n#' x = rep(rnorm(100), 3),\n#' y = c(\n#' \"tinyplot is a lightweight extension of the base R graphics system.\",\n#' \"R is a language for statistical computing.\",\n#' \"Data visualization is an essential skill.\"\n#' )\n#' )\n#' \n#' tinytheme(\"bw\")\n#' tinyplot(y ~ x, data = dat2, type = \"j\", yaxl = strwrap18)\n#' tinytheme()\n#' @export\ntinylabel = function(x, labeller = NULL) {\n if (is.null(labeller)) return(x)\n if (is.character(labeller)) labeller = labeller_fun((labeller))\n return(labeller(x))\n}\n\n\nlabeller_fun = function(label = \"percent\") {\n \n labels = c(\n \"%\" = \"percent\",\n \",\" = \"comma\",\n \"$\" = \"dollar\",\n \"\\u20ac\" = \"euro\",\n \"\\u00a3\" = \"sterling\",\n \"l\" = \"log\"\n )\n if (label %in% names(labels)) label = labels[label]\n \n ## all labels plus absolute value version\n # labels = c(\"percent\", \"comma\", \"dollar\", \"euro\", \"sterling\")\n labels = c(labels, paste0(\"abs_\", labels))\n\n ## match full label first, then store abs_ info separately\n label = match.arg(label, labels)\n abs_ = substr(label, 1L, 4L) == \"abs_\"\n if (abs_) label = substr(label, 5L, nchar(label))\n\n ## actual formatting function\n format_percent = function(x) {\n sprintf(\"%.0f%%\", x * 100)\n }\n \n format_comma = function(x) {\n prettyNum(x, big.mark = \",\", scientific = FALSE)\n }\n \n format_dollar = function(x) {\n paste0(\"$\", prettyNum(x, big.mark = \",\", scientific = FALSE))\n }\n \n format_euro = function(x) {\n paste0(\"\\u20ac\", prettyNum(x, big.mark = \",\", scientific = FALSE))\n }\n \n format_sterling = function(x) {\n paste0(\"\\u00a3\", prettyNum(x, big.mark = \",\", scientific = FALSE))\n }\n \n format_log = function(x) {\n parse(text = paste0(10, \"^\", format(log10(x), digits = 3)))\n }\n \n fun = switch(\n label,\n percent = format_percent,\n comma = format_comma,\n dollar = format_dollar,\n euro = format_euro,\n sterling = format_sterling,\n log = format_log\n )\n\n ## combine with absolute value if necessary\n if (abs_) function(x) fun(abs(x)) else fun\n}\n"], ["/tinyplot/R/tinyplot_add.R", "#' Add new elements to the current `tinyplot`\n#'\n#' @description\n#' This convenience function grabs the preceding `tinyplot` call and updates it\n#' with any new arguments that have been explicitly provided by the user. It\n#' then injects `add=TRUE` and evaluates the updated call, thereby drawing a new\n#' layer on top of the existing plot. `plt_add()` is a shorthand alias for\n#' `tinyplot_add()`.\n#'\n#' @section Limitations:\n#' - `tinyplot_add()` works reliably only when adding to a plot originally\n#' created using the [`tinyplot.formula`] method with a valid `data` argument.\n#' We cannot guarantee correct behavior if the original plot was created with\n#' the atomic [`tinyplot.default`] method, due to potential environment\n#' mismatches. (An exception is when the original plot arguments---`x`, `y`,\n#' etc.---are located in the global environment.)\n#'\n#' - Automatic legends for the added elements will be turned off.\n#'\n#' @param ... All named arguments override arguments from the previous calls.\n#' Arguments not supplied to [tinyplot_add] remain unchanged from the previous\n#' call.\n#'\n#' @examples\n#' tinyplot(Sepal.Width ~ Sepal.Length | Species,\n#' facet = ~Species,\n#' data = iris)\n#'\n#' tinyplot_add(type = \"lm\") ## or : plt_add(type = \"lm\")\n#'\n#' ## Note: the previous function is equivalent to (but much more convenient\n#' ## than) re-writing the full call with the new type and `add=TRUE`:\n#'\n#' # tinyplot(Sepal.Width ~ Sepal.Length | Species,\n#' # facet = ~Species,\n#' # data = iris,\n#' # type = \"lm\",\n#' # add = TRUE)\n#'\n#' @returns No return value, called for side effect of producing a plot.\n#'\n#' @export\ntinyplot_add = function(...) {\n cal = getOption(\"tinyplot_last_call\", default = NULL)\n\n ## TODO: remove the global option above and move to this when density is refactored\n # cal = get(\".last_call\", envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n\n if (is.null(cal)) {\n stop(\"No previous tinyplot call found.\")\n }\n\n args = list(...)\n for (n in names(args)) {\n if (n != \"\") {\n cal[[n]] = args[[n]]\n }\n }\n\n # allow first argument in tinyplot_add() to be unnamed\n if (isTRUE(names(args)[1] == \"\")) {\n cal[[2]] = args[[1]]\n }\n\n cal[[\"add\"]] = TRUE\n eval(cal)\n}\n\n\n\n#' @export\n#' @name plt_add\n#' @rdname tinyplot_add\nplt_add = tinyplot_add\n"], ["/tinyplot/R/assertions.R", "check_dependency = function(library_name) {\n flag = requireNamespace(library_name, quietly = TRUE)\n if (isFALSE(flag)) {\n msg = sprintf(\"Please install the `%s` package.\", library_name)\n return(msg)\n } else {\n return(TRUE)\n }\n}\n\nassert_dependency = function(library_name) {\n flag = check_dependency(library_name)\n if (!isTRUE(flag)) stop(flag, call. = FALSE)\n return(invisible())\n}\n\nassert_choice = function(x, choice, null.ok = FALSE, name = as.character(substitute(x))) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(TRUE)\n }\n if (is.character(x) && length(x) == 1 && x %in% choice) {\n return(TRUE)\n }\n msg = sprintf(\n \"`%s` must be one of: %s\",\n name,\n paste(choice, collapse = \", \")\n )\n stop(msg, call. = FALSE)\n}\n\ncheck_true = function(x, null.ok = FALSE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(invisible(TRUE))\n }\n if (isTRUE(x)) {\n return(invisible(TRUE))\n }\n return(FALSE)\n}\n\nassert_true = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be true.\", name)\n if (!isTRUE(check_true(x, null.ok = null.ok))) {\n stop(msg, call. = FALSE)\n }\n}\n\ncheck_string = function(x, null.ok = FALSE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(invisible(TRUE))\n }\n if (is.character(x) && length(x) == 1) {\n return(invisible(TRUE))\n }\n return(FALSE)\n}\n\nassert_string = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be a string.\", name)\n if (!isTRUE(check_string(x, null.ok = null.ok))) {\n stop(msg, call. = FALSE)\n }\n}\n\ncheck_flag = function(x, null.ok = FALSE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(TRUE)\n }\n if (is.logical(x) && length(x) == 1) {\n return(TRUE)\n }\n return(FALSE)\n}\n\nassert_flag = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be a logical flag.\", name)\n if (!isTRUE(check_flag(x, null.ok = null.ok))) {\n stop(msg, call. = FALSE)\n }\n}\n\nassert_length = function(x, len = 1, null.ok = FALSE, name = as.character(substitute(x))) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(invisible(TRUE))\n }\n msg = sprintf(\"`%s` must be one of these lengths: %s\", name, paste(len, collapse = \", \"))\n if (!length(x) %in% len) {\n stop(msg, call. = FALSE)\n }\n}\n\nassert_logical = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(invisible(TRUE))\n }\n msg = sprintf(\"`%s` must be a logical vector\", name)\n if (!is.logical(x)) stop(msg, call. = FALSE)\n}\n\n\ncheck_integerish = function(x, len = NULL, lower = NULL, upper = NULL, null.ok = TRUE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(TRUE)\n }\n if (!is.numeric(x)) {\n return(FALSE)\n }\n x = stats::na.omit(x)\n if (!is.null(len) && length(x) != len) {\n return(FALSE)\n }\n if (!is.null(lower) && any(x < lower)) {\n return(FALSE)\n }\n if (!is.null(upper) && any(x > upper)) {\n return(FALSE)\n }\n if (isTRUE(any(abs(x - round(x)) > (.Machine$double.eps)^0.5))) {\n return(FALSE)\n }\n return(TRUE)\n}\n\nassert_integerish = function(x, len = NULL, lower = NULL, upper = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(invisible())\n }\n msg = sprintf(\"`%s` must be integer-ish\", name)\n if (is.null(x) && !isTRUE(null.ok)) stop(sprintf(\"%s should not be NULL.\", name), call. = FALSE)\n if (!isTRUE(check_integerish(x, len = len, lower = lower, upper = upper, null.ok = null.ok))) {\n if (!is.numeric(x)) msg = paste0(msg, \"; it is not numeric\")\n if (!is.null(len) && length(x) != len) msg = paste0(msg, sprintf(\"; its length must be %s\", len))\n if (!is.null(lower) && any(x < lower)) msg = paste0(msg, sprintf(\"; all values must be greater than or equal to %s\", lower))\n if (!is.null(upper) && any(x > upper)) msg = paste0(msg, sprintf(\"; all values must be less than or equal to %s\", upper))\n if (isTRUE(any(abs(x - round(x)) > (.Machine$double.eps)^0.5))) msg = paste0(msg, \"; all values must be close to integers\")\n stop(msg, call. = FALSE)\n }\n}\n\ncheck_numeric = function(x, len = NULL, lower = NULL, upper = NULL, null.ok = TRUE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(TRUE)\n }\n if (!is.numeric(x)) {\n return(FALSE)\n }\n if (!is.null(len) && length(x) != len) {\n return(FALSE)\n }\n if (!is.null(lower) && any(x < lower)) {\n return(FALSE)\n }\n if (!is.null(upper) && any(x > upper)) {\n return(FALSE)\n }\n return(TRUE)\n}\n\nassert_numeric = function(x, len = NULL, lower = NULL, upper = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be numeric\", name)\n if (!isTRUE(check_numeric(x, len = len, lower = lower, upper = upper, null.ok = null.ok))) {\n if (!is.null(len) && length(x) != len) msg = paste0(msg, sprintf(\"; its length must be %s\", len))\n if (!is.null(lower) && any(x < lower)) msg = paste0(msg, sprintf(\"; all values must be greater than or equal to %s\", lower))\n if (!is.null(upper) && any(x > upper)) msg = paste0(msg, sprintf(\"; all values must be less than or equal to %s\", upper))\n stop(msg, call. = FALSE)\n }\n}\n\nassert_data_frame = function(x, min_rows = 0, min_cols = 0, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be a data.frame.\", name)\n if (!is.data.frame(x)) stop(msg, call. = FALSE)\n msg = sprintf(\"Number of rows in `%s` must be at least `%s`\", name, min_rows)\n if (nrow(x) < min_rows) stop(msg, call. = FALSE)\n msg = sprintf(\"Number of columns in `%s` must be at least `%s`\", name, min_cols)\n if (ncol(x) < min_cols) stop(msg, call. = FALSE)\n}\n\n\ncheck_character = function(x, len = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(TRUE)\n } else if (!is.character(x)) {\n msg = sprintf(\"`%s` must be character.\", name)\n return(msg)\n } else if (!is.null(len) && length(x) != len) {\n msg = sprintf(\"`%s` must have length %s.\", name, len)\n return(msg)\n }\n return(TRUE)\n}\n\nassert_character = function(x, len = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n flag = check_character(x, len = len, null.ok = null.ok, name = name)\n if (!isTRUE(flag)) {\n stop(flag, call. = FALSE)\n } else {\n return(invisible(TRUE))\n }\n}\n\nassert_list = function(x, named = FALSE, len = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(invisible(TRUE))\n }\n if (!is.list(x)) stop(\"Input is not a list.\", call. = FALSE)\n if (isTRUE(named)) {\n if (is.null(names(x))) {\n stop(sprintf(\"`%s` should be named list.\", name), call. = FALSE)\n }\n }\n if (!is.null(len)) {\n if (length(x) != len) {\n stop(sprintf(\"`%s` must be of length %s.\", name, len), call. = FALSE)\n }\n }\n}\n\nassert_function = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(invisible(TRUE))\n }\n if (!is.function(x)) {\n msg = sprintf(\"`%s` must be a function.\", name)\n stop(msg, call. = FALSE)\n }\n}\n\ncheck_atomic_vector = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(invisible(TRUE))\n }\n # doesn't work on glue::glue() output\n # flag = is.atomic(x) && is.vector(x) && !is.list(x)\n flag = is.atomic(x) && is.null(dim(x)) && length(x) > 0 && !is.list(x)\n if (flag) {\n out = TRUE\n } else if (is.factor(x) && is.null(dim(x))) {\n out = TRUE\n } else {\n out = sprintf(\"`%s` must be an atomic vector.\", name)\n }\n return(out)\n}\n\nassert_atomic_vector = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n flag = check_atomic_vector(x, null.ok = null.ok, name = name)\n if (!isTRUE(flag)) {\n stop(flag, call. = FALSE)\n } else {\n return(invisible(TRUE))\n }\n}\n\nassert_class = function(x, classname) {\n if (!inherits(x, classname)) {\n msg = sprintf(\"`x` must be of class `%s`.\", classname)\n stop(msg, call. = FALSE)\n }\n}\n\n"], ["/tinyplot/R/utils.R", "rescale_num = function (x, from = NULL, to = NULL) {\n if (is.null(from)) from = range(x)\n if (is.null(to)) to = c(0, 1)\n (x - from[1])/diff(from) * diff(to) + to[1]\n}\n\n## Function for efficiently checking whether a vector has more than n unique\n## values (uses a hash set approach for large vectors to check sequentially)\nmore_than_n_unique = function(x, n, small_vec_len = 1e3L) {\n len_x = length(x)\n # For \"small\" vectors, just use direct length(unique(x)) approach\n if (len_x <= small_vec_len) {\n return(length(unique(x)) > n)\n } else {\n # For larger vectors, use the hash set approach\n env = new.env(hash = TRUE, size = n)\n count = 0\n for (val in x) {\n if (!exists(as.character(val), env)) {\n assign(as.character(val), TRUE, env)\n count = count + 1\n if (count > n) {\n return(TRUE)\n }\n }\n }\n return(FALSE)\n }\n}\n\n\n## Null coalescing operator\nif (getRversion() <= \"4.4.0\") {\n `%||%` = function(x, y) if (is.null(x)) y else x\n}\n\n\n## Function that computes an appropriate bandwidth kernel based on a string\n## input\nbw_fun = function(kernel, x) {\n kernel = tolower(kernel)\n switch(\n kernel,\n nrd0 = bw.nrd0(x),\n nrd = bw.nrd(x),\n ucv = bw.ucv(x),\n bcv = bw.bcv(x),\n sj = bw.SJ(x),\n stop(\"Invalid `bw` string. Choose from 'nrd0', 'nrd', 'ucv', 'bcv', or 'SJ'.\")\n )\n}\n"], ["/tinyplot/R/setup_device.R", "setup_device = function(file, width, height) {\n # write to file\n if (!is.null(file)) {\n filepath = file\n filewidth = width\n fileheight = height\n if (is.null(filewidth)) filewidth = .tpar[[\"file.width\"]]\n if (is.null(fileheight)) fileheight = .tpar[[\"file.height\"]]\n fileres = .tpar[[\"file.res\"]]\n # catch to close interactive device if one isn't already open\n fkdev = is.null(dev.list())\n # grab existing device pars to pass on to next one\n dop = par(no.readonly = TRUE)\n # close interactive device if not already open\n if (isTRUE(fkdev)) dev.off()\n exttype = file_ext(filepath)\n if (exttype == \"pdf\" && .tpar[[\"cairo\"]]) {\n exttype = \"cairo\"\n } else if (exttype == \"jpg\") {\n exttype = \"jpeg\"\n }\n switch(exttype,\n png = png(filepath, width = filewidth, height = fileheight, units = \"in\", res = fileres),\n jpeg = jpeg(filepath, width = filewidth, height = fileheight, units = \"in\", res = fileres),\n pdf = pdf(filepath, width = filewidth, height = fileheight),\n cairo = cairo_pdf(filepath, width = filewidth, height = fileheight),\n svg = svg(filepath, width = filewidth, height = fileheight),\n stop(\"\\nUnsupported file extension. Only '.png', '.jpg', '.pdf', or '.svg' are allowed.\\n\")\n )\n dop$new = FALSE # catch for some interfaces\n par(dop)\n\n # interactive plot with user-specified width/height\n } else if (!is.null(width) || !is.null(height)) {\n devwidth = width\n devheight = height\n # if one of width or height is missing, set equal to the other\n if (is.null(devwidth)) devwidth = devheight\n if (is.null(devheight)) devheight = devwidth\n # catch to close interactive device if one isn't already open\n fkdev = is.null(dev.list())\n # grab existing device pars to pass on to next one\n dop = par(no.readonly = TRUE)\n # close interactive device if not already open\n if (isTRUE(fkdev)) dev.off()\n dev.new(width = devwidth, height = devheight)\n dop$new = FALSE # catch for some interfaces\n par(dop)\n }\n}\n"], ["/tinyplot/R/tinytheme.R", "#' Set or Reset Plot Themes for `tinyplot`\n#'\n#' @md\n#' @description\n#' The `tinytheme` function sets or resets the theme for plots created with\n#' `tinyplot`. Themes control the appearance of plots, such as text alignment,\n#' font styles, axis labels, and even dynamic margin adjustment to reduce\n#' whitespace.\n#'\n#' @param theme A character string specifying the name of the theme to apply.\n#' Themes are arranged in an approximate hierarchy, adding or subtracting\n#' elements in the order presented below. Note that several themes are\n#' _dynamic_, in the sense that they attempt to reduce whitespace in a way\n#' that is responsive to the length of axes labels, tick marks, etc. These\n#' dynamic plots are marked with an asterisk (*) below.\n#' \n#' - `\"default\"`: inherits the user's default base graphics settings.\n#' - `\"basic\"`: light modification of `\"default\"`, only adding filled points, a panel background grid, and light gray background to facet titles.\n#' - `\"clean\"` (*): builds on `\"basic\"` by moving the subtitle above the plotting area, adding horizontal axis labels, employing tighter default plot margins and title gaps to reduce whitespace, and setting different default palettes (\"Tableau 10\" for discrete colors and \"agSunset\" for gradient colors). The first of our dynamic themes and the foundation for several derivative themes that follow below.\n#' - `\"clean2\"` (*): removes the plot frame (box) from `\"clean\"`.\n#' - `\"classic\"` (*): connects the axes in a L-shape, but removes the other top and right-hand edges of the plot frame (box). Also sets the \"Okabe-Ito\" palette as a default for discrete colors. Inspired by the **ggplot2** theme of the same name. \n#' - `\"bw\"` (*): similar to `\"clean\"`, except uses thinner lines for the plot frame (box), solid grid lines, and sets the \"Okabe-Ito\" palette as a default for discrete colors. Inspired by the **ggplot2** theme of the same name. \n#' - `\"minimal\"` (*): removes the plot frame (box) from `\"bw\"`, as well as the background for facet titles. Inspired by the **ggplot2** theme of the same name. \n#' - `\"ipsum\"` (*): similar to `\"minimal\"`, except subtitle is italicised and axes titles are aligned to the far edges. Inspired by the **hrbrthemes** theme of the same name for **ggplot2**. \n#' - `\"dark\"` (*): similar to `\"minimal\"`, but set against a dark background with foreground and a palette colours lightened for appropriate contrast.\n#' - `\"ridge\"` (*): a specialized theme for ridge plots (see [`type_ridge()`]). Builds off of `\"clean\"`, but adds ridge-specific tweaks (e.g. default \"Zissou 1\" palette for discrete colors, solid horizontal grid lines, and minor adjustments to y-axis labels). Not recommended for non-ridge plots.\n#' - `\"ridge2\"` (*): removes the plot frame (box) from `\"ridge\"`, but retains the x-axis line. Again, not recommended for non-ridge plots.\n#' - `\"tufte\"`: floating axes and minimalist plot artifacts in the style of Edward Tufte.\n#' - `\"void\"`: switches off all axes, titles, legends, etc.\n#' @param ... Named arguments to override specific theme settings. These\n#' arguments are passed to `tpar()` and take precedence over the predefined\n#' settings in the selected theme.\n#'\n#' @details\n#' Sets a list of graphical parameters using `tpar()`\n#'\n#' To reset the theme to default settings (no customization), call `tinytheme()`\n#' without arguments.\n#' \n#' **Caveat emptor:** Themes are a somewhat experimental feature of `tinyplot`.\n#' While we feel confident that themes should work as expected for most\n#' \"standard\" cases, there may be some sharp edges. Please report any unexpected\n#' behaviour to our GitHub repo:\n#' \n#' \n#' Known current limitations include:\n#' \n#' - Themes do not work well when `legend = \"top!\"`.\n#' - Dynamic margin spacing does not account for multi-line strings (e.g., axes\n#' or main titles that contain \"\\\\n\").\n#'\n#' @return The function returns nothing. It is called for its side effects.\n#' \n#' @seealso [`tpar`] which does the heavy lifting under the hood.\n#'\n#' @examples\n#' # Reusable plot function\n#' p = function() tinyplot(\n#' lat ~ long | depth, data = quakes,\n#' main = \"Earthquakes off Fiji\",\n#' sub = \"Data courtesy of the Harvard PRIM-H project\"\n#' )\n#' p()\n#' \n#' # Set a theme\n#' tinytheme(\"bw\")\n#' p()\n#'\n#' # Try a different theme\n#' tinytheme(\"dark\")\n#' p()\n#' \n#' # Customize the theme by overriding default settings\n#' tinytheme(\"bw\", fg = \"green\", font.main = 2, font.sub = 3, family = \"Palatino\")\n#' p()\n#' \n#' # Another custom theme example\n#' tinytheme(\"bw\", font.main = 2, col.axis = \"darkcyan\", family = \"HersheyScript\")\n#' p()\n#' \n#' # Aside: One or two specialized themes are only meant for certain plot types\n#' tinytheme(\"ridge2\")\n#' tinyplot(I(cut(lat, 10)) ~ depth, data = quakes, type = \"ridge\")\n#'\n#' # Reset the theme\n#' tinytheme()\n#' p()\n#' \n#' # Themes showcase\n#' ## We'll use a slightly more intricate plot (long y-axis labs and facets)\n#' ## to demonstrate dynamic margin adjustment etc.\n#' \n#' thms = eval(formals(tinytheme)$theme)\n#' \n#' for (thm in thms) {\n#' tinytheme(thm)\n#' tinyplot(\n#' I(Sepal.Length*1e4) ~ Petal.Length | Species, facet = \"by\", data = iris,\n#' main = \"Demonstration of tinyplot themes\",\n#' sub = paste0('tinytheme(\"', thm, '\")')\n#' )\n#' }\n#' \n#' # Reset\n#' tinytheme()\n#'\n#' @export\ntinytheme = function(\n theme = c(\n \"default\", \"basic\",\n \"clean\", \"clean2\", \"bw\", \"classic\",\n \"minimal\", \"ipsum\", \"dark\",\n \"ridge\", \"ridge2\",\n \"tufte\", \"void\"\n ),\n ...\n ) {\n \n theme = match.arg(theme)\n\n # in notebooks, we don't want to close the device because no image.\n # init_tpar() tries to be smart, but may fail.\n init_tpar(rm_hook = TRUE)\n\n assert_choice(\n theme,\n c(\n \"default\",\n sort(c(\"basic\", \"bw\", \"classic\", \"clean\", \"clean2\", \"dark\", \"ipsum\",\n \"minimal\", \"ridge\", \"ridge2\", \"tufte\", \"void\"))\n )\n )\n\n settings = switch(theme,\n \"default\" = theme_default,\n \"basic\" = theme_basic,\n \"bw\" = theme_bw,\n \"classic\" = theme_classic,\n \"clean\" = theme_clean,\n \"clean2\" = theme_clean2,\n \"dark\" = theme_dark,\n \"ipsum\" = theme_ipsum,\n \"minimal\" = theme_minimal,\n \"ridge\" = theme_ridge,\n \"ridge2\" = theme_ridge2,\n \"tufte\" = theme_tufte,\n \"void\" = theme_void,\n )\n\n dots = list(...)\n for (n in names(dots)) {\n settings[[n]] = dots[[n]]\n }\n\n if (length(settings) > 0) {\n if (theme == \"default\") {\n # for default theme, we want to revert the original pars and turn off the\n # before.new.plot hook (otherwise manual par(x = y) changes won't work) \n tpar(settings, hook = FALSE)\n old_hooks = get_environment_variable(\".tpar_hooks\")\n remove_hooks(old_hooks)\n } else {\n tpar(settings, hook = TRUE)\n }\n }\n\n return(invisible(NULL))\n}\n\n\n\n#\n## Themes (these are read and set at initial load time)\n\n# theme_default = list()\n\ntheme_default = list(\n tinytheme = \"default\",\n adj = par(\"adj\"), # 0.5,\n adj.main = par(\"adj\"), # 0.5,\n adj.sub = par(\"adj\"), # 0.5,\n bg = \"white\", # par(\"bg\") # \"white\"\n bty = par(\"bty\"), #\"o\",\n cex.axis = par(\"cex.axis\"), #1,\n cex.main = par(\"cex.main\"), #1.2,\n cex.xlab = par(\"cex.axis\"), #1,\n cex.ylab = par(\"cex.axis\"), #1,\n col.axis = par(\"col.axis\"), #1,\n col.xaxs = par(\"col.axis\"), #1,\n col.yaxs = par(\"col.axis\"), #1,\n col.lab = par(\"col.lab\"), #\"black\",\n col.main = par(\"col.main\"), #\"black\",\n col.sub = par(\"col.sub\"), #\"black\",\n dynmar = FALSE,\n facet.bg = NULL,\n facet.border = NA,\n family = par(\"family\"), # \"\"\n fg = par(\"fg\"),\n font = par(\"font\"), # 1,\n font.axis = par(\"font.axis\"), # 1,\n font.lab = par(\"font.lab\"), # 1,\n font.main = par(\"font.main\"), # 2,\n font.sub = par(\"font.sub\"), # 2,\n grid = FALSE,\n grid.col = \"lightgray\",\n grid.lty = \"dotted\",\n grid.lwd = 1,\n lab = par(\"lab\"), # c(5, 5, 7),\n las = par(\"las\"), # 0,\n lwd = par(\"lwd\"), # 1,\n lwd.axis = par(\"lwd\"), # 1,\n mar = c(5.1, 4.1, 4.1, 2.1), ## test\n mgp = par(\"mgp\"),\n # palette.qualitative = \"R4\",\n # palette.sequential = \"Viridis\",\n pch = par(\"pch\"), # 1,\n side.sub = 1,\n tck = NA,\n xaxt = \"standard\",\n yaxt = \"standard\"\n)\n\n# derivatives of \"default\" \n# - basic\n# - tufte\n# - void\n\ntheme_basic = modifyList(theme_default, list(\n tinytheme = \"basic\",\n facet.bg = \"gray90\",\n facet.border = \"black\",\n grid = TRUE,\n pch = 16\n))\n\ntheme_tufte = modifyList(theme_default, list(\n tinytheme = \"tufte\",\n adj.main = 0,\n adj.sub = 0,\n bty = \"n\",\n font.main = 1,\n lab = c(10, 10, 7),\n # palette.sequential = \"Grays\",\n pch = 16,\n side.sub = 3,\n tcl = 0.2\n))\n\ntheme_void = modifyList(theme_default, list(\n tinytheme = \"void\",\n adj.main = 0,\n adj.sub = 0,\n font.main = 1,\n palette.qualitative = \"Tableau 10\",\n palette.sequential = \"ag_Sunset\",\n pch = 16,\n side.sub = 3,\n # tck = -.02,\n xaxt = \"none\",\n yaxt = \"none\"\n))\n\n# derivatives of \"basic\" \n# - clean\n\ntheme_clean = modifyList(theme_basic, list(\n ## Notes:\n ## - 1. Reduce axis title gap by 0.5 lines and also reduce tcl to 0.3 lines.\n ## - 2. Sub moves to top.\n ## - 3. Also want to remove excess white on rhs of plot margin (when no legend).\n ## - Together, 1, 2, and 3 imply that...\n ## -- mgp[1] should be adjusted by 0.8 (= 0.5 + 0.3)\n ## -- mgp[2] should be adjusted by 0.3\n ## -- mar[1] should be adjusted by 1.8 (= 1 (no sub) + 0.5 + 0.3 (tighter axis labs))\n ## -- mar[2] should be adjusted by 0.8 (= 0.5 + 0.3)\n ## -- mar[3] should remain unchanged (main + sub will adjust automatically)\n ## -- mar[4] should be adjusted by 1.5 (relative to 2.1)\n ##\n tinytheme = \"clean\",\n adj.main = 0,\n adj.sub = 0,\n dynmar = TRUE,\n las = 1,\n mar = c(5.1, 4.1, 4.1, 2.1) - c(1+0.5+0.3, 0.5+0.3, 0, 1.5), ## test\n mgp = c(3, 1, 0) - c(0.5+0.3, 0.3, 0), # i.e., subtract 0.5 lines + the (abs) value of the tcl adjustment\n palette.qualitative = \"Tableau 10\",\n palette.sequential = \"ag_Sunset\",\n side.sub = 3,\n tcl = -0.3\n))\n\n# derivatives of \"clean\" \n# - clean2\n# - classic\n# - bw\n\ntheme_clean2 = modifyList(theme_clean, list(\n tinytheme = \"clean2\",\n facet.border = \"gray90\",\n xaxt = \"labels\",\n yaxt = \"labels\"\n))\n\ntheme_classic = modifyList(theme_clean, list(\n tinytheme = \"classic\",\n bty = \"l\",\n facet.bg = NULL,\n font.main = 1,\n grid = FALSE,\n palette.qualitative = \"Okabe-Ito\"\n))\n\ntheme_bw = modifyList(theme_clean, list(\n tinytheme = \"bw\",\n font.main = 1,\n grid.lty = 1,\n grid.lwd = 0.5,\n lwd = 0.5,\n lwd.axis = 0.5,\n palette.qualitative = \"Okabe-Ito\"\n))\n\n# derivatives of \"bw\"\n# - minimal\n# - ipsum\n# - dark\n \ntheme_minimal = modifyList(theme_bw, list(\n tinytheme = \"minimal\",\n bty = \"n\",\n facet.bg = NULL,\n facet.border = NULL,\n xaxt = \"labels\",\n yaxt = \"labels\"\n))\n\ntheme_ipsum = modifyList(theme_minimal, list(\n tinytheme = \"ipsum\",\n bty = \"n\",\n font.sub = 3,\n adj.ylab = 1,\n adj.xlab = 1\n))\n\ntheme_dark = modifyList(theme_minimal, list(\n tinytheme = \"dark\",\n bg = \"#1A1A1A\",\n fg = \"#BBBBBB\",\n # col = \"white\",\n col.xaxs = \"#BBBBBB\",\n col.yaxs = \"#BBBBBB\",\n col.lab = \"#BBBBBB\",\n col.main = \"#BBBBBB\",\n col.sub = \"#BBBBBB\",\n col.axis = \"#BBBBBB\",\n # facet.bg = \"gray20\",\n grid.col = \"#6D6D6D\",\n palette.qualitative = \"Set 2\",\n palette.sequential = \"Sunset\"\n))\n\n# derivative of clean/clean2\n\ntheme_ridge = modifyList(theme_clean, list(\n tinytheme = \"ridge\",\n palette.qualitative = \"Zissou 1\",\n grid = FALSE\n))\ntheme_ridge2 = modifyList(theme_clean2, list(\n tinytheme = \"ridge2\",\n palette.qualitative = \"Zissou 1\",\n grid = FALSE\n))\n"], ["/tinyplot/R/get_saved_par.R", "#' @title Retrieve the saved graphical parameters\n#' \n#' @description Convenience function for retrieving the graphical parameters\n#' (i.e., the full list of `tag = value` pairs held in\n#' \\code{\\link[graphics]{par}}) from either immediately before or\n#' immediately after the most recent [tinyplot] call.\n#'\n#' @param when character. From when should the saved parameters be retrieved?\n#' Either \"before\" (the default) or \"after\" the preceding `tinyplot` call.\n#' \n#' @details A potential side-effect of [tinyplot] is that it can change a user's\n#' \\code{\\link[graphics]{par}} settings. For example, it may adjust the inner\n#' and outer plot margins to make space for an automatic legend; see\n#' [draw_legend]. While it is possible to immediately restore the original\n#' \\code{\\link[graphics]{par}} settings upon exit via the\n#' `tinyplot(..., restore.par = TRUE)` argument, this is not the default\n#' behaviour. The reason being that we need to preserve the adjusted parameter\n#' settings in case users want to add further graphical annotations to their\n#' plot (e.g., \\code{\\link[graphics]{abline}}, \\code{\\link[graphics]{text}},\n#' etc.) Nevertheless, it may still prove desirable to recall and reset these\n#' original graphical parameters after the fact (e.g., once all these extra\n#' annotations have been added). That is the purpose of this [get_saved_par]\n#' function.\n#' \n#' Of course, users may prefer to manually capture and reset graphical\n#' parameters, as per the standard method described in the\n#' \\code{\\link[graphics]{par}} documentation. For example:\n#' \n#' ```\n#' op = par(no.readonly = TRUE) # save current par settings \n#' # \n#' par(op) # reset original pars\n#' ```\n#' \n#' This standard manual approach may be safer than [get_saved_par] because it\n#' offers more precise control. Specifically, the value of [get_saved_par] \n#' itself will be reset after ever new [tinyplot] call; i.e. it may inherit an\n#' already-changed set of parameters. Users should bear these trade-offs in\n#' mind when deciding which approach to use. As a general rule,\n#' [get_saved_par] offers the convenience of resetting the original\n#' \\code{\\link[graphics]{par}} settings even if a user forgot to save them\n#' beforehand. But one should avoid invoking it after a series of consecutive\n#' [tinyplot] calls.\n#' \n#' Finally, note that users can always call \\code{\\link[grDevices]{dev.off}}\n#' to reset all \\code{\\link[graphics]{par}} settings to their defaults.\n#' \n#' @returns A list of \\code{\\link[graphics]{par}} settings.\n#' \n#' @examples\n#' #\n#' # Contrived example where we draw a grouped scatterplot with a legend and\n#' # manually add corresponding best fit lines for each group...\n#' #\n#' \n#' # First draw the grouped scatterplot\n#' tinyplot(Sepal.Length ~ Petal.Length | Species, iris)\n#' \n#' # Preserving adjusted par settings is good for adding elements to our plot\n#' for (s in levels(iris$Species)) {\n#' abline(\n#' lm(Sepal.Length ~ Petal.Length, iris, subset = Species==s),\n#' col = which(levels(iris$Species)==s)\n#' )\n#' }\n#' \n#' # Get saved par from before the preceding tinyplot call (but don't use yet)\n#' sp = get_saved_par(\"before\")\n#' \n#' # Note the changed margins will affect regular plots too, which is probably\n#' # not desirable\n#' plot(1:10)\n#' \n#' # Reset the original parameters (could use `par(sp)` here)\n#' tpar(sp)\n#' # Redraw our simple plot with our corrected right margin\n#' plot(1:10)\n#' \n#' #\n#' # Quick example going the other way, \"correcting\" for par.restore = TRUE...\n#' #\n#' \n#' tinyplot(Sepal.Length ~ Petal.Length | Species, iris, restore.par = TRUE)\n#' # Our added best lines will be wrong b/c of misaligned par\n#' for (s in levels(iris$Species)) {\n#' abline(\n#' lm(Sepal.Length ~ Petal.Length, iris, subset = Species==s),\n#' col = which(levels(iris$Species)==s), lty = 2\n#' )\n#' }\n#' # grab the par settings from the _end_ of the preceding tinyplot call to fix\n#' tpar(get_saved_par(\"after\"))\n#' # now the best lines are correct\n#' for (s in levels(iris$Species)) {\n#' abline(\n#' lm(Sepal.Length ~ Petal.Length, iris, subset = Species==s),\n#' col = which(levels(iris$Species)==s)\n#' )\n#' }\n#' \n#' # reset again to original saved par settings before exit\n#' tpar(sp)\n#'\n#' @export\nget_saved_par = function(when = c(\"before\", \"after\", \"first\")) {\n when = match.arg(when)\n par_env_name = paste0(\".saved_par_\", when)\n return(get(par_env_name, envir = get(\".tinyplot_env\", envir = parent.env(environment()))))\n}\n\n# (non-exported) companion function(s) for setting the original pars\nset_saved_par = function(when = c(\"before\", \"after\", \"first\"), value) {\n when = match.arg(when)\n par_env_name = paste0(\".saved_par_\", when)\n assign(par_env_name, value, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n}\n"], ["/tinyplot/R/hooks.R", "# Copied from https://raw.githubusercontent.com/r-lib/evaluate/refs/heads/main/R/hooks.R\n# license: MIT + file LICENSE\n\n\n\n#' Set and remove hooks\n#'\n#' This interface wraps the base [setHook()] function to provide a return\n#' value that makes it easy to undo.\n#'\n#' @param hooks a named list of hooks - each hook can either be a function or\n#' a list of functions.\n#' @param action `\"replace\"`, `\"append\"` or `\"prepend\"`\n#' @keywords internal\nset_hooks <- function(hooks, action = \"append\") {\n old <- list()\n for (hook_name in names(hooks)) {\n old[[hook_name]] <- getHook(hook_name)\n setHook(hook_name, hooks[[hook_name]], action = action)\n }\n invisible(old)\n}\n\n#' @rdname set_hooks\n#' @keywords internal\nremove_hooks <- function(hooks) {\n for (hook_name in names(hooks)) {\n hook <- getHook(hook_name)\n if (length(hook) > 0) {\n for (fun in unlist(hooks[hook_name])) {\n hook[sapply(hook, identical, fun)] <- NULL\n }\n }\n setHook(hook_name, hook, \"replace\")\n }\n}\n"], ["/tinyplot/R/tinyformula.R", "## auxiliary functions for formula/facet parsing\n\ntinyformula = function(formula, facet = NULL) {\n ## input\n ## - formula: y ~ x or y ~ x | z or ~ x or ~ x | z\n ## - facet: ~ a or ~ a + b or b ~ a\n ##\n ## output:\n ## - x: ~ x\n ## - y: NULL or ~ y\n ## - by: NULL or ~ z or ~ z1 + z2 + ... (use interaction of all)\n ## - xfacet: NULL or ~ a or ~ a + b etc.\n ## - yfacet: NULL or ~ b\n ## - full: e.g. ~ x + y + z + a + b\n\n ## preliminaries\n if (!inherits(formula, \"formula\")) formula = as.formula(formula)\n nf = length(formula)\n\n ## basic formula types\n x = ~ x\n y = if (nf == 2L) NULL else ~ y\n by = if (!inherits(formula[[nf]], \"call\") || formula[[nf]][[1L]] != as.name(\"|\")) NULL else ~ z\n if (is.null(facet) || !inherits(facet, \"formula\")) {\n xfacet = NULL\n yfacet = NULL\n } else {\n xfacet = ~ a\n yfacet = if (length(facet) == 2L) NULL else ~ b\n }\n\n ## fill with actual terms\n environment(x) = environment(formula)\n if (!is.null(y)) {\n environment(y) = environment(formula)\n y[[2L]] = formula[[2L]]\n }\n if (is.null(by)) {\n x[[2L]] = formula[[nf]]\n } else {\n environment(by) = environment(formula)\n by[[2L]] = formula[[nf]][[3L]]\n x[[2L]] = formula[[nf]][[2L]]\n }\n if (!is.null(xfacet)) {\n environment(xfacet) = environment(formula)\n xfacet[[2L]] = facet[[length(facet)]]\n }\n if (!is.null(yfacet)) {\n environment(yfacet) = environment(formula)\n yfacet[[2L]] = facet[[2L]]\n }\n\n ## combine everything\n full = x\n if (!is.null(y)) full[[2L]] = call(\"+\", full[[2L]], y[[2L]])\n if (!is.null(by)) full[[2L]] = call(\"+\", full[[2L]], by[[2L]])\n if (!is.null(xfacet)) full[[2L]] = call(\"+\", full[[2L]], xfacet[[2L]])\n if (!is.null(yfacet)) full[[2L]] = call(\"+\", full[[2L]], yfacet[[2L]])\n\n ## return list of all formulas\n return(list(\n x = x,\n y = y,\n by = by,\n xfacet = xfacet,\n yfacet = yfacet,\n full = full\n ))\n}\n\ntinyframe = function(formula, data, drop = FALSE) {\n ## input\n ## - formula: (sub-)formula\n ## - data: model.frame from full formula\n if (is.null(formula)) return(NULL)\n names = sapply(attr(terms(formula), \"variables\")[-1L], deparse, width.cutoff = 500L)\n data[, names, drop = drop]\n}\n"], ["/tinyplot/R/environment.R", "init_environment = function() {\n tnypltptns = parent.env(environment())\n assign(\".tinyplot_env\", new.env(), envir = tnypltptns)\n .tpar = new.env()\n assign(\".tpar\", .tpar, envir = tnypltptns)\n}\n\nget_environment_variable = function(name) {\n get(name, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n}\n\nset_environment_variable = function(name, value) {\n assign(name, value, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n}\n"], ["/tinyplot/R/tinyplot-package.R", "#' @keywords internal\n\"_PACKAGE\"\n\nNULL\n"]], "task_instance_info": {"created_time": "2025-08-21 01:20:28", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(datapoints, ...) {}", "code_description": "This code segment functions to: Prepare graphical data representations by defining upper and lower bounds for area-based visualizations and configuring rendering parameters for a filled geometric shape."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nfunction(datapoints, ...) {\n transform(datapoints, ymin = 0, ymax = y) |>\n layer(\n aes_ymin = ~ymin,\n aes_ymax = ~ymax,\n alpha = ribbon.alpha\n )\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-20-54"}, "editdistance_info": {"edit_distance": 23.2558, "calculate_time": "2025-08-21 01:20:54", "true_code_clean": "function(datapoints, ...) {\n datapoints$ymax = datapoints$y\n datapoints$ymin = rep.int(0, nrow(datapoints))\n out = list(\n datapoints = datapoints,\n ymax = datapoints$ymax,\n ymin = datapoints$ymin,\n type = \"ribbon\",\n ribbon.alpha = ribbon.alpha\n )\n return(out)\n }", "predict_code_clean": "function(datapoints, ...) {\n transform(datapoints, ymin = 0, ymax = y) |>\n layer(\n aes_ymin = ~ymin,\n aes_ymax = ~ymax,\n alpha = ribbon.alpha\n )\n}"}} {"repo_name": "tinyplot", "file_name": "/tinyplot/R/type_text.R", "inference_info": {"prefix_code": "#' Text annotations plot type\n#'\n#' @description Type function for adding text annotations to a plot. This function allows\n#' you to draw text at specified (x,y) coordinates.\n#'\n#' @param labels Character vector of length 1 or of the same length as the\n#' number of x,y coordinates.\n#' @param font Font to be used, following [graphics::par()].\n#' @param xpd Logical value or `NA` denoting text clipping behaviour, following\n#' [graphics::par()].\n#' @param srt Numeric giving the desired string rotation in degrees.\n#' @inheritParams graphics::text\n#' @examples\n#' tinyplot(mpg ~ hp | factor(cyl),\n#' data = mtcars,\n#' type = type_text(\n#' labels = row.names(mtcars),\n#' font = 2,\n#' adj = 0\n#' )\n#' )\n#' \n#' # to avoid clipping text at the plot region, we can use xpd = NA\n#' tinyplot(mpg ~ hp | factor(cyl),\n#' data = mtcars,\n#' type = type_text(\n#' labels = row.names(mtcars),\n#' font = 2,\n#' adj = 0,\n#' xpd = NA\n#' )\n#' )\n#'\n#' @export\ntype_text = function(labels, adj = NULL, pos = NULL, offset = 0.5, vfont = NULL, font = NULL, xpd = NULL, srt = 0) {\n out = list(\n draw = draw_text(adj = adj, pos = pos, offset = offset, vfont = vfont, font = font, xpd = xpd, srt = srt),\n data = data_text(labels = labels),\n name = \"text\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\ndata_text = function(labels) {\n fun = function(datapoints, ...) {\n if (length(labels) != 1 && length(labels) != nrow(datapoints)) {\n msg <- sprintf(\"`labels` must be of length 1 or %s.\", nrow(datapoints))\n stop(msg, call. = FALSE)\n }\n datapoints$labels = labels\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\ndraw_text = ", "suffix_code": "\n", "middle_code": "function(adj = NULL, pos = NULL, offset = 0.5, vfont = NULL, font = NULL, xpd = NULL, srt = 0) {\n if (is.null(xpd)) xpd = par(\"xpd\")\n fun = function(ix, iy, ilabels, icol, cex, ...) {\n text(\n x = ix, y = iy, labels = ilabels, col = icol,\n adj = adj, pos = pos, offset = offset,\n vfont = vfont, font = font,\n xpd = xpd,\n srt = srt,\n cex = cex\n )\n }\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/tinyplot/R/tinyplot.R", "#' @title Lightweight extension of the base R plotting function\n#'\n#' @description\n#' Enhances the base \\code{\\link[graphics]{plot}} function. Supported features\n#' include automatic legends and facets for grouped data, additional plot types,\n#' theme customization, and so on. Users can call either `tinyplot()`, or its\n#' shorthand alias `plt()`.\n#'\n#' @md\n#' @param x,y the x and y arguments provide the x and y coordinates for the\n#' plot. Any reasonable way of defining the coordinates is acceptable; most\n#' likely the names of existing vectors or columns of data frames. See the\n#' 'Examples' section below, or the function\n#' \\code{\\link[grDevices]{xy.coords}} for details. If supplied separately, `x`\n#' and `y` must be of the same length.\n#' @param xmin,xmax,ymin,ymax minimum and maximum coordinates of relevant area\n#' or interval plot types. Only used when the `type` argument is one of\n#' `\"rect\"` or `\"segments\"` (where all four min-max coordinates are required),\n#' or `\"pointrange\"`, `\"errorbar\"`, or `\"ribbon\"` (where only `ymin` and\n#' `ymax` required alongside `x`). In the formula method the arguments\n#' can be specified as `ymin = var` if `var` is a variable in `data`.\n#' @param by grouping variable(s). The default behaviour is for groups to be\n#' represented in the form of distinct colours, which will also trigger an\n#' automatic legend. (See `legend` below for customization options.) However,\n#' groups can also be presented through other plot parameters (e.g., `pch` or\n#' `lty`) by passing an appropriate \"by\" keyword; see Examples. Note that\n#' continuous (i.e., gradient) colour legends are also supported if the user\n#' passes a numeric or integer to `by`. To group by multiple variables, wrap\n#' them with \\code{\\link[base]{interaction}}.\n#' @param facet the faceting variable(s) that you want arrange separate plot\n#' windows by. Can be specified in various ways:\n#' - In \"atomic\" form, e.g. `facet = fvar`. To facet by multiple variables in\n#' atomic form, simply interact them, e.g.\n#' `interaction(fvar1, fvar2)` or `factor(fvar1):factor(fvar2)`.\n#' - As a one-sided formula, e.g. `facet = ~fvar`. Multiple variables can be\n#' specified in the formula RHS, e.g. `~fvar1 + fvar2` or `~fvar1:fvar2`. Note\n#' that these multi-variable cases are _all_ treated equivalently and\n#' converted to `interaction(fvar1, fvar2, ...)` internally. (No distinction\n#' is made between different types of binary operators, for example, and so\n#' `f1+f2` is treated the same as `f1:f2`, is treated the same as `f1*f2`,\n#' etc.)\n#' - As a two-side formula, e.g. `facet = fvar1 ~ fvar2`. In this case, the\n#' facet windows are arranged in a fixed grid layout, with the formula LHS\n#' defining the facet rows and the RHS defining the facet columns. At present\n#' only single variables on each side of the formula are well supported. (We\n#' don't recommend trying to use multiple variables on either the LHS or RHS\n#' of the two-sided formula case.)\n#' - As a special `\"by\"` convenience keyword, in which case facets will match\n#' the grouping variable(s) passed to `by` above.\n#' @param facet.args an optional list of arguments for controlling faceting\n#' behaviour. (Ignored if `facet` is NULL.) Supported arguments are as\n#' follows:\n#' - `nrow`, `ncol` for overriding the default \"square\" facet window\n#' arrangement. Only one of these should be specified, but `nrow` will take\n#' precedence if both are specified together. Ignored if a two-sided formula\n#' is passed to the main `facet` argument, since the layout is arranged in a\n#' fixed grid.\n#' - `free` a logical value indicating whether the axis limits (scales) for\n#' each individual facet should adjust independently to match the range of\n#' the data within that facet. Default is `FALSE`. Separate free scaling of\n#' the x- or y-axis (i.e., whilst holding the other axis fixed) is not\n#' currently supported.\n#' - `fmar` a vector of form `c(b,l,t,r)` for controlling the base margin\n#' between facets in terms of lines. Defaults to the value of `tpar(\"fmar\")`,\n#' which should be `c(1,1,1,1)`, i.e. a single line of padding around each\n#' individual facet, assuming it hasn't been overridden by the user as part\n#' their global \\code{\\link[tinyplot]{tpar}} settings. Note some automatic\n#' adjustments are made for certain layouts, and depending on whether the plot\n#' is framed or not, to reduce excess whitespace. See\n#' \\code{\\link[tinyplot]{tpar}} for more details.\n#' - `cex`, `font`, `col`, `bg`, `border` for adjusting the facet title text\n#' and background. Default values for these arguments are inherited from\n#' \\code{\\link[tinyplot]{tpar}} (where they take a \"facet.\" prefix, e.g.\n#' `tpar(\"facet.cex\")`). The latter function can also be used to set these\n#' features globally for all `tinyplot` plots.\n#' @param formula a \\code{\\link[stats]{formula}} that optionally includes\n#' grouping variable(s) after a vertical bar, e.g. `y ~ x | z`. One-sided\n#' formulae are also permitted, e.g. `~ y | z`. Only a single `y` and `x`\n#' variable (if any) must be specified but multiple grouping variables\n#' can be included in different ways, e.g. `y ~ x | z1:z2` or\n#' `y ~ x | z1 + z2`. (These two representations are treated as equivalent;\n#' both are parsed as `interaction(z1, z2)` internally.) If arithmetic\n#' operators are used for transforming variables, they should be wrapped in\n#' `I()`, e.g., `I(y1/y2) ~ x`. Note that the `formula` and `x` arguments\n#' should not be specified in the same call.\n#' @param data a data.frame (or list) from which the variables in formula\n#' should be taken. A matrix is converted to a data frame.\n#' @param type character string or call to a `type_*()` function giving the\n#' type of plot desired.\n#' - NULL (default): Choose a sensible type for the type of `x` and `y` inputs\n#' (i.e., usually `\"p\"`).\n#' - 1-character values supported by \\code{\\link[graphics]{plot}}:\n#' - `\"p\"` Points\n#' - `\"l\"` Lines\n#' - `\"b\"` Both points and lines\n#' - `\"c\"` Empty points joined by lines\n#' - `\"o\"` Overplotted points and lines\n#' - `\"s\"` Stair steps\n#' - `\"S\"` Stair steps\n#' - `\"h\"` Histogram-like vertical lines\n#' - `\"n\"` Empty plot over the extent of the data\n#' - `tinyplot`-specific types. These fall into several categories:\n#' - Shapes:\n#' - `\"area\"` / [`type_area()`]: Plots the area under the curve from `y` = 0 to `y` = f(`x`).\n#' - `\"errorbar\"` / [`type_errorbar()`]: Adds error bars to points; requires `ymin` and `ymax`.\n#' - `\"pointrange\"` / [`type_pointrange()`]: Combines points with error bars.\n#' - `\"polygon\"` / [`type_polygon()`]: Draws polygons.\n#' - `\"polypath\"` / [`type_polypath()`]: Draws a path whose vertices are given in `x` and `y`.\n#' - `\"rect\"` / [`type_rect()`]: Draws rectangles; requires `xmin`, `xmax`, `ymin`, and `ymax`.\n#' - `\"ribbon\"` / [`type_ribbon()`]: Creates a filled area between `ymin` and `ymax`.\n#' - `\"segments\"` / [`type_segments()`]: Draws line segments between pairs of points.\n#' - `\"text\"` / [`type_text()`]: Add text annotations.\n#' - Visualizations:\n#' - `\"barplot\"` / [`type_barplot()`]: Creates a bar plot.\n#' - `\"boxplot\"` / [`type_boxplot()`]: Creates a box-and-whisker plot.\n#' - `\"density\"` / [`type_density()`]: Plots the density estimate of a variable.\n#' - `\"histogram\"` / [`type_histogram()`]: Creates a histogram of a single variable.\n#' - `\"jitter\"` / [`type_jitter()`]: Jittered points.\n#' - `\"qq\"` / [`type_qq()`]: Creates a quantile-quantile plot.\n#' - `\"ridge\"` / [`type_ridge()`]: Creates a ridgeline (aka joy) plot.\n#' - `\"rug\"` / [`type_rug()`]: Adds a rug to an existing plot.\n#' - `\"spineplot\"` / [`type_spineplot()`]: Creates a spineplot or spinogram.\n#' - `\"violin\"` / [`type_violin()`]: Creates a violin plot.\n#' - Models:\n#' - `\"loess\"` / [`type_loess()`]: Local regression curve.\n#' - `\"lm\"` / [`type_lm()`]: Linear regression line.\n#' - `\"glm\"` / [`type_glm()`]: Generalized linear model fit.\n#' - `\"spline\"` / [`type_spline()`]: Cubic (or Hermite) spline interpolation.\n#' - Functions:\n#' - [`type_abline()`]: line(s) with intercept and slope.\n#' - [`type_hline()`]: horizontal line(s).\n#' - [`type_vline()`]: vertical line(s).\n#' - [`type_function()`]: arbitrary function.\n#' - [`type_summary()`]: summarize `y` by unique values of `x`.\n#' @param legend one of the following options:\n#' - NULL (default), in which case the legend will be determined by the\n#' grouping variable. If there is no group variable (i.e., `by` is NULL) then\n#' no legend is drawn. If a grouping variable is detected, then an automatic\n#' legend is drawn to the _outer_ right of the plotting area. Note that the\n#' legend title and categories will automatically be inferred from the `by`\n#' argument and underlying data.\n#' - A convenience string indicating the legend position. The string should\n#' correspond to one of the position keywords supported by the base `legend`\n#' function, e.g. \"right\", \"topleft\", \"bottom\", etc. In addition, `tinyplot`\n#' supports adding a trailing exclamation point to these keywords, e.g.\n#' \"right!\", \"topleft!\", or \"bottom!\". This will place the legend _outside_\n#' the plotting area and adjust the margins of the plot accordingly. Finally,\n#' users can also turn off any legend printing by specifying \"none\".\n#' - Logical value, where TRUE corresponds to the default case above (same\n#' effect as specifying NULL) and FALSE turns the legend off (same effect as\n#' specifying \"none\").\n#' - A list or, equivalently, a dedicated `legend()` function with supported\n#' legend arguments, e.g. \"bty\", \"horiz\", and so forth.\n#' @param main a main title for the plot, see also `title`.\n#' @param sub a subtitle for the plot.\n#' @param xlab a label for the x axis, defaults to a description of x.\n#' @param ylab a label for the y axis, defaults to a description of y.\n#' @param ann a logical value indicating whether the default annotation (title\n#' and x and y axis labels) should appear on the plot.\n#' @param xlim the x limits (x1, x2) of the plot. Note that x1 > x2 is allowed\n#' and leads to a ‘reversed axis’. The default value, NULL, indicates that\n#' the range of the `finite` values to be plotted should be used.\n#' @param ylim the y limits of the plot.\n#' @param axes logical or character. Should axes be drawn (`TRUE` or `FALSE`)?\n#' Or alternatively what type of axes should be drawn: `\"standard\"` (with\n#' axis, ticks, and labels; equivalent to `TRUE`), `\"none\"` (no axes;\n#' equivalent to `FALSE`), `\"ticks\"` (only ticks and labels without axis line),\n#' `\"labels\"` (only labels without ticks and axis line), `\"axis\"` (only axis\n#' line and labels but no ticks). To control this separately for the two\n#' axes, use the character specifications for `xaxt` and/or `yaxt`.\n#' @param xaxt,yaxt character specifying the type of x-axis and y-axis,\n#' respectively. See `axes` for the possible values.\n#' @param xaxs,yaxs character specifying the style of the interval calculation\n#' used for the x-axis and y-axis, respectively. See\n#' \\code{\\link[graphics]{par}} for the possible values.\n#' @param xaxb,yaxb numeric vector (or character vector, if appropriate) giving\n#' the break points at which the axis tick-marks are to be drawn. Break points\n#' outside the range of the data will be ignored if the associated axis\n#' variable is categorical, or an explicit `x/ylim` range is given.\n#' @param xaxl,yaxl a function or a character keyword specifying the format of\n#' the x- or y-axis tick labels. Note that this is a post-processing step that\n#' affects the _appearance_ of the tick labels only; use in conjunction with\n#' `x/yaxb` if you would like to adjust the position of the tick marks too. In\n#' addition to user-supplied formatting functions (e.g., [`format`],\n#' [`toupper`], [`abs`], or other custom function), several convenience\n#' keywords (or their symbol equivalents) are available for common formatting\n#' transformations: `\"percent\"` (`\"%\"`), `\"comma\"` (`\",\"`), `\"log\"` (`\"l\"`),\n#' `\"dollar\"` (`\"$\"`), `\"euro\"` (`\"€\"`), or `\"sterling\"` (`\"£\"`). See the\n#' [`tinylabel`] documentation for examples.\n#' @param log a character string which contains `\"x\"` if the x axis is to be\n#' logarithmic, `\"y\"` if the y axis is to be logarithmic and `\"xy\"` or `\"yx\"`\n#' if both axes are to be logarithmic.\n#' @param flip logical. Should the plot orientation be flipped, so that the\n#' y-axis is on the horizontal plane and the x-axis is on the vertical plane?\n#' Default is FALSE.\n#' @param frame.plot a logical indicating whether a box should be drawn around\n#' the plot. Can also use `frame` as an acceptable argument alias.\n#' The default is to draw a frame if both axis types (set via `axes`, `xaxt`,\n#' or `yaxt`) include axis lines.\n#' @param grid argument for plotting a background panel grid, one of either:\n#' - a logical (i.e., `TRUE` to draw the grid), or\n#' - a panel grid plotting function like `grid()`.\n#' Note that this argument replaces the `panel.first` and `panel.last`\n#' arguments from base `plot()` and tries to make the process more seamless\n#' with better default behaviour. The default behaviour is determined by (and\n#' can be set globally through) the value of `tpar(\"grid\")`.\n#' @param palette one of the following options:\n#' - NULL (default), in which case the palette will be chosen according to\n#' the class and cardinality of the \"by\" grouping variable. For non-ordered\n#' factors or strings with a reasonable number of groups, this will inherit\n#' directly from the user's default \\code{\\link[grDevices]{palette}} (e.g.,\n#' \"R4\"). In other cases, including ordered factors and high cardinality, the\n#' \"Viridis\" palette will be used instead. Note that a slightly restricted\n#' version of the \"Viridis\" palette---where extreme color values have been\n#' trimmed to improve visual perception---will be used for ordered factors\n#' and continuous variables. In the latter case of a continuous grouping\n#' variable, we also generate a gradient legend swatch.\n#' - A convenience string corresponding to one of the many palettes listed by\n#' either `palette.pals()` or `hcl.pals()`. Note that the string can be\n#' case-insensitive (e.g., \"Okabe-Ito\" and \"okabe-ito\" are both valid).\n#' - A palette-generating function. This can be \"bare\" (e.g.,\n#' `palette.colors`) or \"closed\" with a set of named arguments (e.g.,\n#' `palette.colors(palette = \"Okabe-Ito\", alpha = 0.5)`). Note that any\n#' unnamed arguments will be ignored and the key `n` argument, denoting the\n#' number of colours, will automatically be spliced in as the number of\n#' groups.\n#' - A vector or list of colours, e.g. `c(\"darkorange\", \"purple\", \"cyan4\")`.\n#' If too few colours are provided for a discrete (qualitative) set of\n#' groups, then the colours will be recycled with a warning. For continuous\n#' (sequential) groups, a gradient palette will be interpolated. \n#' @param col plotting color. Character, integer, or vector of length equal to\n#' the number of categories in the `by` variable. See `col`. Note that the\n#' default behaviour in `tinyplot` is to vary group colors along any variables\n#' declared in the `by` argument. Thus, specifying colors manually should not\n#' be necessary unless users wish to override the automatic colors produced by\n#' this grouping process. Typically, this would only be done if grouping\n#' features are deferred to some other graphical parameter (i.e., passing the\n#' \"by\" keyword to one of `pch`, `lty`, `lwd`, or `bg`; see below.)\n#' @param pch plotting \"character\", i.e., symbol to use. Character, integer, or\n#' vector of length equal to the number of categories in the `by` variable.\n#' See `pch`. In addition, users can supply a special `pch = \"by\"` convenience\n#' argument, in which case the characters will automatically loop over the\n#' number groups. This automatic looping will begin at the global character\n#' value (i.e., `par(\"pch\")`) and recycle as necessary.\n#' @param lty line type. Character, integer, or vector of length equal to the\n#' number of categories in the `by` variable. See `lty`. In addition, users\n#' can supply a special `lty = \"by\"` convenience argument, in which case the\n#' line type will automatically loop over the number groups. This automatic\n#' looping will begin at the global line type value (i.e., `par(\"lty\")`) and\n#' recycle as necessary.\n#' @param lwd line width. Numeric scalar or vector of length equal to the\n#' number of categories in the `by` variable. See `lwd`. In addition, users\n#' can supply a special `lwd = \"by\"` convenience argument, in which case the\n#' line width will automatically loop over the number of groups. This\n#' automatic looping will be centered at the global line width value (i.e.,\n# ` par(\"lwd\")`) and pad on either side of that.\n#' @param bg background fill color for the open plot symbols 21:25 (see\n#' `points.default`), as well as ribbon and area plot types.\n#' Users can also supply either one of two special convenience arguments that\n#' will cause the background fill to inherit the automatic grouped coloring\n#' behaviour of `col`:\n#'\n#' - `bg = \"by\"` will insert a background fill that inherits the main color\n#' mappings from `col`.\n#' - `by = ` (i.e., a numeric in the range `[0,1]`) will insert\n#' a background fill that inherits the main color mapping(s) from `col`, but\n#' with added alpha-transparency.\n#'\n#' For both of these convenience arguments, note that the (grouped) `bg`\n#' mappings will persist even if the (grouped) `col` defaults are themselves\n#' overridden. This can be useful if you want to preserve the grouped palette\n#' mappings by background fill but not boundary color, e.g. filled points. See\n#' examples.\n#' @param fill alias for `bg`. If non-NULL values for both `bg` and `fill` are\n#' provided, then the latter will be ignored in favour of the former.\n#' @param alpha a numeric in the range `[0,1]` for adjusting the alpha channel\n#' of the color palette, where 0 means transparent and 1 means opaque. Use\n#' fractional values, e.g. `0.5` for semi-transparency.\n#' @param cex character expansion. A numerical vector (can be a single value)\n#' giving the amount by which plotting characters and symbols should be scaled\n#' relative to the default. Note that NULL is equivalent to 1.0, while NA\n#' renders the characters invisible.\n#' @param subset,na.action,drop.unused.levels arguments passed to `model.frame`\n#' when extracting the data from `formula` and `data`.\n#' @param add logical. If TRUE, then elements are added to the current plot rather\n#' than drawing a new plot window. Note that the automatic legend for the\n#' added elements will be turned off. See also [tinyplot_add], which provides\n#' a convenient wrapper around this functionality for layering on top of an\n#' existing plot without having to repeat arguments.\n#' @param draw a function that draws directly on the plot canvas (before `x` and\n#' `y` are plotted). The `draw` argument is primarily useful for adding common\n#' elements to each facet of a faceted plot, e.g.\n#' \\code{\\link[graphics]{abline}} or \\code{\\link[graphics]{text}}. Note that\n#' this argument is somewhat experimental and that _no_ internal checking is\n#' done for correctness; the provided argument is simply captured and\n#' evaluated as-is. See Examples.\n#' @param restore.par a logical value indicating whether the\n#' \\code{\\link[graphics]{par}} settings prior to calling `tinyplot` should be\n#' restored on exit. Defaults to FALSE, which makes it possible to add\n#' elements to the plot after it has been drawn. However, note the the outer\n#' margins of the graphics device may have been altered to make space for the\n#' `tinyplot` legend. Users can opt out of this persistent behaviour by\n#' setting to TRUE instead. See also [get_saved_par] for another option to\n#' recover the original \\code{\\link[graphics]{par}} settings, as well as\n#' longer discussion about the trade-offs involved.\n#' @param empty logical indicating whether the interior plot region should be\n#' left empty. The default is `FALSE`. Setting to `TRUE` has a similar effect\n#' to invoking `type = \"n\"` above, except that any legend artifacts owing to a\n#' particular plot type (e.g., lines for `type = \"l\"` or squares for\n#' `type = \"area\"`) will still be drawn correctly alongside the empty plot. In\n#' contrast,`type = \"n\"` implicitly assumes a scatterplot and so any legend\n#' will only depict points.\n#' @param file character string giving the file path for writing a plot to disk.\n#' If specified, the plot will not be displayed interactively, but rather sent\n#' to the appropriate external graphics device (i.e.,\n#' \\code{\\link[grDevices]{png}}, \\code{\\link[grDevices]{jpeg}},\n#' \\code{\\link[grDevices]{pdf}}, or \\code{\\link[grDevices]{svg}}). As a point\n#' of convenience, note that any global parameters held in `(t)par` are\n#' automatically carried over to the external device and don't need to be\n#' reset (in contrast to the conventional base R approach that requires\n#' manually opening and closing the device). The device type is determined by\n#' the file extension at the end of the provided path, and must be one of\n#' \".png\", \".jpg\" (\".jpeg\"), \".pdf\", or \".svg\". (Other file types may be\n#' supported in the future.) The file dimensions can be controlled by the\n#' corresponding `width` and `height` arguments below, otherwise will fall\n#' back to the `\"file.width\"` and `\"file.height\"` values held in\n#' \\code{\\link[tinyplot]{tpar}} (i.e., both defaulting to 7 inches, and where\n#' the default resolution for bitmap files is also specified as 300\n#' DPI).\n#' @param width numeric giving the plot width in inches. Together with `height`,\n#' typically used in conjunction with the `file` argument above, overriding the\n#' default values held in `tpar(\"file.width\", \"file.height\")`. If either `width`\n#' or `height` is specified, but a corresponding `file` argument is not\n#' provided as well, then a new interactive graphics device dimensions will be\n#' opened along the given dimensions. Note that this interactive resizing may\n#' not work consistently from within an IDE like RStudio that has an integrated\n#' graphics windows.\n#' @param height numeric giving the plot height in inches. Same considerations as\n#' `width` (above) apply, e.g. will default to `tpar(\"file.height\")` if not\n#' specified.\n#' @param asp the y/xy/x aspect ratio, see `plot.window`.\n#' @param ... other graphical parameters. If `type` is a character specification\n#' (such as `\"hist\"`) then any argument names that match those from the corresponding\n#' `type_*()` function (such as \\code{\\link{type_hist}}) are passed on to that.\n#' All remaining arguments from `...` can be further graphical parameters, see\n#' \\code{\\link[graphics]{par}}).\n#'\n#' @returns No return value, called for side effect of producing a plot.\n#'\n#' @details\n#' Disregarding the enhancements that it supports, `tinyplot` tries as far as\n#' possible to mimic the behaviour and syntax logic of the original base\n#' \\code{\\link[graphics]{plot}} function. Users should therefore be able to swap\n#' out existing `plot` calls for `tinyplot` (or its shorthand alias `plt`),\n#' without causing unexpected changes to the output.\n#'\n#' @importFrom grDevices axisTicks adjustcolor cairo_pdf colorRampPalette extendrange palette palette.colors palette.pals hcl.colors hcl.pals xy.coords png jpeg pdf svg dev.off dev.new dev.list\n#' @importFrom graphics abline arrows axis Axis axTicks box boxplot grconvertX grconvertY hist lines mtext par plot.default plot.new plot.window points polygon polypath segments rect text title\n#' @importFrom utils modifyList head tail\n#' @importFrom stats na.omit\n#' @importFrom tools file_ext\n#'\n#' @examples\n#' aq = transform(\n#' airquality,\n#' Month = factor(Month, labels = month.abb[unique(Month)])\n#' )\n#'\n#' # In most cases, `tinyplot` should be a drop-in replacement for regular\n#' # `plot` calls. For example:\n#'\n#' op = tpar(mfrow = c(1, 2))\n#' plot(0:10, main = \"plot\")\n#' tinyplot(0:10, main = \"tinyplot\")\n#' tpar(op) # restore original layout\n#'\n#' # Aside: `tinyplot::tpar()` is a (near) drop-in replacement for `par()`\n#'\n#' # Unlike vanilla plot, however, tinyplot allows you to characterize groups\n#' # using either the `by` argument or equivalent `|` formula syntax.\n#'\n#' with(aq, tinyplot(Day, Temp, by = Month)) ## atomic method\n#' tinyplot(Temp ~ Day | Month, data = aq) ## formula method\n#'\n#' # (Notice that we also get an automatic legend.)\n#'\n#' # You can also use the equivalent shorthand `plt()` alias if you'd like to\n#' # save on a few keystrokes\n#'\n#' plt(Temp ~ Day | Month, data = aq) ## shorthand alias\n#'\n#' # Use standard base plotting arguments to adjust features of your plot.\n#' # For example, change `pch` (plot character) to get filled points and `cex`\n#' # (character expansion) to increase their size.\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' pch = 16,\n#' cex = 2\n#' )\n#'\n#' # We can add alpha transparency for overlapping points\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' pch = 16,\n#' cex = 2,\n#' alpha = 0.3\n#' )\n#'\n#' # To get filled points with a common solid background color, use an\n#' # appropriate plotting character (21:25) and combine with one of the special\n#' # `bg` convenience arguments.\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' pch = 21, # use filled circles\n#' cex = 2,\n#' bg = 0.3, # numeric in [0,1] adds a grouped background fill with transparency\n#' col = \"black\" # override default color mapping; give all points a black border\n#' )\n#'\n#' # Converting to a grouped line plot is a simple matter of adjusting the\n#' # `type` argument.\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' type = \"l\"\n#' )\n#'\n#' # Similarly for other plot types, including some additional ones provided\n#' # directly by tinyplot, e.g. density plots or internal plots (ribbons,\n#' # pointranges, etc.)\n#'\n#' tinyplot(\n#' ~ Temp | Month,\n#' data = aq,\n#' type = \"density\",\n#' fill = \"by\"\n#' )\n#'\n#' # Facet plots are supported too. Facets can be drawn on their own...\n#'\n#' tinyplot(\n#' Temp ~ Day,\n#' facet = ~Month,\n#' data = aq,\n#' type = \"area\",\n#' main = \"Temperatures by month\"\n#' )\n#'\n#' # ... or combined/contrasted with the by (colour) grouping.\n#'\n#' aq = transform(aq, Summer = Month %in% c(\"Jun\", \"Jul\", \"Aug\"))\n#' tinyplot(\n#' Temp ~ Day | Summer,\n#' facet = ~Month,\n#' data = aq,\n#' type = \"area\",\n#' palette = \"dark2\",\n#' main = \"Temperatures by month and season\"\n#' )\n#'\n#' # Users can override the default square window arrangement by passing `nrow`\n#' # or `ncol` to the helper facet.args argument. Note that we can also reduce\n#' # axis label repetition across facets by turning the plot frame off.\n#'\n#' tinyplot(\n#' Temp ~ Day | Summer,\n#' facet = ~Month, facet.args = list(nrow = 1),\n#' data = aq,\n#' type = \"area\",\n#' palette = \"dark2\",\n#' frame = FALSE,\n#' main = \"Temperatures by month and season\"\n#' )\n#'\n#' # Use a two-sided formula to arrange the facet windows in a fixed grid.\n#' # LHS -> facet rows; RHS -> facet columns\n#'\n#' aq$hot = ifelse(aq$Temp >= 75, \"hot\", \"cold\")\n#' aq$windy = ifelse(aq$Wind >= 15, \"windy\", \"calm\")\n#' tinyplot(\n#' Temp ~ Day,\n#' facet = windy ~ hot,\n#' data = aq\n#' )\n#'\n#' # To add common elements to each facet, use the `draw` argument\n#'\n#' tinyplot(\n#' Temp ~ Day,\n#' facet = windy ~ hot,\n#' data = aq,\n#' draw = abline(h = 75, lty = 2, col = \"hotpink\")\n#' )\n#'\n#' # The (automatic) legend position and look can be customized using\n#' # appropriate arguments. Note the trailing \"!\" in the `legend` position\n#' # argument below. This tells `tinyplot` to place the legend _outside_ the plot\n#' # area.\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' type = \"l\",\n#' legend = legend(\"bottom!\", title = \"Month of the year\", bty = \"o\")\n#' )\n#'\n#' # The default group colours are inherited from either the \"R4\" or \"Viridis\"\n#' # palettes, depending on the number of groups. However, all palettes listed\n#' # by `palette.pals()` and `hcl.pals()` are supported as convenience strings,\n#' # or users can supply a valid palette-generating function for finer control\n#'\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' type = \"l\",\n#' palette = \"tableau\"\n#' )\n#'\n#' # It's possible to customize the look of your plots by setting graphical\n#' # parameters (e.g., via `(t)par`)... But a more convenient way is to just use\n#' # built-in themes (see `?tinytheme`).\n#'\n#' tinytheme(\"clean2\")\n#' tinyplot(\n#' Temp ~ Day | Month,\n#' data = aq,\n#' type = \"b\",\n#' alpha = 0.5,\n#' main = \"Daily temperatures by month\",\n#' sub = \"Brought to you by tinyplot\"\n#' )\n#' # reset the theme\n#' tinytheme()\n#'\n#' # For more examples and a detailed walkthrough, please see the introductory\n#' # tinyplot tutorial available online:\n#' # https://grantmcdermott.com/tinyplot/vignettes/introduction.html\n#'\n#' @rdname tinyplot\n#' @export\ntinyplot =\n function(x, ...) {\n UseMethod(\"tinyplot\")\n }\n\n#' @rdname tinyplot\n#' @export\ntinyplot.default = function(\n x = NULL,\n y = NULL,\n xmin = NULL,\n xmax = NULL,\n ymin = NULL,\n ymax = NULL,\n by = NULL,\n facet = NULL,\n facet.args = NULL,\n data = NULL,\n type = NULL,\n legend = NULL,\n main = NULL,\n sub = NULL,\n xlab = NULL,\n ylab = NULL,\n ann = par(\"ann\"),\n xlim = NULL,\n ylim = NULL,\n axes = TRUE,\n xaxt = NULL,\n yaxt = NULL,\n xaxs = NULL,\n yaxs = NULL,\n xaxb = NULL,\n yaxb = NULL,\n xaxl = NULL,\n yaxl = NULL,\n log = \"\",\n flip = FALSE,\n frame.plot = NULL,\n grid = NULL,\n palette = NULL,\n pch = NULL,\n lty = NULL,\n lwd = NULL,\n col = NULL,\n bg = NULL,\n fill = NULL,\n alpha = NULL,\n cex = 1,\n add = FALSE,\n draw = NULL,\n empty = FALSE,\n restore.par = FALSE,\n file = NULL,\n width = NULL,\n height = NULL,\n asp = NA,\n ...) {\n\n par_first = get_saved_par(\"first\")\n if (is.null(par_first)) set_saved_par(\"first\", par())\n\n assert_logical(add)\n \n # save for tinyplot_add()\n if (!add) {\n calls = sys.calls()\n idx = grep(\"^tinyplot\", sapply(calls, function(k) k[[1]]))\n if (length(idx) > 0) {\n options(tinyplot_last_call = calls[[idx[1]]])\n }\n ## TODO: remove the global option above and move to this when density is refactored\n # cal = match.call(call = sys.call(sys.parent()), expand.dots = TRUE)\n # assign(\".last_call\", cal, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n }\n\n dots = list(...)\n\n if (add) legend = FALSE\n draw = substitute(draw)\n\n\n # sanitize arguments\n\n # type factories vs. strings\n type = sanitize_type(type, x, y, dots)\n if (\"dots\" %in% names(type)) dots = type$dots\n \n # retrieve type-specific data and drawing functions\n type_data = type$data\n type_draw = type$draw\n type = type$name\n \n # area flag (mostly for legend)\n was_area_type = identical(type, \"area\")\n # check flip flag is logical \n assert_flag(flip)\n\n palette = substitute(palette)\n\n # themes\n if (is.null(palette)) palette = get_tpar(\"palette\", default = NULL)\n if (is.null(pch)) pch = get_tpar(\"pch\", default = NULL)\n\n xlabs = ylabs = NULL\n\n # type_ridge()\n ygroup = NULL\n\n # will be overwritten by some type_data() functions and ignored by others\n ribbon.alpha = sanitize_ribbon.alpha(NULL)\n\n ## handle defaults of axes, xaxt, yaxt, frame.plot\n ## - convert axes to character if necessary\n ## - set defaults of xaxt/yaxt (if these are NULL) based on axes\n ## - set logical axes based on xaxt/yaxt\n ## - set frame.plot default based on xaxt/yaxt\n if (isFALSE(axes)) {\n axes = xaxt = yaxt = \"none\"\n } else if (isTRUE(axes)) {\n axes = \"standard\"\n if (is.null(xaxt)) xaxt = get_tpar(\"xaxt\", default = \"standard\")\n if (is.null(yaxt)) yaxt = get_tpar(\"yaxt\", default = \"standard\")\n } else {\n xaxt = yaxt = axes\n }\n axis_types = c(\"standard\", \"none\", \"labels\", \"ticks\", \"axis\")\n axes = match.arg(axes, axis_types)\n xaxt = match.arg(xaxt, axis_types)\n yaxt = match.arg(yaxt, axis_types)\n xaxt = substr(match.arg(xaxt, axis_types), 1L, 1L)\n yaxt = substr(match.arg(yaxt, axis_types), 1L, 1L)\n axes = any(c(xaxt, yaxt) != \"n\")\n if (is.null(frame.plot) || !is.logical(frame.plot)) frame.plot = all(c(xaxt, yaxt) %in% c(\"s\", \"a\"))\n\n # Write plot to output file or window with fixed dimensions\n setup_device(file = file, width = width, height = height)\n if (!is.null(file)) on.exit(dev.off(), add = TRUE)\n\n # Save current graphical parameters\n opar = par(no.readonly = TRUE)\n if (restore.par || !is.null(facet)) {\n if (!is.null(file) || !is.null(width) || !is.null(height)) {\n opar$new = FALSE # catch for some interfaces\n }\n on.exit(par(opar), add = TRUE)\n }\n # set_orig_par(opar)\n set_saved_par(when = \"before\", opar)\n\n # catch for adding to existing facet plot\n if (!is.null(facet) && add) {\n recordGraphics(\n par(get_saved_par(when = \"after\")),\n list = list(),\n env = getNamespace('tinyplot')\n )\n }\n\n # Capture deparsed expressions early, before x, y and by are evaluated\n x_dep = if (!is.null(x)) {\n deparse1(substitute(x))\n } else if (type %in% c(\"rect\", \"segments\")) {\n x = NULL\n NULL\n }\n y_dep = if (is.null(y)) {\n deparse1(substitute(x))\n } else {\n deparse1(substitute(y))\n }\n by_dep = deparse1(substitute(by))\n null_by = is.null(by)\n\n ## coerce character variables to factors\n if (!is.null(x) && is.character(x)) x = factor(x)\n if (!is.null(y) && is.character(y)) y = factor(y)\n if (!null_by && is.character(by)) by = factor(by)\n\n # flag if x==by (currently only used for \"boxplot\", \"spineplot\" and \"ridges\" types)\n x_by = identical(x, by)\n\n facet_dep = deparse1(substitute(facet))\n # flag if facet==by\n facet_by = FALSE\n if (!is.null(facet) && length(facet) == 1 && facet == \"by\") {\n by = as.factor(by) ## if by==facet, then both need to be factors\n facet = by\n facet_by = TRUE\n } else if (!is.null(facet) && inherits(facet, \"formula\")) {\n facet = get_facet_fml(facet, data = data)\n if (isTRUE(attr(facet, \"facet_grid\"))) {\n facet.args[[\"nrow\"]] = attr(facet, \"facet_nrow\")\n }\n }\n facet_attr = attributes(facet) ## TODO: better solution for restoring facet attributes?\n null_facet = is.null(facet)\n\n if (is.null(x)) {\n ## Special catch for rect and segment plots without a specified y-var\n if (type %in% c(\"rect\", \"segments\")) {\n xmin_dep = deparse(substitute(xmin))\n xmax_dep = deparse(substitute(xmax))\n x_dep = paste0(\"[\", xmin_dep, \", \", xmax_dep, \"]\")\n x = rep(NA, length(x))\n }\n }\n if (is.null(y)) {\n ## Special catch for area and interval plots without a specified y-var\n if (type %in% c(\"rect\", \"segments\", \"pointrange\", \"errorbar\", \"ribbon\")) {\n ymin_dep = deparse(substitute(ymin))\n ymax_dep = deparse(substitute(ymax))\n y_dep = paste0(\"[\", ymin_dep, \", \", ymax_dep, \"]\")\n y = rep(NA, length(x))\n } else if (type == \"density\") {\n if (is.null(ylab)) ylab = \"Density\"\n } else if (type == \"function\") {\n if (is.null(ylab)) ylab = \"Frequency\"\n } else if (!(type %in% c(\"histogram\", \"barplot\"))) {\n y = x\n x = seq_along(x)\n if (is.null(xlab)) xlab = \"Index\"\n }\n }\n\n if (is.null(xlab)) xlab = x_dep\n if (is.null(ylab) && type != \"histogram\") ylab = y_dep\n \n # flag(s) indicating whether x/ylim was set by the user (needed later for\n # special case where facets are free but still want to set x/ylim manually)\n xlim_user = !is.null(xlim)\n ylim_user = !is.null(ylim)\n\n # alias\n if (is.null(bg) && !is.null(fill)) bg = fill\n\n datapoints = list(x = x, y = y, xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, ygroup = ygroup)\n datapoints = Filter(function(z) length(z) > 0, datapoints)\n datapoints = data.frame(datapoints)\n if (nrow(datapoints) > 0) {\n datapoints[[\"rowid\"]] = seq_len(nrow(datapoints))\n datapoints[[\"facet\"]] = if (!is.null(facet)) facet else \"\"\n datapoints[[\"by\"]] = if (!null_by) by else \"\"\n }\n\n ## initialize empty list with information that type_data\n ## can overwrite in order to pass on to type_draw\n type_info = list()\n\n if (!is.null(type_data)) {\n fargs = list(\n datapoints = datapoints,\n bg = bg,\n by = by,\n col = col,\n log = log,\n lty = lty,\n lwd = lwd,\n facet = facet,\n facet_by = facet_by,\n facet.args = facet.args,\n null_by = null_by,\n null_facet = null_facet,\n palette = palette,\n ribbon.alpha = ribbon.alpha,\n xaxt = xaxt,\n xaxb = xaxb,\n xaxl = xaxl,\n xlab = xlab,\n xlabs = xlabs,\n xlim = xlim,\n yaxt = yaxt,\n yaxb = yaxb,\n yaxl = yaxl,\n ylab = ylab,\n ylim = ylim\n )\n fargs = c(fargs, dots)\n list2env(do.call(type_data, fargs), environment())\n }\n\n\n # swap x and y values if flip is TRUE\n assert_flag(flip)\n # extra catch for boxplots\n # now swap the values\n if (isTRUE(flip)) {\n if (type != \"boxplot\") {\n # limits, labs, etc.\n xlim_cp = xlim\n xlim = ylim\n ylim = xlim_cp\n xlab_cp = xlab\n xlab = ylab\n ylab = xlab_cp\n xlabs_cp = xlabs\n xlabs = ylabs\n ylabs = xlabs_cp\n xaxt_cp = xaxt\n xaxt = yaxt\n yaxt = xaxt_cp\n xaxs_cp = xaxs\n xaxs = yaxs\n yaxs = xaxs_cp\n xaxb_cp = xaxb\n xaxb = yaxb\n yaxb = xaxb_cp\n xaxl_cp = xaxl\n xaxl = yaxl\n yaxl = xaxl_cp\n if (!is.null(log)) {\n log = if (log == \"x\") \"y\" else if (log == \"y\") \"x\" else log\n }\n # x/y vars\n x_cp = datapoints[[\"x\"]]\n datapoints[[\"x\"]] = datapoints[[\"y\"]]\n datapoints[[\"y\"]] = x_cp\n # x/y min and max vars\n xmin_cp = if (!is.null(datapoints[[\"xmin\"]])) datapoints[[\"xmin\"]] else NULL\n datapoints[[\"xmin\"]] = if (!is.null(datapoints[[\"ymin\"]])) datapoints[[\"ymin\"]] else NULL\n datapoints[[\"ymin\"]] = if (!is.null(xmin_cp)) xmin_cp else NULL\n xmax_cp = if (!is.null(datapoints[[\"xmax\"]])) datapoints[[\"xmax\"]] else NULL\n datapoints[[\"xmax\"]] = if (!is.null(datapoints[[\"ymax\"]])) datapoints[[\"ymax\"]] else NULL\n datapoints[[\"ymax\"]] = if (!is.null(xmax_cp)) xmax_cp else NULL\n # clean up\n rm(xlim_cp, xlab_cp, xlabs_cp, xaxt_cp, xaxs_cp, xaxb_cp, xaxl_cp, x_cp, xmin_cp, xmax_cp)\n } else {\n # We'll let boxplot(..., horizontal = TRUE) handle most of the adjustments\n # and just catch a few elements that we draw beforehand.\n xlab_cp = xlab\n xlab = ylab\n ylab = xlab_cp\n rm(xlab_cp)\n }\n }\n \n # For cases where x/yaxb is provided and corresponding x/ylabs is not null...\n # We can subset these here to provide breaks\n if (!is.null(xaxb) && !is.null(xlabs)) {\n xlabs = xlabs[names(xlabs) %in% xaxb]\n xaxb = NULL # don't need this any more\n }\n if (!is.null(yaxb) && !is.null(ylabs)) {\n ylabs = ylabs[names(ylabs) %in% yaxb]\n yaxb = NULL # don't need this any more\n }\n \n # plot limits\n fargs = lim_args(\n datapoints = datapoints,\n xlim = xlim, ylim = ylim,\n xaxb = xaxb, yaxb = yaxb,\n xlim_user = xlim_user, ylim_user = ylim_user,\n type = type\n )\n list2env(fargs, environment())\n\n\n # split data\n by_ordered = FALSE\n by_continuous = !null_by && inherits(datapoints$by, c(\"numeric\", \"integer\"))\n if (isTRUE(by_continuous) && type %in% c(\"l\", \"b\", \"o\", \"ribbon\", \"polygon\", \"polypath\", \"boxplot\")) {\n warning(\"\\nContinuous legends not supported for this plot type. Reverting to discrete legend.\")\n by_continuous = FALSE\n } else if (!null_by) {\n by_ordered = is.ordered(by)\n }\n\n if (length(unique(datapoints$facet)) == 1) {\n datapoints[[\"facet\"]] = NULL\n }\n if (!is.null(datapoints$facet)) {\n split_data = split(datapoints, datapoints$facet)\n split_data = lapply(split_data, as.list)\n } else {\n split_data = list(as.list(datapoints))\n }\n\n # aesthetics by group: col, bg, etc.\n ngrps = if (null_by) 1L else if (is.factor(by)) length(levels(by)) else if (by_continuous) 100L else length(unique(by))\n pch = by_pch(ngrps = ngrps, type = type, pch = pch)\n lty = by_lty(ngrps = ngrps, type = type, lty = lty)\n lwd = by_lwd(ngrps = ngrps, type = type, lwd = lwd)\n col = by_col(\n ngrps = ngrps, col = col, palette = palette,\n gradient = by_continuous, ordered = by_ordered, alpha = alpha)\n bg = by_bg(\n adjustcolor = adjustcolor, alpha = alpha, bg = bg, by = by, by_continuous = by_continuous,\n by_ordered = by_ordered, col = col, fill = fill, palette = substitute(palette),\n ribbon.alpha = ribbon.alpha, ngrps = ngrps, type = type)\n \n ncolors = length(col)\n lgnd_labs = rep(NA, times = ncolors)\n if (isTRUE(by_continuous)) {\n ## Identify the pretty break points for our labels\n nlabs = 5\n ncolors = length(col)\n ubyvar = unique(by)\n byvar_range = range(ubyvar)\n pbyvar = pretty(byvar_range, n = nlabs)\n pbyvar = pbyvar[pbyvar >= byvar_range[1] & pbyvar <= byvar_range[2]]\n # optional thinning\n if (length(ubyvar) == 2 && all(ubyvar %in% pbyvar)) {\n pbyvar = ubyvar\n } else if (length(pbyvar) > nlabs) {\n pbyvar = pbyvar[seq_along(pbyvar) %% 2 == 0]\n }\n ## Find the (approximate) location of our pretty labels\n pidx = rescale_num(c(byvar_range, pbyvar), to = c(1, ncolors))[-c(1:2)]\n pidx = round(pidx)\n lgnd_labs[pidx] = pbyvar\n }\n\n # Determine the number and arrangement of facets.\n # Note: We're do this up front, so we can make some adjustments to legend cex\n # next (if there are facets). But the actual drawing of the facets will only\n # come later.\n attributes(datapoints$facet) = facet_attr ## TODO: better solution for restoring facet attributes?\n fargs = facet_layout(facet = datapoints$facet, facet.args = facet.args, add = add)\n list2env(fargs, environment())\n\n #\n ## Global plot elements (legend and titles)\n #\n\n # place and draw the legend\n has_legend = FALSE # simple indicator variable for later use\n\n if (!exists(\"legend_args\")) {\n legend_args = dots[[\"legend_args\"]]\n }\n if (is.null(legend_args)) legend_args = list(x = NULL)\n legend = substitute(legend)\n\n if (isFALSE(legend)) {\n legend = \"none\"\n } else if (isTRUE(legend)) {\n legend = NULL\n }\n if (!is.null(legend) && legend == \"none\") {\n legend_args[[\"x\"]] = \"none\"\n }\n\n if (null_by) {\n if (is.null(legend)) {\n legend = \"none\"\n legend_args[[\"x\"]] = \"none\"\n }\n }\n\n if ((is.null(legend) || legend != \"none\") && !add) {\n if (isFALSE(by_continuous)) {\n if (ngrps > 1) {\n lgnd_labs = if (is.factor(datapoints$by)) levels(datapoints$by) else unique(datapoints$by)\n } else {\n lgnd_labs = ylab\n }\n }\n\n has_sub = !is.null(sub)\n\n if (isTRUE(was_area_type) || isTRUE(type %in% c(\"area\", \"rect\", \"hist\", \"histogram\"))) {\n legend_args[[\"pt.lwd\"]] = par(\"lwd\")\n legend_args[[\"lty\"]] = 0\n }\n\n draw_legend(\n legend = legend,\n legend_args = legend_args,\n by_dep = by_dep,\n lgnd_labs = lgnd_labs,\n type = type,\n pch = pch,\n lty = lty,\n lwd = lwd,\n col = col,\n bg = bg,\n gradient = by_continuous,\n cex = cex * cex_fct_adj,\n has_sub = has_sub\n )\n\n has_legend = TRUE\n } else if (legend_args[[\"x\"]] == \"none\" && !add) {\n omar = par(\"mar\")\n ooma = par(\"oma\")\n topmar_epsilon = 0.1\n\n # Catch to avoid recursive offsets, e.g. repeated tinyplot calls with\n # \"bottom!\" legend position.\n\n ## restore inner margin defaults\n ## (in case the plot region/margins were affected by the preceding tinyplot call)\n if (any(ooma != 0)) {\n if (ooma[1] != 0 && omar[1] == par(\"mgp\")[1] + 1 * par(\"cex.lab\")) omar[1] = 5.1\n if (ooma[2] != 0 && omar[2] == par(\"mgp\")[1] + 1 * par(\"cex.lab\")) omar[2] = 4.1\n if (ooma[3] == topmar_epsilon && omar[3] != 4.1) omar[3] = 4.1\n if (ooma[4] != 0 && omar[4] == 0) omar[4] = 2.1\n par(mar = omar)\n }\n ## restore outer margin defaults (with a catch for custom mfrow plots)\n if (all(par(\"mfrow\") == c(1, 1))) {\n par(omd = c(0, 1, 0, 1))\n }\n\n # clean up for now\n rm(omar, ooma, topmar_epsilon)\n\n # Draw new plot\n plot.new()\n }\n\n # Titles. Only draw these if add = FALSE\n if (!add) {\n # main title\n # Note that we include a special catch for the main title if legend is\n # \"top!\" (and main is specified in the first place).\n legend_eval = tryCatch(eval(legend), error = function(e) NULL)\n # Extra bit of footwork if user passed legend = legend(...) instead of\n # legend = list(...), since the call environment is tricky\n if (is.null(legend_eval)) {\n legend_eval = tryCatch(paste0(legend)[[2]], error = function(e) NULL)\n }\n\n adj_title = !is.null(legend) && (legend == \"top!\" || (!is.null(legend_args[[\"x\"]]) && legend_args[[\"x\"]] == \"top!\") || (is.list(legend_eval) && legend_eval[[1]] == \"top!\"))\n\n # For the \"top!\" legend case, bump main title up to make space for the\n # legend beneath it: Take the normal main title line gap (i.e., 1.7 lines)\n # and add the difference between original top margin and new one (i.e.,\n # which should equal the height of the new legend). Note that we also\n # include a 0.1 epsilon bump, which we're using to reset the tinyplot\n # window in case of recursive \"top!\" calls. (See draw_legend code.)\n\n if (isTRUE(adj_title)) {\n line_main = par(\"mar\")[3] - opar[[\"mar\"]][3] + 1.7 + 0.1\n } else {\n line_main = NULL\n }\n\n if (!is.null(sub)) {\n if (isTRUE(get_tpar(\"side.sub\", 1) == 3)) {\n if (is.null(line_main)) line_main = par(\"mgp\")[3] + 1.7 - .1\n line_main = line_main + 1.2\n }\n if (isTRUE(get_tpar(\"side.sub\", 1) == 3)) {\n line_sub = get_tpar(\"line.sub\", 1.7)\n } else {\n line_sub = get_tpar(\"line.sub\", 4)\n }\n args = list(\n text = sub,\n line = line_sub,\n cex = get_tpar(\"cex.sub\", 1.2),\n col = get_tpar(\"col.sub\", \"black\"),\n adj = get_tpar(c(\"adj.sub\", \"adj\")),\n font = get_tpar(\"font.sub\", 1),\n side = get_tpar(\"side.sub\", 1),\n las = 1\n )\n args = Filter(function(x) !is.null(x), args)\n do.call(mtext, args)\n }\n\n if (!is.null(main)) {\n args = list(\n main = main,\n line = line_main,\n cex.main = get_tpar(\"cex.main\", 1.4),\n col.main = get_tpar(\"col.main\", \"black\"),\n font.main = get_tpar(\"font.main\", 2),\n adj = get_tpar(c(\"adj.main\", \"adj\"), 3))\n args = Filter(function(x) !is.null(x), args)\n do.call(title, args)\n }\n\n\n # Axis titles\n args = list(xlab = xlab)\n args[[\"adj\"]] = get_tpar(c(\"adj.xlab\", \"adj\"))\n do.call(title, args)\n args = list(ylab = ylab)\n args[[\"adj\"]] = get_tpar(c(\"adj.ylab\", \"adj\"))\n do.call(title, args)\n }\n\n #\n ## Exterior plot elements (plot and facet windows, axes, etc.)\n #\n\n omar = NULL # Placeholder variable for now, which we re-assign as part of facet margins\n\n # placeholders for facet_window_args() call\n facet_newlines = facet_text = facet_rect = facet_font = facet_col = facet_bg = facet_border = NULL\n\n if (!is.null(facet) && !add) {\n if (is.null(omar)) omar = par(\"mar\")\n\n # Grab some of the customizable facet args that we'll be using later\n facet_rect = FALSE\n facet_text = .tpar[[\"facet.cex\"]]\n facet_font = .tpar[[\"facet.font\"]]\n facet_col = .tpar[[\"facet.col\"]]\n facet_bg = .tpar[[\"facet.bg\"]]\n facet_border = .tpar[[\"facet.border\"]]\n if (!is.null(facet.args)) {\n if (!is.null(facet.args[[\"cex\"]])) facet_text = facet.args[[\"cex\"]]\n if (!is.null(facet.args[[\"col\"]])) facet_col = facet.args[[\"col\"]]\n if (!is.null(facet.args[[\"font\"]])) facet_font = facet.args[[\"font\"]]\n if (!is.null(facet.args[[\"bg\"]])) facet_bg = facet.args[[\"bg\"]]\n if (!is.null(facet.args[[\"border\"]])) facet_border = facet.args[[\"border\"]]\n }\n if (!is.null(facet_bg) || !is.null(facet_border)) facet_rect = TRUE\n\n # Need extra adjustment to top margin if facet titles have \"\\n\" newline\n # separator. (Note that we'll also need to take account for this in the\n # individual facet margins / gaps further below.)\n facet_newlines = lengths(gregexpr(\"\\n\", grep(\"\\\\n\", facets, value = TRUE)))\n # if (length(facet_newlines)==0) facet_newlines = 0\n # omar[3] = omar[3] + max(facet_newlines)\n facet_newlines = ifelse(length(facet_newlines) == 0, 0, max(facet_newlines))\n omar[3] = omar[3] + facet_newlines * facet_text / cex_fct_adj\n # apply the changes\n par(mar = omar)\n }\n\n # Now draw the individual facet windows (incl. axes, grid lines, and facet titles)\n # Will be skipped if adding to an existing plot; see ?facet\n\n facet_window_args = recordGraphics(\n draw_facet_window(\n add = add,\n # facet-specific args\n cex_fct_adj = cex_fct_adj,\n facet.args = facet.args,\n facet_newlines = facet_newlines, facet_font = facet_font,\n facet_rect = facet_rect, facet_text = facet_text,\n facet_col = facet_col, facet_bg = facet_bg, facet_border = facet_border,\n facet = facet,\n facets = facets, ifacet = ifacet,\n nfacets = nfacets, nfacet_cols = nfacet_cols, nfacet_rows = nfacet_rows,\n # axes args\n axes = axes, flip = flip, frame.plot = frame.plot,\n oxaxis = oxaxis, oyaxis = oyaxis,\n xlabs = xlabs, xlim = xlim, xlim_user = xlim_user, xaxt = xaxt, xaxs = xaxs, xaxb = xaxb, xaxl = xaxl,\n ylabs = ylabs, ylim = ylim, ylim_user = ylim_user, yaxt = yaxt, yaxs = yaxs, yaxb = yaxb, yaxl = yaxl,\n asp = asp, log = log,\n # other args (in approx. alphabetical + group ordering)\n dots = dots,\n draw = draw,\n grid = grid,\n has_legend = has_legend,\n type = type,\n x = x, xmax = xmax, xmin = xmin,\n y = y, ymax = ymax, ymin = ymin\n ),\n list = list(\n add = add,\n cex_fct_adj = cex_fct_adj,\n facet.args = facet.args,\n facet_newlines = facet_newlines, facet_font = facet_font,\n facet_rect = facet_rect, facet_text = facet_text,\n facet_col = facet_col, facet_bg = facet_bg, facet_border = facet_border,\n facet = datapoints$facet,\n facets = facets, ifacet = ifacet,\n nfacets = nfacets, nfacet_cols = nfacet_cols, nfacet_rows = nfacet_rows,\n axes = axes, flip = flip, frame.plot = frame.plot,\n oxaxis = oxaxis, oyaxis = oyaxis,\n xlabs = xlabs, xlim = xlim, xlim_user = xlim_user, xaxt = xaxt, xaxs = xaxs, xaxb = xaxb, xaxl = xaxl,\n ylabs = ylabs, ylim = ylim, ylim_user = ylim_user, yaxt = yaxt, yaxs = yaxs, yaxb = yaxb, yaxl = yaxl,\n asp = asp, log = log,\n dots = dots,\n draw = draw,\n grid = grid,\n has_legend = has_legend,\n type = type,\n x = datapoints$x, xmax = datapoints$xmax, xmin = datapoints$xmin,\n y = datapoints$y, ymax = datapoints$ymax, ymin = datapoints$ymin\n ),\n getNamespace(\"tinyplot\")\n )\n list2env(facet_window_args, environment())\n\n\n #\n ## Interior plot elements\n #\n\n # Finally, we can draw all of the plot elements (points, lines, etc.)\n # We'll do this via a nested loops:\n # 1) Outer loop over facets\n # 2) Inner loop over groups\n\n ## Outer loop over the facets\n for (i in seq_along(split_data)) {\n # Split group-level data again to grab any \"by\" groups\n idata = split_data[[i]]\n iby = idata[[\"by\"]]\n if (!null_by) { ## maybe all(iby==\"\")\n if (isTRUE(by_continuous)) {\n idata[[\"col\"]] = col[round(rescale_num(idata$by, from = range(datapoints$by), to = c(1, 100)))]\n idata[[\"bg\"]] = bg[round(rescale_num(idata$by, from = range(datapoints$by), to = c(1, 100)))]\n idata = list(idata)\n } else {\n idata = lapply(idata, split, iby)\n idata = do.call(function(...) Map(\"list\", ...), idata)\n }\n } else {\n idata = list(idata)\n if (isTRUE(by_continuous)) {\n if (length(col) != 1) {\n idata[[1]][[\"col\"]] = col[round(rescale_num(by, to = c(1, 100)))]\n } else {\n idata[[1]][[\"col\"]] = col\n }\n if (length(bg) != 1) {\n idata[[1]][[\"bg\"]] = bg[round(rescale_num(by, to = c(1, 100)))]\n } else {\n idata[[1]][[\"bg\"]] = bg\n }\n }\n }\n \n # Set the facet \"window\" manually\n # See: https://github.com/grantmcdermott/tinyplot/issues/65\n if (nfacets > 1) {\n mfgi = ceiling(i / nfacet_cols)\n mfgj = i %% nfacet_cols\n if (mfgj == 0) mfgj = nfacet_cols\n par(mfg = c(mfgi, mfgj))\n\n # For free facets, we need to reset par(usr) based extent of that\n # particular facet... which we calculated and saved to the .fusr env var\n # (list) back in draw_facet_window()\n if (isTRUE(facet.args[[\"free\"]])) {\n fusr = get(\".fusr\", envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n par(usr = fusr[[i]])\n }\n }\n\n\n ## Inner loop over the \"by\" groupings\n for (ii in seq_along(idata)) {\n icol = col[ii]\n ibg = bg[ii]\n ipch = pch[ii]\n ilty = lty[ii]\n ilwd = lwd[ii]\n \n ix = idata[[ii]][[\"x\"]]\n iy = idata[[ii]][[\"y\"]]\n iz = idata[[ii]][[\"z\"]]\n ixmin = idata[[ii]]$xmin\n ixmax = idata[[ii]]$xmax\n iymin = idata[[ii]]$ymin\n iymax = idata[[ii]]$ymax\n ilabels = idata[[ii]][[\"labels\"]]\n\n if (isTRUE(by_continuous)) {\n icol = idata[[ii]]$col\n ibg = idata[[ii]]$bg\n }\n\n # empty plot flag\n empty_plot = FALSE\n if (isTRUE(empty) || isTRUE(type == \"n\") || ((length(ix) == 0) && !(type %in% c(\"histogram\", \"hist\", \"rect\", \"segments\", \"spineplot\")))) {\n empty_plot = TRUE\n }\n\n # Draw the individual plot elements...\n if (!isTRUE(empty_plot)) {\n if (is.null(type_draw)) {\n type_draw = switch(type,\n \"ribbon\" = type_ribbon()$draw,\n \"polygon\" = type_polygon()$draw,\n \"rect\" = type_rect()$draw,\n \"p\" = ,\n \"points\" = type_points()$draw,\n \"l\" = ,\n \"o\" = ,\n \"b\" = ,\n \"c\" = ,\n \"h\" = ,\n \"s\" = ,\n \"S\" = type_lines(type = type)$draw\n )\n }\n type_draw(\n ibg = ibg,\n icol = icol,\n ilty = ilty,\n ilwd = ilwd,\n ipch = ipch,\n ix = ix,\n ixmax = ixmax,\n ixmin = ixmin,\n iy = iy,\n iymax = iymax,\n iymin = iymin,\n ilabels = ilabels,\n iz = iz,\n cex = cex,\n dots = dots,\n type = type,\n x_by = x_by,\n by_continuous = by_continuous,\n iby = ii,\n ifacet = i,\n facet_by = facet_by,\n data_facet = idata,\n ngrps = ngrps,\n nfacets = nfacets,\n flip = flip,\n type_info = type_info,\n facet_window_args = facet_window_args\n )\n }\n }\n }\n \n if (!add) {\n # save end pars for possible recall later\n recordGraphics(\n {\n apar = par(no.readonly = TRUE)\n set_saved_par(when = \"after\", apar)\n },\n list = list(), \n env = getNamespace('tinyplot')\n )\n }\n\n}\n\n\n\n\n#' @rdname tinyplot\n#' @importFrom stats as.formula model.frame terms\n#' @export\ntinyplot.formula = function(\n x = NULL,\n data = parent.frame(),\n facet = NULL,\n facet.args = NULL,\n type = NULL,\n xmin = NULL,\n xmax = NULL,\n ymin = NULL,\n ymax = NULL,\n xlim = NULL,\n ylim = NULL,\n # log = \"\",\n main = NULL,\n sub = NULL,\n xlab = NULL,\n ylab = NULL,\n ann = par(\"ann\"),\n axes = TRUE,\n frame.plot = NULL,\n asp = NA,\n grid = NULL,\n pch = NULL,\n col = NULL,\n lty = NULL,\n lwd = NULL,\n restore.par = FALSE,\n formula = NULL,\n subset = NULL,\n na.action = NULL,\n drop.unused.levels = TRUE,\n ...) {\n ## formula for variables must be specified through 'x' or 'formula' but not both\n if (is.null(x)) {\n if (missing(formula)) {\n stop(\"plot formula must be specified by either 'x' or 'formula' argument\")\n }\n } else {\n if (missing(formula)) {\n formula = x\n } else {\n warning(\"only one of the arguments 'x' and 'formula' should be specified, defaulting to the 'formula' argument\")\n }\n }\n\n ## placeholder for legend title\n legend_args = list(x = NULL)\n\n ## turn facet into a formula if it does not evaluate successfully\n if (inherits(try(facet, silent = TRUE), \"try-error\")) {\n facet = as.formula(paste(\"~\", deparse(substitute(facet))))\n environment(facet) = environment(formula)\n }\n\n ## process all formulas\n tf = tinyformula(formula, facet)\n\n ## set up model frame\n m = match.call(expand.dots = FALSE)\n m = m[c(1L, match(c(\"formula\", \"data\", \"subset\", \"na.action\", \"drop.unused.levels\", \"xmin\", \"xmax\", \"ymin\", \"ymax\"), names(m), 0L))]\n m$formula = tf$full\n ## need stats:: for non-standard evaluation\n m[[1L]] = quote(stats::model.frame)\n mf = eval.parent(m)\n\n ## extract x\n x = tinyframe(tf$x, mf)\n xnam = names(x)[[1L]]\n if (length(names(x)) != 1L) warning(\n paste(\"formula should specify exactly one x-variable, using:\", xnam),\n \"\\nif you want to use arithmetic operators, make sure to wrap them inside I()\")\n x = x[[xnam]]\n\n ## extract y (if any)\n y = tinyframe(tf$y, mf)\n if (!is.null(y)) {\n ynam = names(y)[[1L]]\n if (length(names(y)) > 1L) warning(paste(\"formula should specify at most one y-variable, using:\", ynam),\n \"\\nif you want to use arithmetic operators, make sure to wrap them inside I()\")\n y = y[[ynam]]\n }\n\n ## extract by (if any)\n by = tinyframe(tf$by, mf)\n if (!is.null(by)) {\n bynam = names(by)\n by = if (length(bynam) == 1L) by[[bynam]] else interaction(by, sep = \":\")\n }\n\n ## extract x/y facet (if formula)\n if (!is.null(tf$xfacet) || !is.null(tf$yfacet)) {\n xfacet = tinyframe(tf$xfacet, mf)\n yfacet = tinyframe(tf$yfacet, mf)\n if (!is.null(xfacet)) xfacet = if (ncol(xfacet) == 1L) xfacet[[1L]] else interaction(xfacet, sep = \":\")\n if (!is.null(yfacet)) yfacet = if (ncol(yfacet) == 1L) yfacet[[1L]] else interaction(yfacet, sep = \":\")\n if (is.null(yfacet)) {\n facet = xfacet\n } else {\n facet = interaction(xfacet, yfacet, sep = \"~\")\n attr(facet, \"facet_grid\") = TRUE\n attr(facet, \"facet_nrow\") = length(unique(yfacet))\n }\n }\n\n ## nice axis and legend labels\n dens_type = (is.atomic(type) && identical(type, \"density\")) || (!is.atomic(type) && identical(type$name, \"density\"))\n hist_type = (is.atomic(type) && type %in% c(\"hist\", \"histogram\")) || (!is.atomic(type) && identical(type$name, \"histogram\"))\n if (!is.null(type) && dens_type) {\n # if (is.null(ylab)) ylab = \"Density\" ## rather assign ylab as part of internal type_density() logic\n if (is.null(xlab)) xlab = xnam\n } else if (!is.null(type) && hist_type) {\n # if (is.null(ylab)) ylab = \"Frequency\" ## rather assign ylab as part of internal type_histogram() logic\n if (is.null(xlab)) xlab = xnam\n } else if (is.null(y)) {\n if (is.null(ylab)) ylab = xnam\n if (is.null(xlab)) xlab = \"Index\"\n } else {\n if (is.null(ylab)) ylab = ynam\n if (is.null(xlab)) xlab = xnam\n }\n if (!is.null(by)) {\n legend_args[[\"title\"]] = if (length(bynam) == 1L) bynam else sprintf(\"interaction(%s)\", paste(bynam, collapse = \", \"))\n }\n\n tinyplot.default(\n x = x, y = y, by = by,\n facet = facet, facet.args = facet.args,\n data = data,\n type = type,\n xmin = mf[[\"(xmin)\"]],\n xmax = mf[[\"(xmax)\"]],\n ymin = mf[[\"(ymin)\"]],\n ymax = mf[[\"(ymax)\"]],\n xlim = xlim,\n ylim = ylim,\n # log = \"\",\n main = main,\n sub = sub,\n xlab = xlab,\n ylab = ylab,\n ann = ann,\n axes = axes,\n frame.plot = frame.plot,\n asp = asp,\n grid = grid,\n legend_args = legend_args,\n pch = pch,\n col = col,\n lty = lty,\n lwd = lwd,\n restore.par = restore.par,\n ...\n )\n}\n\n#' @rdname tinyplot\n#' @export\ntinyplot.density = function(\n x = NULL,\n type = c(\"l\", \"area\"),\n ...) {\n \n dots = list(...)\n \n if (!is.null(dots[[\"by\"]]) || !is.null(dots[[\"facet\"]])) {\n stop(\n '\\nGrouped and/or faceted plots are no longer supported with the tinyplot.density() method. ',\n '\\nPlease use the dedicated type argument instead, e.g. `tinyplot(..., type = \"density\")`. See `?type_density` for details.',\n '\\n\\nThis breaking change was introduced in tinyplot v0.3.0.'\n )\n }\n \n type = match.arg(type)\n \n ## override if bg = \"by\"\n if (!is.null(dots[[\"bg\"]]) || !is.null(dots[[\"fill\"]])) type = \"area\"\n \n if (inherits(x, \"density\")) {\n object = x\n # legend_args = list(x = NULL)\n # # Grab by label to pass on legend title to tinyplot.default\n # legend_args[[\"title\"]] = deparse(substitute(by))\n } else {\n ## An internal catch for non-density objects that were forcibly\n ## passed to tinyplot.density (e.g., via a one-side formula)\n if (anyNA(x)) {\n x = na.omit(x)\n x = as.numeric(x)\n }\n object = density(x)\n }\n \n x = object$x\n y = object$y\n \n if (type == \"area\") {\n ymin = rep(0, length(y))\n ymax = y\n # # set extra legend params to get bordered boxes with fill\n # legend_args[[\"x.intersp\"]] = 1.25\n # legend_args[[\"lty\"]] = 0\n # legend_args[[\"pt.lwd\"]] = 1\n }\n \n # splice in change arguments\n dots[[\"x\"]] = x\n dots[[\"y\"]] = y\n dots[[\"type\"]] = type\n \n ## axes range\n if (is.null(dots[[\"xlim\"]])) dots[[\"xlim\"]] = range(x)\n if (is.null(dots[[\"ylim\"]])) dots[[\"ylim\"]] = range(y)\n \n ## nice labels and titles\n if (is.null(dots[[\"ylab\"]])) dots[[\"ylab\"]] = \"Density\"\n if (is.null(dots[[\"xlab\"]])) dots[[\"xlab\"]] = paste0(\"N = \", object$n, \" Bandwidth = \", sprintf(\"%.4g\", object$bw))\n if (is.null(dots[[\"main\"]])) dots[[\"main\"]] = paste0(paste(object$call, collapse = \"(x = \"), \")\")\n \n do.call(tinyplot.default, args = dots)\n \n}\n\n\n#' @export\n#' @name plt\n#' @rdname tinyplot\nplt = tinyplot\n"], ["/tinyplot/R/draw_legend.R", "#' @title Calculate placement of legend and draw it\n#' \n#' @description Function used to calculate the placement of (including\n#' outside the plotting area) and drawing of legend.\n#' \n#' @md\n#' @param legend Legend placement keyword or list, passed down from [tinyplot].\n#' @param legend_args Additional legend arguments to be passed to\n#' \\code{\\link[graphics]{legend}}.\n#' @param by_dep The (deparsed) \"by\" grouping variable name.\n#' @param lgnd_labs The labels passed to `legend(legend = ...)`.\n#' @param type Plotting type(s), passed down from [tinyplot].\n#' @param pch Plotting character(s), passed down from [tinyplot].\n#' @param lty Plotting linetype(s), passed down from [tinyplot].\n#' @param lwd Plotting line width(s), passed down from [tinyplot].\n#' @param col Plotting colour(s), passed down from [tinyplot].\n#' @param bg Plotting character background fill colour(s), passed down from [tinyplot].\n#' @param cex Plotting character expansion(s), passed down from [tinyplot].\n#' @param gradient Logical indicating whether a continuous gradient swatch\n#' should be used to represent the colors.\n#' @param lmar Legend margins (in lines). Should be a numeric vector of the form\n#' `c(inner, outer)`, where the first number represents the \"inner\" margin\n#' between the legend and the plot, and the second number represents the\n#' \"outer\" margin between the legend and edge of the graphics device. If no\n#' explicit value is provided by the user, then reverts back to `tpar(\"lmar\")`\n#' for which the default values are `c(1.0, 0.1)`.\n#' @param has_sub Logical. Does the plot have a sub-caption. Only used if\n#' keyword position is \"bottom!\", in which case we need to bump the legend\n#' margin a bit further.\n#' @param new_plot Logical. Should we be calling plot.new internally?\n#' @param draw Logical. If `FALSE`, no legend is drawn but the sizes are\n#' returned. Note that a new (blank) plot frame will still need to be started\n#' in order to perform the calculations. \n#' \n#' @returns No return value, called for side effect of producing a(n empty) plot\n#' with a legend in the margin.\n#' \n#' @importFrom graphics grconvertX grconvertY rasterImage strwidth\n#' @importFrom grDevices as.raster recordGraphics\n#' @importFrom utils modifyList\n#' \n#' @examples\n#' oldmar = par(\"mar\")\n#' \n#' draw_legend(\n#' legend = \"right!\", ## default (other options incl, \"left(!)\", \"\"bottom(!)\", etc.)\n#' legend_args = list(title = \"Key\", bty = \"o\"),\n#' lgnd_labs = c(\"foo\", \"bar\"),\n#' type = \"p\",\n#' pch = 21:22,\n#' col = 1:2\n#' )\n#' \n#' # The legend is placed in the outer margin...\n#' box(\"figure\", col = \"cyan\", lty = 4)\n#' # ... and the plot is proportionally adjusted against the edge of this\n#' # margin.\n#' box(\"plot\")\n#' # You can add regular plot objects per normal now\n#' plot.window(xlim = c(1,10), ylim = c(1,10))\n#' points(1:10)\n#' points(10:1, pch = 22, col = \"red\")\n#' axis(1); axis(2)\n#' # etc.\n#' \n#' # Important: A side effect of draw_legend is that the inner margins have been\n#' # adjusted. (Here: The right margin, since we called \"right!\" above.)\n#' par(\"mar\")\n#' \n#' # To reset you should call `dev.off()` or just reset manually.\n#' par(mar = oldmar)\n#' \n#' # Note that the inner and outer margin of the legend itself can be set via\n#' # the `lmar` argument. (This can also be set globally via\n#' # `tpar(lmar = c(inner, outer))`.)\n#' draw_legend(\n#' legend_args = list(title = \"Key\", bty = \"o\"),\n#' lgnd_labs = c(\"foo\", \"bar\"),\n#' type = \"p\",\n#' pch = 21:22,\n#' col = 1:2,\n#' lmar = c(0, 0.1) ## set inner margin to zero\n#' )\n#' box(\"figure\", col = \"cyan\", lty = 4)\n#' \n#' par(mar = oldmar)\n#' \n#' # Continuous (gradient) legends are also supported\n#' draw_legend(\n#' legend = \"right!\",\n#' legend_args = list(title = \"Key\"),\n#' lgnd_labs = LETTERS[1:5],\n#' col = hcl.colors(5),\n#' gradient = TRUE ## enable gradient legend\n#' )\n#' \n#' par(mar = oldmar)\n#' \n#' @export\ndraw_legend = function(\n legend = NULL,\n legend_args = NULL,\n by_dep = NULL,\n lgnd_labs = NULL,\n type = NULL,\n pch = NULL,\n lty = NULL,\n lwd = NULL,\n col = NULL,\n bg = NULL,\n cex = NULL,\n gradient = FALSE,\n lmar = NULL,\n has_sub = FALSE,\n new_plot = TRUE,\n draw = TRUE\n) {\n \n if (is.null(lmar)) {\n lmar = tpar(\"lmar\")\n } else {\n if (!is.numeric(lmar) || length(lmar)!=2) stop (\"lmar must be a numeric of length 2.\")\n }\n \n assert_logical(gradient)\n assert_logical(has_sub)\n assert_logical(new_plot)\n assert_logical(draw)\n \n #\n ## legend args ----\n \n if (is.null(legend_args[[\"x\"]])) {\n if (is.null(legend)) {\n legend_args[[\"x\"]] = \"right!\"\n } else if (is.character(legend)) {\n legend_args = utils::modifyList(legend_args, list(x = legend))\n } else if (class(legend) %in% c(\"call\", \"name\")) {\n largs = as.list(legend)\n if (is.null(largs[[\"x\"]])) {\n lnms = names(largs)\n # check second position b/c first will be a symbol \n if (is.null(lnms)) {\n largs = stats::setNames(largs, c(\"\", \"x\"))\n } else if (length(largs)>=2 && lnms[2] == \"\") {\n lnms[2] = \"x\"\n largs = stats::setNames(largs, lnms)\n } else {\n largs[[\"x\"]] = \"right!\"\n }\n }\n # Finally, combine with any pre-existing legend args (e.g., title from the by label)\n legend_args = utils::modifyList(legend_args, largs, keep.null = TRUE)\n }\n }\n \n ## Use `!exists` rather than `is.null` for title in case user specified no title\n if (!exists(\"title\", where = legend_args)) legend_args[[\"title\"]] = by_dep\n \n legend_args[[\"pch\"]] = legend_args[[\"pch\"]] %||% pch\n legend_args[[\"lty\"]] = legend_args[[\"lty\"]] %||% lty\n legend_args[[\"col\"]] = legend_args[[\"col\"]] %||% col\n legend_args[[\"bty\"]] = legend_args[[\"bty\"]] %||% \"n\"\n legend_args[[\"horiz\"]] = legend_args[[\"horiz\"]] %||% FALSE\n legend_args[[\"xpd\"]] = legend_args[[\"xpd\"]] %||% NA\n \n if (!isTRUE(type %in% c(\"p\", \"ribbon\", \"polygon\", \"polypath\"))) {\n legend_args[[\"lwd\"]] = legend_args[[\"lwd\"]] %||% lwd\n }\n \n if (isTRUE(type %in% c(\"p\", \"pointrange\", \"errorbar\")) && (length(col) == 1 || length(cex) == 1)) {\n legend_args[[\"pt.cex\"]] = legend_args[[\"pt.cex\"]] %||% cex\n }\n \n # turn off inner line for \"barplot\" type\n if (identical(type, \"barplot\")) {\n legend_args[[\"lty\"]] = 0\n }\n \n if (isTRUE(type %in% c(\"rect\", \"ribbon\", \"polygon\", \"polypath\", \"boxplot\", \"hist\", \"histogram\", \"spineplot\", \"ridge\", \"barplot\", \"violin\")) || gradient) {\n legend_args[[\"pch\"]] = 22\n legend_args[[\"pt.cex\"]] = legend_args[[\"pt.cex\"]] %||% 3.5\n legend_args[[\"y.intersp\"]] = legend_args[[\"y.intersp\"]] %||% 1.25\n legend_args[[\"seg.len\"]] = legend_args[[\"seg.len\"]] %||% 1.25\n }\n \n if (isTRUE(type %in% c(\"ribbon\", \"hist\", \"histogram\", \"spineplot\"))) {\n legend_args[[\"pt.lwd\"]] = legend_args[[\"pt.lwd\"]] %||% 0\n }\n \n if (identical(type, \"p\")) {\n legend_args[[\"pt.lwd\"]] = legend_args[[\"pt.lwd\"]] %||% lwd\n }\n \n if (identical(type, \"n\") && isFALSE(gradient)) {\n legend_args[[\"pch\"]] = legend_args[[\"pch\"]] %||% par(\"pch\")\n }\n \n if (identical(type, \"spineplot\")) {\n legend_args[[\"pt.bg\"]] = legend_args[[\"pt.bg\"]] %||% legend_args[[\"col\"]]\n }\n \n if (identical(type, \"ridge\") && isFALSE(gradient)) {\n legend_args[[\"pt.bg\"]] = legend_args[[\"pt.bg\"]] %||% sapply(legend_args[[\"col\"]], function(ccol) seq_palette(ccol, n = 2)[2])\n }\n \n legend_args[[\"pt.bg\"]] = legend_args[[\"pt.bg\"]] %||% bg\n \n legend_args[[\"legend\"]] = legend_args[[\"legend\"]] %||% lgnd_labs\n if (length(lgnd_labs) != length(eval(legend_args[[\"legend\"]]))) {\n warning(\n \"\\nUser-supplied legend labels do not match the number of groups.\\n\",\n \"Defaulting to automatic labels determined by the group splits in `by`,\\n\"\n )\n legend_args[[\"legend\"]] = lgnd_labs\n }\n \n if (isTRUE(gradient)) {\n legend_args[[\"ncol\"]] = NULL\n }\n \n #\n ## legend placement ----\n \n # Note: \"side\" = left/right ; \"end\" = top/bottom\n outer_side = outer_end = outer_right = outer_bottom = FALSE ## placeholders\n \n ooma = par(\"oma\")\n omar = par(\"mar\")\n topmar_epsilon = 0.1\n \n # Catch to avoid recursive offsets, e.g. repeated tinyplot calls with\n # \"bottom!\" legend position.\n \n ## restore inner margin defaults\n ## (in case the plot region/margins were affected by the preceding tinyplot call)\n dynmar = isTRUE(.tpar[[\"dynmar\"]])\n if (any(ooma != 0) && !dynmar) {\n if ( ooma[1] != 0 & omar[1] == par(\"mgp\")[1] + 1*par(\"cex.lab\") ) omar[1] = 5.1\n if ( ooma[2] != 0 & omar[2] == par(\"mgp\")[1] + 1*par(\"cex.lab\") ) omar[2] = 4.1\n if ( ooma[3] == topmar_epsilon & omar[3] != 4.1 ) omar[3] = 4.1\n if ( ooma[4] != 0 & omar[4] == 0 ) omar[4] = 2.1\n par(mar = omar)\n }\n ## restore outer margin defaults\n par(omd = c(0,1,0,1))\n ooma = par(\"oma\")\n \n ## Legend to outer side (either right or left) of plot\n if (grepl(\"right!$|left!$\", legend_args[[\"x\"]])) {\n \n outer_side = TRUE\n outer_right = grepl(\"right!$\", legend_args[[\"x\"]])\n \n # extra bump for spineplot if outer_right legend (to accommodate secondary y-axis)\n if (identical(type, \"spineplot\")) lmar[1] = lmar[1] + 1.1\n \n ## Switch position anchor (we'll adjust relative to the _opposite_ side below)\n if (outer_right) legend_args[[\"x\"]] = gsub(\"right!$\", \"left\", legend_args[[\"x\"]])\n if (!outer_right) legend_args[[\"x\"]] = gsub(\"left!$\", \"right\", legend_args[[\"x\"]])\n \n ## We have to set the inner margins of the plot before the (fake) legend is\n ## drawn, otherwise the inset calculation---which is based in the legend\n ## width---will be off the first time.\n if (outer_right) {\n omar[4] = 0\n } else {\n # For outer left we have to account for the y-axis label too, which\n # requires additional space\n omar[2] = par(\"mgp\")[1] + 1*par(\"cex.lab\")\n }\n par(mar = omar)\n \n if (new_plot && draw) {\n plot.new()\n # For themed + dynamic plots, we need to make sure the adjusted plot\n # margins for the legend are reinstated (after being overwritten by\n # the before.plot.new hook.\n if (dynmar) {\n omar = par(\"mar\")\n if (outer_right) {\n omar[4] = 0\n } else {\n omar[2] = par(\"mgp\")[1] + 1*par(\"cex.lab\")\n }\n par(mar = omar)\n }\n }\n \n legend_args[[\"horiz\"]] = FALSE\n \n ## Legend at the outer top or bottom of plot\n } else if (grepl(\"bottom!$|top!$\", legend_args[[\"x\"]])) {\n\n outer_end = TRUE\n outer_bottom = grepl(\"bottom!$\", legend_args[[\"x\"]])\n\n ## Switch position anchor (we'll adjust relative to the _opposite_ side below)\n if (outer_bottom) legend_args[[\"x\"]] = gsub(\"bottom!$\", \"top\", legend_args[[\"x\"]])\n if (!outer_bottom) legend_args[[\"x\"]] = gsub(\"top!$\", \"bottom\", legend_args[[\"x\"]])\n\n ## We have to set the inner margins of the plot before the (fake) legend is\n ## drawn, otherwise the inset calculation---which is based in the legend\n ## width---will be off the first time.\n if (outer_bottom) {\n omar[1] = par(\"mgp\")[1] + 1*par(\"cex.lab\")\n if (has_sub && (is.null(.tpar[[\"side.sub\"]]) || .tpar[[\"side.sub\"]]==1)) omar[1] = omar[1] + 1*par(\"cex.sub\")\n } else {\n ## For \"top!\", the logic is slightly different: We don't expand the outer\n ## margin b/c we need the legend to come underneath the main title. So\n ## we rather expand the existing inner margin.\n ooma[3] = ooma[3] + topmar_epsilon\n par(oma = ooma)\n }\n par(mar = omar)\n\n if (new_plot && draw) {\n plot.new()\n # For themed + dynamic plots, we need to make sure the adjusted plot\n # margins for the legend are reinstated (after being overwritten by\n # the before.plot.new hook.\n if (dynmar) {\n omar = par(\"mar\")\n if (outer_bottom) {\n # omar[1] = par(\"mgp\")[1] + 1*par(\"cex.lab\")\n omar[1] = theme_clean$mgp[1] + 1*par(\"cex.lab\") ## bit of a hack\n if (has_sub && (is.null(.tpar[[\"side.sub\"]]) || .tpar[[\"side.sub\"]]==1)) omar[1] = omar[1] + 1*par(\"cex.sub\")\n } else {\n ooma[3] = ooma[3] + topmar_epsilon\n par(oma = ooma)\n }\n par(mar = omar)\n }\n }\n\n # enforce horizontal legend if user hasn't specified ncol arg\n # (exception: gradient legends at bottom/top are always horizontal)\n if (is.null(legend_args[[\"ncol\"]]) || gradient) legend_args[[\"horiz\"]] = TRUE\n\n } else {\n \n legend_args[[\"inset\"]] = 0\n if (new_plot && draw) plot.new()\n \n }\n \n # Additional tweaks for horiz and/or multi-column legends\n if (isTRUE(legend_args[[\"horiz\"]]) || !is.null(legend_args[[\"ncol\"]])) {\n # tighter horizontal labelling\n # See: https://github.com/grantmcdermott/tinyplot/issues/434\n if (!gradient) {\n legend_args[[\"text.width\"]] = NA\n # Add a space to all labs except the outer most right ones\n nlabs = length(legend_args[[\"legend\"]])\n nidx = nlabs\n if (!is.null(legend_args[[\"ncol\"]])) nidx = tail(1:nlabs, (nlabs %/% legend_args[[\"ncol\"]]))\n legend_args[[\"legend\"]][-nidx] = paste(legend_args[[\"legend\"]][-nidx], \" \")\n }\n # catch for horizontal ribbon legend spacing\n if (type==\"ribbon\") {\n if (legend_args[[\"pt.lwd\"]] == 1) {\n legend_args[[\"x.intersp\"]] = 1\n } else {\n legend_args[[\"x.intersp\"]] = 0.5\n }\n } else if (gradient) {\n legend_args[[\"x.intersp\"]] = 0.5\n }\n }\n \n #\n ## draw the legend ----\n \n # Legend drawing is handled by the internal `tinylegend()` function, which:\n # 1. calculates appropriate insets for \"outer\" legend placement\n # 2. can draw gradient legends (via `gradient_legend()` below)\n #\n # Note: We wrap everything in `recordGraphics()` to preserve legend spacing\n # if the plot is resized (also necessary for Positron graphics logic regardless)\n recordGraphics(\n tinylegend(\n legend_args = legend_args,\n ooma = ooma,\n omar = omar,\n lmar = lmar,\n topmar_epsilon = topmar_epsilon,\n outer_side = outer_side,\n outer_right = outer_right,\n outer_end = outer_end,\n outer_bottom = outer_bottom,\n gradient = gradient,\n draw = draw\n ),\n list = list(\n legend_args = legend_args,\n ooma = ooma,\n omar = omar,\n lmar = lmar,\n topmar_epsilon = topmar_epsilon,\n outer_side = outer_side,\n outer_right = outer_right,\n outer_end = outer_end,\n outer_bottom = outer_bottom,\n gradient = gradient,\n draw = draw\n ),\n env = getNamespace(\"tinyplot\")\n )\n \n}\n\n\n# tinylegend ----\n\n## Internal workhorse function that draws the legend, given a set of legend\n## arguments and other graphical parameters. It does this in three steps:\n## 1) draw a fake legend, 2) calculate the associated inset and adjust the plot\n## margins accordingly, 3) draw the real legend\n\ntinylegend = function(\n legend_args,\n ooma, omar, lmar, topmar_epsilon,\n outer_side, outer_right, outer_end, outer_bottom,\n gradient,\n draw\n) {\n \n #\n ## Step 1: \"draw\" fake legend\n \n fklgnd.args = modifyList(\n legend_args,\n list(plot = FALSE),\n keep.null = TRUE\n )\n \n if (gradient) {\n lgnd_labs_tmp = na.omit(fklgnd.args[[\"legend\"]])\n if (length(lgnd_labs_tmp) < 5L) {\n nmore = 5L - length(lgnd_labs_tmp)\n lgnd_labs_tmp = c(lgnd_labs_tmp, rep(\"\", nmore))\n }\n fklgnd.args = modifyList(\n fklgnd.args,\n list(legend = lgnd_labs_tmp),\n keep.null = TRUE\n )\n if (outer_end) fklgnd.args = modifyList(fklgnd.args, list(title = NULL), keep.null = TRUE)\n }\n \n if (draw) {\n fklgnd = do.call(\"legend\", fklgnd.args)\n } else {\n plot.new()\n fklgnd = do.call(\"legend\", fklgnd.args)\n return(fklgnd)\n }\n \n #\n ## Step 2: Calculate legend inset (for outer placement in plot region)\n \n # calculate outer margin width in lines\n soma = 0\n if (outer_side) {\n soma = grconvertX(fklgnd$rect$w, to=\"lines\") - grconvertX(0, to=\"lines\")\n } else if (outer_end) {\n soma = grconvertY(fklgnd$rect$h, to=\"lines\") - grconvertY(0, to=\"lines\")\n }\n # Add legend margins to the outer margin\n soma = soma + sum(lmar)\n \n ## differing outer margin adjustments depending on side\n if (outer_side) {\n if (outer_right) {\n ooma[4] = soma\n } else {\n ooma[2] = soma\n }\n } else if (outer_end) {\n if (outer_bottom) {\n ooma[1] = soma\n } else {\n omar[3] = omar[3] + soma - topmar_epsilon\n par(mar = omar)\n }\n }\n par(oma = ooma)\n \n # determine legend inset\n inset = 0\n if (outer_side) {\n inset = grconvertX(lmar[1], from=\"lines\", to=\"npc\") - grconvertX(0, from = \"lines\", to = \"npc\")\n # extra space needed for \"left!\" b/c of lhs inner margin\n if (!outer_right) {\n inset_bump = grconvertX(par(\"mar\")[2], from = \"lines\", to = \"npc\") - grconvertX(0, from = \"lines\", to = \"npc\")\n inset = inset + inset_bump\n }\n inset = c(1+inset, 0)\n } else if (outer_end) {\n inset = grconvertY(lmar[1], from=\"lines\", to=\"npc\") - grconvertY(0, from=\"lines\", to=\"npc\")\n if (outer_bottom) {\n # extra space needed for \"bottom!\" b/c of lhs inner margin\n inset_bump = grconvertY(par(\"mar\")[1], from=\"lines\", to=\"npc\") - grconvertY(0, from=\"lines\", to=\"npc\")\n inset = inset + inset_bump\n } else {\n epsilon_bump = grconvertY(topmar_epsilon, from=\"lines\", to=\"npc\") - grconvertY(0, from=\"lines\", to=\"npc\")\n inset = inset + epsilon_bump\n }\n inset = c(0, 1+inset)\n }\n \n # GM: The legend inset spacing only works _exactly_ if we refresh the plot\n # area. I'm not sure why (and it works properly if we use the same\n # parameters manually while debugging), but this hack seems to work.\n ## v0.3.0 update: Using (temporary) hook instead of direct par(new = TRUE)\n ## assignment to play nice with tinytheme logic.\n oldhook = getHook(\"before.plot.new\")\n setHook(\"before.plot.new\", function() par(new = TRUE), action = \"append\")\n setHook(\"before.plot.new\", function() par(mar = omar), action = \"append\")\n plot.new()\n setHook(\"before.plot.new\", oldhook, action = \"replace\")\n \n # Finally, set the inset as part of the legend args.\n legend_args[[\"inset\"]] = inset\n \n #\n ## Step 3: Draw the legend\n\n if (gradient) {\n if (!more_than_n_unique(legend_args[[\"col\"]], 1)) {\n if (!is.null(legend_args[[\"pt.bg\"]]) && length(legend_args[[\"pt.bg\"]])==100) {\n legend_args[[\"col\"]] = legend_args[[\"pt.bg\"]]\n }\n }\n gradient_legend(\n legend_args = legend_args,\n fklgnd = fklgnd,\n lmar = lmar,\n outer_side = outer_side,\n outer_end = outer_end,\n outer_right = outer_right,\n outer_bottom = outer_bottom\n )\n } else {\n do.call(\"legend\", legend_args)\n }\n \n}\n\n\n# gradient legend ----\n\n# For gradient (i.e., continuous color) legends, we'll role our own bespoke\n# legend function based on grDevices::as.raster\n\ngradient_legend = function(legend_args, fklgnd, lmar, outer_side, outer_end, outer_right, outer_bottom) {\n pal = legend_args[[\"col\"]]\n lgnd_labs = legend_args[[\"legend\"]]\n if (!is.null(legend_args[[\"horiz\"]])) horiz = legend_args[[\"horiz\"]] else horiz = FALSE\n if (isTRUE(horiz)) {\n rasterlgd = as.raster(matrix(pal, nrow = 1))\n } else {\n rasterlgd = as.raster(matrix(rev(pal), ncol = 1))\n }\n \n corners = par(\"usr\")\n rasterbox = rep(NA_real_, 4)\n \n inner = !any(c(outer_side, outer_end))\n inner_right = inner_bottom = FALSE\n if (inner) {\n if (!is.null(legend_args[[\"x\"]]) && grepl(\"left$|right$\", legend_args[[\"x\"]])) {\n inner_right = grepl(\"right$\", legend_args[[\"x\"]])\n }\n if (!is.null(legend_args[[\"x\"]]) && grepl(\"^bottoml|^top\", legend_args[[\"x\"]])) {\n inner_bottom = grepl(\"^bottom\", legend_args[[\"x\"]])\n }\n }\n \n if (inner) {\n \n fklgnd$rect$h = fklgnd$rect$h - (grconvertY(1.5 + 0.4, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\"))\n \n rasterbox[1] = fklgnd$rect$left\n if (isFALSE(inner_right)) rasterbox[1] = rasterbox[1] + (grconvertX(0.2, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\"))\n rasterbox[2] = fklgnd$rect$top - fklgnd$rect$h - (grconvertY(1.5 + 0.2, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\"))\n rasterbox[3] = rasterbox[1] + (grconvertX(1.25, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\"))\n rasterbox[4] = rasterbox[2] + fklgnd$rect$h\n \n } else if (outer_side) {\n \n rb1_adj = grconvertX(lmar[1] + 0.2, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\")\n rb3_adj = grconvertX(1.25, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\")\n rb2_adj = (corners[4] - corners[3] - (grconvertY(5+1 + 2.5, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\"))) / 2\n # override if top or bottom\n if (!is.null(legend_args[[\"x\"]])) {\n if (grepl(\"^bottom\", legend_args[[\"x\"]])) {\n rb2_adj = corners[3]\n }\n if (grepl(\"^top\", legend_args[[\"x\"]])) {\n rb2_adj = corners[4] - (grconvertY(5+1 + 2.5, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\"))\n }\n }\n rb4_adj = grconvertY(5+1, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n \n if (outer_right) {\n rasterbox[1] = corners[2] + rb1_adj\n rasterbox[2] = rb2_adj \n rasterbox[3] = rasterbox[1] + rb3_adj\n rasterbox[4] = rasterbox[2] + rb4_adj\n } else {\n rb1_adj = rb1_adj + grconvertX(par(\"mar\")[2] + 1, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\")\n rasterbox[1] = corners[1] - rb1_adj\n rasterbox[2] = rb2_adj \n rasterbox[3] = rasterbox[1] - rb3_adj\n rasterbox[4] = rasterbox[2] + rb4_adj\n }\n \n } else if (outer_end) {\n \n rb1_adj = (corners[2] - corners[1] - (grconvertX(5+1, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\"))) / 2\n rb3_adj = grconvertX(5+1, from=\"lines\", to=\"user\") - grconvertX(0, from=\"lines\", to=\"user\")\n rb2_adj = grconvertY(lmar[1], from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n rb4_adj = grconvertY(1.25, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n \n if (outer_bottom) {\n rb2_adj = rb2_adj + grconvertY(par(\"mar\")[2], from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n rasterbox[1] = rb1_adj\n rasterbox[2] = corners[3] - rb2_adj \n rasterbox[3] = rasterbox[1] + rb3_adj\n rasterbox[4] = rasterbox[2] - rb4_adj\n } else {\n rb2_adj = rb2_adj + grconvertY(1.25 + 1, from=\"lines\", to=\"user\") - grconvertY(0, from=\"lines\", to=\"user\")\n rasterbox[1] = rb1_adj\n rasterbox[2] = corners[4] + rb2_adj \n rasterbox[3] = rasterbox[1] + rb3_adj\n rasterbox[4] = rasterbox[2] - rb4_adj\n }\n \n }\n \n #\n ## Draw the gradient swatch\n \n rasterImage(\n rasterlgd,\n rasterbox[1], #x1\n rasterbox[2], #y1\n rasterbox[3], #x2\n rasterbox[4], #y2\n xpd = NA\n ) \n \n #\n ## Add the labels, tick marks, and title \n \n if (isFALSE(horiz)) {\n labs_idx = !is.na(lgnd_labs)\n lgnd_labs[labs_idx] = paste0(\" \", format(lgnd_labs[labs_idx]))\n lbl_x_anchor = rasterbox[3]\n ttl_x_anchor = rasterbox[1]\n lbl_adj = c(0, 0.5)\n tck_adj = c(1, 0.5)\n ttl_adj = c(0, 0)\n if (!inner && !outer_right) {\n lbl_x_anchor = rasterbox[1]\n ttl_x_anchor = ttl_x_anchor + max(strwidth(lgnd_labs[labs_idx]))\n ttl_adj = c(1, 0)\n }\n text(\n x = lbl_x_anchor,\n y = seq(rasterbox[2], rasterbox[4], length.out = length(lgnd_labs)),\n labels = lgnd_labs,\n xpd = NA, \n adj = lbl_adj\n )\n # legend tick marks\n lgnd_ticks = lgnd_labs\n lgnd_ticks[labs_idx] = \"- -\"\n text(\n x = lbl_x_anchor,\n y = seq(rasterbox[2], rasterbox[4], length.out = length(lgnd_labs)),\n labels = lgnd_ticks, col = \"white\",\n xpd = NA, adj = tck_adj\n )\n # legend title\n text(\n x = ttl_x_anchor,\n y = rasterbox[4] + grconvertY(1, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\"),\n labels = legend_args[[\"title\"]],\n xpd = NA, adj = ttl_adj\n )\n } else {\n lbl_y_anchor = rasterbox[4]\n ttl_y_anchor = rasterbox[4]\n lbl_adj = c(0.5, 1.25)\n tck_adj = c(0, 0.5)\n ttl_adj = c(1, -0.5)\n # legend labs\n text(\n x = seq(rasterbox[1], rasterbox[3], length.out = length(lgnd_labs)),\n y = lbl_y_anchor,\n labels = lgnd_labs,\n xpd = NA, adj = lbl_adj\n )\n # legend tick marks\n lgnd_ticks = lgnd_labs\n lgnd_ticks[!is.na(lgnd_ticks)] = \"- -\"\n text(\n x = seq(rasterbox[1], rasterbox[3], length.out = length(lgnd_labs)),\n y = lbl_y_anchor,\n labels = lgnd_ticks, col = \"white\",\n xpd = NA, adj = tck_adj, srt = 90\n )\n # legend title\n text(\n x = rasterbox[1],\n y = ttl_y_anchor,\n labels = paste0(legend_args[[\"title\"]], \" \"),\n xpd = NA, adj = ttl_adj\n )\n }\n}\n\n\n"], ["/tinyplot/R/facet.R", "#' Draw facet windows\n#' \n#' @description Internal functions called from `tinyplot` in order to draw the\n#' plot window with different facets, grids, axes, etc. \n#' \n#' `facet_layout` determines the layout of the facets, based on a set of inputs.\n#' \n#' `draw_facet_window` is the main workhorse function for setting the exterior\n#' plot elements as part of a `tinyplot` call, including adjustment of margins\n#' for dynamic themes, etc.\n#' \n#' @keywords internal\n#' @rdname facet\ndraw_facet_window = function(\n # add arg first, since that determines what happens (if at all)\n add,\n # facet-specific args\n cex_fct_adj,\n facet.args,\n facet_newlines, facet_font, facet_rect, facet_text,\n facet_col, facet_bg, facet_border,\n facet, facets, ifacet,\n nfacets, nfacet_cols, nfacet_rows,\n # axes args\n axes, flip, frame.plot, oxaxis, oyaxis,\n xlabs, xlim, xlim_user, xaxt, xaxs, xaxb, xaxl,\n ylabs, ylim, ylim_user, yaxt, yaxs, yaxb, yaxl,\n asp, log,\n # other args (in approx. alphabetical + group ordering)\n dots,\n draw,\n grid,\n has_legend,\n type,\n x, xmax, xmin,\n y, ymax, ymin\n ) {\n \n # if add is TRUE, just return inputs without any calculations\n if (isTRUE(add)) {\n return(as.list(environment()))\n }\n \n # if breaks are provided use these (but only if x/ylabs are null)\n if (!is.null(xaxb) && !is.null(xlabs)) xlabs = xaxb\n if (!is.null(yaxb) && !is.null(ylabs)) ylabs = yaxb\n \n # draw background color only in the grid rectangle\n grid.bg = get_tpar(\"grid.bg\")\n if (!is.null(grid.bg)) {\n corners = par(\"usr\")\n rect(corners[1], corners[3], corners[2], corners[4], col = grid.bg, border = NA)\n }\n\n ## dynamic margins flag\n dynmar = isTRUE(.tpar[[\"dynmar\"]])\n \n ## optionally allow to modify the style of axis interval calculation\n if (!is.null(xaxs)) par(xaxs = xaxs)\n if (!is.null(yaxs)) par(yaxs = yaxs)\n\n if (nfacets > 1) {\n # Set facet margins (i.e., gaps between facets)\n if (is.null(facet.args[[\"fmar\"]])) {\n fmar = tpar(\"fmar\")\n } else {\n if (length(facet.args[[\"fmar\"]]) != 4) {\n warning(\n \"`fmar` has to be a vector of length four, e.g.\",\n \"`facet.args = list(fmar = c(b,l,t,r))`.\",\n \"\\n\",\n \"Resetting to fmar = c(1,1,1,1) default.\",\n \"\\n\"\n )\n fmar = tpar(\"fmar\")\n } else {\n fmar = facet.args[[\"fmar\"]]\n }\n }\n # We need to adjust for n>=3 facet cases for correct spacing...\n if (nfacets >= 3) {\n ## ... exception for 2x2 cases\n if (!(nfacet_rows == 2 && nfacet_cols == 2)) fmar = fmar * .75\n }\n # Extra reduction if no plot frame to reduce whitespace\n if (isFALSE(frame.plot) && !isTRUE(facet.args[[\"free\"]])) {\n fmar = fmar - 0.5\n }\n\n ooma = par(\"oma\")\n\n # Bump top margin down for facet titles\n fmar[3] = fmar[3] + 1\n if (isTRUE(attr(facet, \"facet_grid\"))) {\n fmar[3] = max(0, fmar[3] - 1)\n # Indent for RHS facet_grid title strip if \"right!\" legend\n if (has_legend && ooma[4] > 0) ooma[4] = ooma[4] + 1\n }\n fmar[3] = fmar[3] + facet_newlines * facet_text / cex_fct_adj\n\n omar = par(\"mar\")\n \n ## Dynamic plot margin adjustments\n if (dynmar) {\n if (par(\"las\") %in% 1:2) {\n # extra whitespace bump on the y axis\n ## overrides for ridge and some types that use integer spacing with (named) axis labels ## FXIME\n if (type == \"ridge\") {\n yaxlabs = levels(y)\n } else if (!is.null(ylabs)) {\n yaxlabs = if (!is.null(names(ylabs))) names(ylabs) else ylabs \n } else if (type == \"boxplot\" && isTRUE(flip) && !is.null(xlabs)) {\n yaxlabs = if (!is.null(names(xlabs))) names(xlabs) else xlabs \n } else {\n # yaxl = axTicks(2)\n yaxlabs = axisTicks(usr = extendrange(ylim, f = 0.04), log = par(\"ylog\"))\n }\n if (!is.null(yaxl)) yaxlabs = tinylabel(yaxlabs, yaxl)\n # whtsbp = grconvertX(max(strwidth(yaxl, \"figure\")), from = \"nfc\", to = \"lines\") - 1\n whtsbp = grconvertX(max(strwidth(yaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - grconvertX(0, from = \"nfc\", to = \"lines\") - 1\n if (whtsbp > 0) {\n omar = omar + c(0, whtsbp, 0, 0) * cex_fct_adj\n fmar[2] = fmar[2] + whtsbp * cex_fct_adj\n }\n # Extra reduction if no plot frame to reduce whitespace\n if (isFALSE(frame.plot) && !isTRUE(facet.args[[\"free\"]])) {\n fmar[2] = fmar[2] - (whtsbp * cex_fct_adj)\n }\n }\n if (par(\"las\") %in% 2:3) {\n # extra whitespace bump on the x axis\n # xaxlabs = axTicks(1)\n xaxlabs = if (is.null(xlabs)) axisTicks(usr = extendrange(xlim, f = 0.04), log = par(\"xlog\")) else \n if (!is.null(names(xlabs))) names(xlabs) else xlabs\n if (!is.null(xaxl)) xaxlabs = tinylabel(xaxlabs, xaxl)\n whtsbp = grconvertX(max(strwidth(xaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - 1\n if (whtsbp > 0) {\n omar = omar + c(whtsbp, 0, 0, 0) * cex_fct_adj\n fmar[1] = fmar[1] + whtsbp * cex_fct_adj\n }\n # Extra reduction if no plot frame to reduce whitespace\n if (isFALSE(frame.plot) && !isTRUE(facet.args[[\"free\"]])) {\n fmar[1] = fmar[1] - (whtsbp * cex_fct_adj)\n }\n }\n # FIXME: Is this causing issues for lhs legends with facet_grid?\n # catch for missing rhs legend\n if (isTRUE(attr(facet, \"facet_grid\")) && !has_legend) {\n omar[4] = omar[4] + 1\n }\n }\n\n # Now we set the margins. The trick here is that we simultaneously adjust\n # inner (mar) and outer (oma) margins by the same amount, but in opposite\n # directions, to preserve the overall facet and plot centroids.\n nmar = (fmar + .1) / cex_fct_adj\n noma = (ooma + omar - fmar - .1) / cex_fct_adj\n # Catch in case of negative oma values. (Probably only occurs with some\n # user-supplied tpar(lmar) values and a \"left!\" positioned legend.)\n if (any(noma < 0)) {\n noma_orig = noma\n noma[noma < 0] = 0\n # noma_diff = noma-noma_orig\n # nmar = nmar + noma_diff\n }\n # apply changes\n par(oma = noma)\n par(mar = nmar)\n\n # Now that the margins have been set, arrange facet rows and columns based\n # on our earlier calculations.\n par(mfrow = c(nfacet_rows, nfacet_cols))\n } else if (dynmar) {\n # Dynamic plot margin adjustments\n omar = par(\"mar\")\n omar = omar - c(0, 0, 1, 0) # reduce top whitespace since no facet (title)\n if (type == \"spineplot\") omar[4] = 2.1 # FIXME catch for spineplot RHS axis labs\n if (par(\"las\") %in% 1:2) {\n # extra whitespace bump on the y axis\n ## overrides for ridge and some types that use integer spacing with (named) axis labels ## FXIME\n if (type == \"ridge\") {\n yaxlabs = levels(y)\n } else if (!is.null(ylabs)) {\n yaxlabs = if (!is.null(names(ylabs))) names(ylabs) else ylabs \n } else if (type == \"boxplot\" && isTRUE(flip) && !is.null(xlabs)) {\n yaxlabs = if (!is.null(names(xlabs))) names(xlabs) else xlabs \n } else {\n # yaxl = axTicks(2)\n yaxlabs = axisTicks(usr = extendrange(ylim, f = 0.04), log = par(\"ylog\"))\n }\n if (!is.null(yaxl)) yaxlabs = tinylabel(yaxlabs, yaxl)\n # whtsbp = grconvertX(max(strwidth(yaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - 1\n whtsbp = grconvertX(max(strwidth(yaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - grconvertX(0, from = \"nfc\", to = \"lines\") - 1\n if (whtsbp > 0) {\n omar[2] = omar[2] + whtsbp\n }\n }\n if (par(\"las\") %in% 2:3) {\n # extra whitespace bump on the x axis\n # xaxl = axTicks(1)\n xaxlabs = if (is.null(xlabs)) axisTicks(usr = extendrange(xlim, f = 0.04), log = par(\"xlog\")) else \n if (!is.null(names(xlabs))) names(xlabs) else xlabs\n if (!is.null(xaxl)) xaxlabs = tinylabel(xaxlabs, xaxl)\n whtsbp = grconvertX(max(strwidth(xaxlabs, \"figure\")), from = \"nfc\", to = \"lines\") - 1\n if (whtsbp > 0) {\n omar[1] = omar[1] + whtsbp\n }\n }\n par(mar = omar)\n }\n\n ## Loop over the individual facet windows and draw the plot region\n ## components (axes, titles, box, grid, etc.)\n for (ii in ifacet) {\n # See: https://github.com/grantmcdermott/tinyplot/issues/65\n if (nfacets > 1) {\n mfgi = ceiling(ii / nfacet_cols)\n mfgj = ii %% nfacet_cols\n if (mfgj == 0) mfgj = nfacet_cols\n par(mfg = c(mfgi, mfgj))\n }\n\n ## Set the plot window\n ## Problem: Passing extra args through ... (e.g., legend_args) to plot.window\n ## triggers an annoying warning about unrecognized graphical params.\n # plot.window(\n # xlim = xlim, ylim = ylim,\n # asp = asp, log = log,\n # # ...\n # )\n ## Solution: Only pass on relevant args using name checking and do.call.\n ## Idea borrowed from here: https://stackoverflow.com/a/4128401/4115816\n pdots = dots[names(dots) %in% names(formals(plot.default))]\n ## catch for flipped boxplots...\n if (type == \"boxplot\" && isTRUE(flip)) {\n log_flip = log\n if (!is.null(log)) {\n if (log == \"x\") log_flip = \"y\"\n if (log == \"y\") log_flip = \"x\"\n }\n do.call(\n \"plot.window\",\n c(list(xlim = ylim, ylim = xlim, asp = asp, log = log_flip), pdots)\n )\n xside = 2\n yside = 1\n } else {\n ## ... standard plot window for all other cases\n do.call(\n \"plot.window\",\n c(list(xlim = xlim, ylim = ylim, asp = asp, log = log), pdots)\n )\n xside = 1\n yside = 2\n }\n\n\n # axes, frame.plot and grid\n if (isTRUE(axes) || isTRUE(facet.args[[\"free\"]])) {\n args_x = list(x,\n side = xside,\n type = xaxt,\n labeller = xaxl,\n cex = get_tpar(c(\"cex.xaxs\", \"cex.axis\"), 0.8),\n lwd = get_tpar(c(\"lwd.xaxs\", \"lwd.axis\"), 1),\n lty = get_tpar(c(\"lty.xaxs\", \"lty.axis\"), 1)\n )\n args_y = list(y,\n side = yside,\n type = yaxt,\n labeller = yaxl,\n cex = get_tpar(c(\"cex.yaxs\", \"cex.axis\"), 0.8),\n lwd = get_tpar(c(\"lwd.yaxs\", \"lwd.axis\"), 1),\n lty = get_tpar(c(\"lty.yaxs\", \"lty.axis\"), 1)\n )\n if (!is.null(xaxb)) args_x$at = xaxb\n if (!is.null(yaxb)) args_y$at = yaxb\n type_range_x = type %in% c(\"barplot\", \"pointrange\", \"errorbar\", \"ribbon\", \"boxplot\", \"p\", \"violin\") && !is.null(xlabs)\n type_range_y = !is.null(ylabs) && (type == \"p\" || (isTRUE(flip) && type %in% c(\"barplot\", \"pointrange\", \"errorbar\", \"ribbon\", \"boxplot\", \"violin\")))\n if (type_range_x) {\n args_x = modifyList(args_x, list(at = xlabs, labels = names(xlabs)))\n }\n if (type_range_y) {\n args_y = modifyList(args_y, list(at = ylabs, labels = names(ylabs)))\n }\n\n if (isTRUE(facet.args[[\"free\"]]) && (par(\"xlog\") || par(\"ylog\"))) {\n warning(\n \"\\nFree scale axes for faceted plots are currently not supported if the axes are logged. Reverting back to fixed scales.\",\n \"\\nIf support for this feature is important to you, please raise an issue on our GitHub repo:\",\n \"\\nhttps://github.com/grantmcdermott/tinyplot/issues\\n\"\n )\n facet.args[[\"free\"]] = FALSE\n }\n\n # Special logic if facets are free...\n if (isTRUE(facet.args[[\"free\"]])) {\n # First, we need to calculate the plot extent and axes range of each\n # individual facet.\n xfree = split(c(x, xmin, xmax), facet)[[ii]]\n yfree = split(c(y, ymin, ymax), facet)[[ii]]\n if (!xlim_user) xlim = range(xfree, na.rm = TRUE)\n if (!ylim_user) ylim = range(yfree, na.rm = TRUE)\n xext = extendrange(xlim, f = 0.04)\n yext = extendrange(ylim, f = 0.04)\n # We'll save this in a special .fusr env var (list) that we'll re-use\n # when it comes to plotting the actual elements later\n if (ii == 1) {\n fusr = replicate(4, vector(\"double\", length = nfacets), simplify = FALSE)\n assign(\".fusr\", fusr, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n }\n fusr = get(\".fusr\", envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n fusr[[ii]] = c(xext, yext)\n assign(\".fusr\", fusr, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n # Explicitly set (override) the current facet extent\n par(usr = fusr[[ii]])\n # if plot frame is true then print axes per normal...\n if (type %in% c(\"barplot\", \"pointrange\", \"errorbar\", \"ribbon\", \"boxplot\", \"p\", \"violin\") && !is.null(xlabs)) {\n tinyAxis(xfree, side = xside, at = xlabs, labels = names(xlabs), type = xaxt, labeller = xaxl)\n } else {\n tinyAxis(xfree, side = xside, type = xaxt, labeller = xaxl)\n }\n if (isTRUE(flip) && type %in% c(\"barplot\", \"pointrange\", \"errorbar\", \"ribbon\", \"boxplot\", \"p\", \"violin\") && !is.null(ylabs)) {\n tinyAxis(yfree, side = yside, at = ylabs, labels = names(ylabs), type = yaxt, labeller = yaxl)\n } else {\n tinyAxis(yfree, side = yside, type = yaxt, labeller = yaxl)\n }\n\n # For fixed facets we can just reuse the same plot extent and axes limits\n } else if (isTRUE(frame.plot)) {\n # if plot frame is true then print axes per normal...\n do.call(tinyAxis, args_x)\n do.call(tinyAxis, args_y)\n } else {\n # ... else only print the \"outside\" axes.\n if (ii %in% oxaxis) do.call(tinyAxis, args_x)\n if (ii %in% oyaxis) do.call(tinyAxis, args_y)\n }\n }\n\n # facet titles\n ## Note: facet titles could be done more simply with mtext... but then we\n ## couldn't adjust background features (e.g., fill), or rotate the rhs\n ## facet grid text. So we're rolling our own \"manual\" versions with text\n ## and rect.\n if (!is.null(facet)) {\n # Get the four corners of plot area (x1, x2, y1, y2)\n corners = par(\"usr\")\n # catch for logged axes\n xlog = isTRUE(par(\"xlog\"))\n ylog = isTRUE(par(\"ylog\"))\n if (xlog) corners[1:2] = 10^(corners[1:2])\n if (ylog) corners[3:4] = 10^(corners[3:4])\n # special logic for facet grids\n if (is.null(facet_newlines) || facet_newlines == 0) {\n facet_title_lines = 1\n } else {\n facet_title_lines = 1 + facet_newlines\n }\n # different logic for facet grids versus regular facets\n if (isTRUE(attr(facet, \"facet_grid\"))) {\n ## top facet strips\n if (ii %in% 1:nfacet_cols) {\n if (isTRUE(facet_rect)) {\n line_height = (facet_title_lines + .1) * facet_text / cex_fct_adj\n if (ylog) {\n line_height = grconvertY(line_height, from = \"lines\", to = \"user\") / grconvertY(0, from = \"lines\", to = \"user\")\n rect_height = corners[4] * line_height\n } else {\n line_height = grconvertY(line_height, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\")\n rect_height = corners[4] + line_height\n }\n rect(\n corners[1], corners[4], corners[2], rect_height,\n col = facet_bg, border = facet_border,\n xpd = NA\n )\n }\n xpos = if (xlog) 10^(mean(log10(corners[1:2]))) else mean(corners[1:2])\n if (ylog) {\n ypos = grconvertY(0.4, from = \"lines\", to = \"user\") / grconvertY(0, from = \"lines\", to = \"user\")\n ypos = corners[4] * ypos\n } else {\n ypos = grconvertY(0.4, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\")\n ypos = corners[4] + ypos\n }\n text(\n x = xpos,\n y = ypos,\n labels = sub(\"^(.*?)~.*\", \"\\\\1\", facets[[ii]]),\n adj = c(0.5, 0),\n cex = facet_text / cex_fct_adj,\n col = facet_col,\n font = facet_font,\n xpd = NA,\n )\n }\n ## right facet strips\n if (ii %% nfacet_cols == 0 || ii == nfacets) {\n if (isTRUE(facet_rect)) {\n line_height = (facet_title_lines + .1) * facet_text / cex_fct_adj\n if (xlog) {\n line_height = grconvertX(line_height, from = \"lines\", to = \"user\") / grconvertX(0, from = \"lines\", to = \"user\")\n rect_width = corners[2] * line_height\n } else {\n line_height = grconvertX(line_height, from = \"lines\", to = \"user\") - grconvertX(0, from = \"lines\", to = \"user\")\n rect_width = corners[2] + line_height\n }\n rect(\n corners[2], corners[3], rect_width, corners[4],\n col = facet_bg, border = facet_border,\n xpd = NA\n )\n }\n if (xlog) {\n xpos = grconvertX(0.4, from = \"lines\", to = \"user\") / grconvertX(0, from = \"lines\", to = \"user\")\n xpos = corners[2] * xpos\n } else {\n xpos = grconvertX(0.4, from = \"lines\", to = \"user\") - grconvertX(0, from = \"lines\", to = \"user\")\n xpos = corners[2] + xpos\n }\n ypos = if (ylog) 10^(mean(log10(corners[3:4]))) else mean(corners[3:4])\n text(\n x = xpos,\n y = ypos,\n labels = sub(\"^.*?~(.*)\", \"\\\\1\", facets[[ii]]),\n srt = 270,\n adj = c(0.5, 0),\n cex = facet_text / cex_fct_adj,\n col = facet_col,\n font = facet_font,\n xpd = NA\n )\n }\n } else {\n if (isTRUE(facet_rect)) {\n line_height = (facet_title_lines + .1) * facet_text / cex_fct_adj\n if (ylog) {\n line_height = grconvertY(line_height, from = \"lines\", to = \"user\") / grconvertY(0, from = \"lines\", to = \"user\")\n rect_height = corners[4] * line_height\n } else {\n line_height = grconvertY(line_height, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\")\n rect_height = corners[4] + line_height\n }\n rect(\n corners[1], corners[4], corners[2], rect_height,\n col = facet_bg, border = facet_border,\n xpd = NA\n )\n }\n xpos = if (xlog) 10^(mean(log10(corners[1:2]))) else mean(corners[1:2])\n if (ylog) {\n ypos = grconvertY(0.4, from = \"lines\", to = \"user\") / grconvertY(0, from = \"lines\", to = \"user\")\n ypos = corners[4] * ypos\n } else {\n ypos = grconvertY(0.4, from = \"lines\", to = \"user\") - grconvertY(0, from = \"lines\", to = \"user\")\n ypos = corners[4] + ypos\n }\n text(\n x = xpos,\n y = ypos,\n labels = paste(facets[[ii]]),\n adj = c(0.5, 0),\n cex = facet_text / cex_fct_adj,\n col = facet_col,\n font = facet_font,\n xpd = NA\n )\n }\n }\n\n # plot frame\n if (frame.plot) box()\n\n # panel grid lines\n if (is.null(grid)) grid = .tpar[[\"grid\"]]\n if (!is.null(grid)) {\n if (is.logical(grid)) {\n ## If grid is TRUE create a default grid. Rather than just calling the default grid()\n ## abline(... = pretty(extendrange(...)), ...) is used. Reason: pretty() is generic\n ## and works better for axes based on date/time classes. Exception: For axes in logs,\n ## resort to using grid() which is likely better handled there.\n if (isTRUE(grid)) {\n gnx = gny = NULL\n if (!is.null(xaxb)) {\n abline(v = xaxb, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n gnx = NA\n } else if (!any(c(par(\"xlog\"), type == \"boxplot\"))) {\n xg = if (!inherits(x, c(\"POSIXt\", \"Date\"))) axTicks(side = 1) else axTicksDateTime(side = 1, x = x)\n abline(v = xg, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n gnx = NA\n }\n if (!is.null(yaxb)) {\n abline(h = yaxb, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n gny = NA\n } else if (!any(c(par(\"ylog\"), type == \"boxplot\"))) {\n yg = if (!inherits(y, c(\"POSIXt\", \"Date\"))) axTicks(side = 2) else axTicksDateTime(side = 2, x = x)\n abline(h = yg, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n gny = NA\n }\n grid(nx = gnx, ny = gny, col = .tpar[[\"grid.col\"]], lty = .tpar[[\"grid.lty\"]], lwd = .tpar[[\"grid.lwd\"]])\n }\n } else {\n grid\n }\n }\n\n # add any drawn elements\n if (!is.null(draw)) eval(draw)\n } # end of ii facet loop\n\n return(as.list(environment()))\n}\n\n\n#' @rdname facet\n#' @keywords internal\nfacet_layout = function(facet, add = FALSE, facet.args = list()) {\n nfacet_rows = 1\n nfacet_cols = 1\n if (!is.null(facet)) {\n facets = if (is.factor(facet)) levels(facet) else sort(unique(facet))\n ifacet = seq_along(facets)\n nfacets = length(facets)\n if (isTRUE(add)) {\n omfrow = par(\"mfrow\")\n nfacet_rows = omfrow[1]\n nfacet_cols = omfrow[2]\n } else {\n if (isTRUE(attr(facet, \"facet_grid\"))) {\n facet.args[[\"nrow\"]] = attr(facet, \"facet_nrow\")\n }\n if (!is.null(facet.args[[\"nrow\"]])) {\n nfacet_rows = facet.args[[\"nrow\"]]\n nfacet_cols = ceiling(nfacets / nfacet_rows)\n } else if (!is.null(facet.args[[\"ncol\"]])) {\n nfacet_cols = facet.args[[\"ncol\"]]\n nfacet_rows = ceiling(nfacets / nfacet_cols)\n } else {\n if (nfacets > 3) {\n nfacet_cols = ceiling(sqrt(nfacets))\n nfacet_rows = ceiling(nfacets / nfacet_cols)\n } else {\n nfacet_rows = 1L\n nfacet_cols = nfacets\n }\n }\n }\n\n oxaxis = tail(ifacet, nfacet_cols)\n oyaxis = seq(1, nfacets, by = nfacet_cols)\n\n if (nfacet_rows >= 3 || nfacet_cols >= 3) {\n cex_fct_adj = 0.66\n } else if (nfacet_rows == 2 && nfacet_cols == 2) {\n cex_fct_adj = 0.83\n } else {\n cex_fct_adj = 1\n }\n } else {\n facets = ifacet = nfacets = oxaxis = oyaxis = 1\n cex_fct_adj = 1\n }\n\n list(\n facets = facets,\n ifacet = ifacet,\n nfacets = nfacets,\n nfacet_rows = nfacet_rows,\n nfacet_cols = nfacet_cols,\n oxaxis = oxaxis,\n oyaxis = oyaxis,\n cex_fct_adj = cex_fct_adj\n )\n}\n\n\n\n#\n# helper functions\n#\n\n\n# utility function for converting facet formulas into variables\nget_facet_fml = function(formula, data = NULL) {\n xfacet = yfacet = NULL\n\n ## catch one-sided formula ~ x or ~ x | z with no \"y\" variable\n if (!inherits(formula, \"formula\")) formula = as.formula(formula)\n no_yfacet = length(formula) == 2L\n fml_rhs = if (no_yfacet) 2L else 3L\n\n ## set up model frame\n m = match.call(expand.dots = FALSE)\n\n if (!is.null(data)) {\n m = m[c(1L, match(c(\"formula\", \"data\", \"subset\", \"na.action\", \"drop.unused.levels\"), names(m), 0L))]\n }\n\n m$formula = formula\n ## need stats:: for non-standard evaluation\n m[[1L]] = quote(stats::model.frame)\n mf = eval.parent(m)\n\n ## extract variables: x, y (if any)\n if (no_yfacet) {\n yfacet_loc = NULL\n xfacet_loc = 1L\n } else {\n yfacet_loc = 1L\n xfacet_loc = 2L\n }\n if (NCOL(mf) < xfacet_loc) stop(\"formula should specify at least one variable on the right-hand side\")\n yfacet = if (no_yfacet) NULL else mf[, yfacet_loc]\n xfacet = mf[, xfacet_loc:NCOL(mf)]\n\n ## return object\n xfacet = interaction(xfacet, sep = \":\")\n if (no_yfacet) {\n ret = xfacet\n } else {\n # yfacet = interaction(yfacet, sep = \":\")\n ## NOTE: We \"swap\" the formula LHS and RHS since mfrow plots rowwise\n ret = interaction(xfacet, yfacet, sep = \"~\")\n attr(ret, \"facet_grid\") = TRUE\n attr(ret, \"facet_nrow\") = length(unique(yfacet))\n }\n\n return(ret)\n}\n\n\n## internal convenience function to determine whether the current facet panel\n## has the position \"left\", \"right\", \"top\", or \"bottom\" in the facet grid\nis_facet_position = function(position, ifacet, facet_window_args) {\n id = facet_window_args$ifacet\n nc = facet_window_args$nfacet_cols\n ni = tail(id, 1L)\n switch(position,\n \"left\" = ifacet %in% seq(1L, ni, by = nc),\n \"right\" = ifacet %in% pmin(ni, seq(1L, ni, by = nc) + nc - 1L),\n \"top\" = ifacet %in% head(id, nc),\n \"bottom\" = ifacet %in% tail(id, nc),\n NA\n )\n}\n"], ["/tinyplot/R/type_ridge.R", "#' Ridge plot type\n#'\n#' @description Type function for producing ridge plots (also known as joy plots),\n#' which display density distributions for multiple groups with vertical offsets.\n#' This function uses `tinyplot` scaffolding, which enables added functionality\n#' such as grouping and faceting.\n#'\n#' The line color is controlled by the `col` argument in the `tinyplot()` call.\n#' The fill color is controlled by the `bg` argument in the `tinyplot()` call.\n#'\n#' @param scale Numeric. Controls the scaling factor of each plot.\n#' Values greater than 1 means that plots overlap.\n#' @param joint.max character indicating how to scale the maximum of the densities:\n#' The default `\"all\"` indicates that all densities are scaled jointly relative to\n#' the same maximum so that the areas of all densities are comparable.\n#' Alternatively, `\"facet\"` indicates that the maximum is computed within\n#' each facet so that the areas of the densities are comparable within each\n#' facet but not necessarily across facets. Finally, `\"by\"` indicates that\n#' each row (in each facet) is scaled separately, so that the areas of the\n#' densities for `by` groups in the same row are comparable but not necessarily\n#' across rows.\n#' @param breaks Numeric. If a color gradient is used for shading, the\n#' breaks between the colors can be modified. The default is to use\n#' equidistant breaks spanning the range of the `x` variable.\n#' @param probs Numeric. Instead of specifying the same `breaks` on the\n#' x-axis for all groups, it is possible to specify group-specific quantiles\n#' at the specified `probs`. The quantiles are computed based on the density\n#' (rather than the raw original variable). Only one of `breaks` or\n#' `probs` must be specified.\n#' @param ylevels a character or numeric vector specifying in which order\n#' the levels of the y-variable should be plotted.\n#' @inheritParams stats::density\n#' @param kernel a character string giving the smoothing kernel to be used. This\n#' must partially match one of `\"gaussian\"`, `\"rectangular\"`, `\"triangular\"`,\n#' `\"epanechnikov\"`, `\"biweight\"`, `\"cosine\"` or `\"optcosine\"`, with default\n#' `\"gaussian\"`, and may be abbreviated to a unique prefix (single letter).\n#'\n#' `\"cosine\"` is smoother than `\"optcosine\"`, which is the usual 'cosine'\n#' kernel in the literature and almost MSE-efficient. However, `\"cosine\"` is\n#' the version used by S.\n#' @param joint.bw character string indicating whether (and how) the smoothing\n#' bandwidth should be computed from the joint data distribution. The default\n#' of `\"mean\"` will compute the joint bandwidth as the mean of the individual\n#' subgroup bandwidths (weighted by their number of observations). Choosing\n#' `\"full\"` will result in a joint bandwidth computed from the full\n#' distribution (merging all subgroups). For `\"none\"` the individual bandwidth\n#' will be computed independently for each subgroup. Also accepts a logical\n#' argument, where `TRUE` maps to `\"mean\"` and `FALSE` maps to `\"none\"`. See\n#' \\code{\\link{type_density}} for some discussion of practical considerations.\n#' @param gradient Logical or character. Should a gradient fill be used to\n#' shade the area under the density? If a character specification is used,\n#' then it can either be of length 1 and specify the palette to be used with\n#' `gradient = TRUE` corresponding to `gradient = \"viridis\"`. If a character\n#' vector of length greater than 1 is used, then it should specify the\n#' colors in the palette, e.g., `gradient = hcl.colors(512)`.\n#' @param raster Logical. Should the `gradient` fill be drawn using\n#' \\code{\\link[graphics]{rasterImage}}? Defaults to `FALSE`, in which case the\n#' `gradient` fill will instead be drawn using\n#' \\code{\\link[graphics]{polygon}}. See the `Technical note on gradient fills`\n#' section below.\n#' @param col Character string denoting the outline (border) color for all\n#' of the ridge densities. Note that a singular value is expected; if multiple\n#' colors are provided then only the first will be used. This argument is mostly\n#' useful for the aesthetic effect of drawing a common outline color in\n#' combination with gradient fills. See Examples.\n#' @param alpha Numeric in the range `[0,1]` for adjusting the alpha\n#' transparency of the density fills. In most cases, will default to a value of\n#' 1, i.e. fully opaque. But for some `by` grouped plots (excepting the special\n#' cases where `by==y` or `by==x`), will default to 0.6.\n#' \n#' @section Technical note on gradient fills:\n#' \n#' `tinyplot` uses two basic approaches for drawing gradient fills in ridge line\n#' plots, e.g., if `type_ridge(gradient = TRUE)`.\n#' \n#' The first (and default) polygon-based approach involves dividing up the main\n#' density region into many smaller polygons along the x-axis. Each of these\n#' smaller polygons inherits a different color \"segment\" from the underlying\n#' palette swatch, which in turn creates the effect of a continuous gradient\n#' when they are all plotted together. Internally, this polygon-based approach\n#' is vectorized (i.e., all of the sub-polygons are plotted simultaneously). It\n#' is thus efficient from a plotting perspective and generally also performs\n#' well from an aesthetic perspective. However, it can occasionally produce\n#' undesirable plotting artifacts on some graphics devices---e.g., thin but\n#' visible vertical lines---if alpha transparency is being used at the same \n#' time.\n#' \n#' For this reason, we also offer an alternative raster-based approach for\n#' gradient fills that users can invoke via\n#' `type_ridge(gradient = TRUE, raster = TRUE)`. The essential idea is that we\n#' coerce the density polygon into a raster representation (using\n#' \\code{\\link[graphics]{rasterImage}}) and achieve the gradient effect via\n#' color interpolation. The trade-off this time is potential smoothness\n#' artifacts around the top of the ridge densities at high resolutions, since we\n#' have converted a vector object into a raster object.\n#' \n#' Again, we expect that the choice between these two approaches will only\n#' matter for ridge plots that combine gradient fills with alpha transparency\n#' (and on certain graphics devices). We recommend that users experiment to\n#' determine which approach is optimal for their device.\n#'\n#' @examples\n#' aq = transform(\n#' airquality,\n#' Month = factor(month.abb[Month], levels = month.abb[5:9]),\n#' Month2 = factor(month.name[Month], levels = month.name[5:9]),\n#' Late = ifelse(Day > 15, \"Late\", \"Early\")\n#' )\n#' \n#' # default ridge plot (using the \"ridge\" convenience string)\n#' tinyplot(Month ~ Temp, data = aq, type = \"ridge\")\n#' \n#' # for ridge plots, we recommend pairing with the dedicated theme(s), which\n#' # facilitate nicer y-axis labels, grid lines, etc.\n#' \n#' tinytheme(\"ridge\")\n#' tinyplot(Month ~ Temp, data = aq, type = \"ridge\")\n#' \n#' tinytheme(\"ridge2\") # removes the plot frame (but keeps x-axis line)\n#' tinyplot(Month ~ Temp, data = aq, type = \"ridge\")\n#' \n#' # the \"ridge(2)\" themes are especially helpful for long y labels, due to\n#' # dyanmic plot adjustment\n#' tinyplot(Month2 ~ Temp, data = aq, type = \"ridge\")\n#' \n#' # pass customization arguments through type_ridge()... for example, use\n#' # the scale argument to change/avoid overlap of densities (more on scaling\n#' # further below)\n#' \n#' tinyplot(Month ~ Temp, data = aq, type = type_ridge(scale = 1))\n#' \n#' ## by grouping is also supported. two special cases of interest:\n#'\n#' # 1) by == y (color by y groups)\n#' tinyplot(Month ~ Temp | Month, data = aq, type = \"ridge\")\n#'\n#' # 2) by == x (gradient coloring along x)\n#' tinyplot(Month ~ Temp | Temp, data = aq, type = \"ridge\")\n#'\n#' # aside: pass explicit `type_ridge(col = )` arg to set a different\n#' # border color\n#' tinyplot(Month ~ Temp | Temp, data = aq, type = type_ridge(col = \"white\"))\n#'\n#' # gradient coloring along the x-axis can also be invoked manually without\n#' # a legend (the next two tinyplot calls are equivalent)\n#' \n#' # tinyplot(Month ~ Temp, data = aq, type = type_ridge(gradient = \"agsunset\"))\n#' tinyplot(Month ~ Temp, data = aq, type = type_ridge(gradient = TRUE))\n#' \n#' # aside: when combining gradient fill with alpha transparency, it may be\n#' # better to use the raster-based approach (test on your graphics device)\n#' \n#' tinyplot(Month ~ Temp, data = aq,\n#' type = type_ridge(gradient = TRUE, alpha = 0.5),\n#' main = \"polygon fill (default)\")\n#' tinyplot(Month ~ Temp, data = aq,\n#' type = type_ridge(gradient = TRUE, alpha = 0.5, raster = TRUE),\n#' main = \"raster fill\")\n#'\n#' # highlighting only the center 50% of the density (i.e., 25%-75% quantiles)\n#' tinyplot(Month ~ Temp, data = aq, type = type_ridge(\n#' gradient = hcl.colors(3, \"Dark Mint\")[c(2, 1, 2)],\n#' probs = c(0.25, 0.75), col = \"white\"))\n#'\n#' # highlighting the probability distribution by color gradient\n#' # (darkest point = median)\n#' tinyplot(Month ~ Temp, data = aq, type = type_ridge(\n#' gradient = hcl.colors(250, \"Dark Mint\")[c(250:1, 1:250)],\n#' probs = 0:500/500))\n#'\n#' # faceting also works, although we recommend switching (back) to the \"ridge\"\n#' # theme for faceted ridge plots\n#' \n#' tinytheme(\"ridge\")\n#' tinyplot(Month ~ Ozone, facet = ~ Late, data = aq,\n#' type = type_ridge(gradient = TRUE))\n#' \n#' ## use the joint.max argument to vary the maximum density used for\n#' ## determining relative scaling...\n#' \n#' # jointly across all densities (default) vs. per facet\n#' tinyplot(Month ~ Temp, facet = ~ Late, data = aq,\n#' type = type_ridge(scale = 1))\n#' tinyplot(Month ~ Temp, facet = ~ Late, data = aq,\n#' type = type_ridge(scale = 1, joint.max = \"facet\"))\n#' \n#' # jointly across all densities (default) vs. per by row\n#' tinyplot(Month ~ Temp | Late, data = aq,\n#' type = type_ridge(scale = 1))\n#' tinyplot(Month ~ Temp | Late, data = aq,\n#' type = type_ridge(scale = 1, joint.max = \"by\"))\n#' \n#' # restore the default theme\n#' tinytheme()\n#'\n#' @export\ntype_ridge = function(\n scale = 1.5,\n joint.max = c(\"all\", \"facet\", \"by\"),\n breaks = NULL,\n probs = NULL,\n ylevels = NULL,\n bw = \"nrd0\",\n joint.bw = c(\"mean\", \"full\", \"none\"),\n adjust = 1,\n kernel = c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"),\n n = 512,\n # more args from density here?\n gradient = FALSE,\n raster = FALSE,\n col = NULL,\n alpha = NULL\n ) {\n \n kernel = match.arg(kernel, c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"))\n if (is.logical(joint.bw)) {\n joint.bw = ifelse(joint.bw, \"mean\", \"none\")\n }\n joint.bw = match.arg(joint.bw, c(\"mean\", \"full\", \"none\"))\n\n out = list(\n draw = draw_ridge(),\n data = data_ridge(bw = bw, adjust = adjust, kernel = kernel, n = n,\n joint.bw = joint.bw,\n scale = scale,\n joint.max = joint.max,\n gradient = gradient,\n breaks = breaks,\n probs = probs,\n ylevels = ylevels,\n raster = raster,\n col = col,\n alpha = alpha\n ),\n name = \"ridge\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n#\n## Underlying data_ridge function\ndata_ridge = function(bw = \"nrd0\", adjust = 1, kernel = \"gaussian\", n = 512,\n joint.bw = \"mean\",\n scale = 1.5,\n joint.max = \"all\",\n gradient = FALSE,\n breaks = NULL,\n probs = NULL,\n ylevels = NULL,\n raster = FALSE,\n col = NULL,\n alpha = NULL\n ) {\n fun = function(datapoints, yaxt = NULL, null_by, ...) {\n # catch for special cases\n anyby = !null_by\n x_by = anyby && identical(datapoints$x, datapoints$by)\n y_by = anyby && identical(datapoints$y, datapoints$by)\n if (x_by) {\n gradient = TRUE\n datapoints$by = \"\"\n } else if (y_by) {\n datapoints$by = \"\"\n } else if (anyby && is.null(alpha)) {\n alpha = 0.6\n }\n # flag for (non-gradient) interior fill adjustment\n fill_by = anyby || y_by\n if (isTRUE(x_by)) fill_by = FALSE\n # if (isTRUE(anyby) && is.null(alpha)) alpha = 0.6\n\n ## reorder levels of y-variable if requested\n if (!is.null(ylevels)) {\n if (!is.factor(datapoints$y)) datapoints$y = factor(datapoints$y)\n datapoints$y = factor(datapoints$y, levels = if(is.numeric(ylevels)) levels(datapoints$y)[ylevels] else ylevels)\n if (y_by) datapoints$by = datapoints$y\n }\n\n ##\n datapoints = split(datapoints, list(datapoints$y, datapoints$by, datapoints$facet))\n\n if (joint.bw == \"none\" || is.numeric(bw)) {\n dens_bw = bw\n } else {\n if (joint.bw == \"mean\") {\n # Use weighted mean of subgroup bandwidths\n bws = sapply(datapoints, function(dat) bw_fun(kernel = bw, dat$x))\n ws = sapply(datapoints, nrow)\n dens_bw = weighted.mean(bws, ws)\n } else if (joint.bw == \"full\") {\n dens_bw = bw_fun(kernel = bw, unlist(sapply(datapoints, `[[`, \"x\")))\n }\n }\n\n datapoints = lapply(datapoints, function(dat) {\n dens = density(dat$x, bw = dens_bw, kernel = kernel, n = n)\n out = data.frame(\n by = dat$by[1], # already split\n facet = dat$facet[1], # already split\n x = dens$x,\n y = dat$y[1],\n ymin = 0L,\n ymax = dens$y\n )\n return(out)\n })\n datapoints = do.call(rbind, datapoints)\n\n if (is.character(joint.max)) {\n joint.max = match.arg(joint.max, c(\"all\", \"facet\", \"by\"))\n joint.max = switch(joint.max,\n \"all\" = rep.int(1, nrow(datapoints)),\n \"facet\" = datapoints$facet,\n \"by\" = interaction(datapoints$facet, datapoints$y)\n )\n joint.max = ave(datapoints$ymax, joint.max, FUN = max)\n }\n datapoints$ymax = datapoints$ymax / joint.max * scale\n\n datapoints = split(datapoints, datapoints$facet)\n offset_z = function(k) {\n ksplit = split(k, k$y)\n for (idx in seq_along(ksplit)) {\n ksplit[[idx]]$ymax = ksplit[[idx]]$ymax + idx - 1\n ksplit[[idx]]$ymin = ksplit[[idx]]$ymin + idx - 1\n }\n k = do.call(rbind, ksplit)\n return(k)\n }\n datapoints = do.call(rbind, lapply(datapoints, offset_z))\n\n if (y_by) {\n datapoints$y = factor(datapoints$y)\n datapoints$by = factor(datapoints$y, levels = rev(levels(datapoints$y)))\n } else if (x_by) {\n datapoints$by = datapoints$x\n }\n\n # Manual breaks flag. Only used if gradient is on\n manbreaks = !is.null(breaks) || !is.null(probs)\n\n ## use color gradient?\n xlim = range(datapoints$x, na.rm = TRUE)\n if (!is.null(probs)) {\n if (!is.null(breaks)) {\n warning(\"only one of 'breaks' and 'quantile' must be specified\")\n probs = NULL\n } else {\n if (probs[1L] > 0) probs = c(0, probs)\n if (probs[length(probs)] < 1) probs = c(probs, 1)\n }\n }\n if (!isFALSE(gradient)) {\n dotspal = list(...)[[\"palette\"]]\n palette = if (!is.null(dotspal)) dotspal else gradient\n gradient = TRUE\n if (isTRUE(palette)) {\n palette = if (!is.null(.tpar[[\"palette.sequential\"]])) .tpar[[\"palette.sequential\"]] else \"viridis\"\n }\n\n if (length(palette) > 1L || !is.character(palette)) {\n ## color vector already given\n if (is.null(breaks) && is.null(probs)) {\n breaks = seq(from = xlim[1L], to = xlim[2L], length.out = length(palette) + 1L)\n } else {\n npal = pmax(length(breaks), length(probs)) - 1L\n if (length(palette) != npal) {\n warning(\"length of 'palette' does not match 'breaks'/'probs'\")\n palette = rep_len(palette, npal)\n }\n if (isTRUE(raster)) raster = npal > 20L\n }\n } else {\n ## only palette name given\n npal = if (is.null(breaks) && is.null(probs)) 512L else pmax(length(breaks), length(probs)) - 1L\n palette = hcl.colors(npal, palette = palette)\n if (is.null(breaks) && is.null(probs)) breaks = seq(from = xlim[1L], to = xlim[2L], length.out = npal + 1L)\n if (isTRUE(raster)) raster = npal > 20L\n }\n } else {\n palette = NULL\n if (!is.null(breaks) || !is.null(probs)) gradient = TRUE\n }\n if (!is.null(breaks)) {\n breaks[1L] = pmin(breaks[1L], xlim[1L])\n breaks[length(breaks)] = pmax(breaks[length(breaks)], xlim[2L])\n }\n \n if (is.null(col) && (!anyby || x_by)) col = \"black\"\n\n out = list(\n datapoints = datapoints,\n yaxt = \"n\",\n ylim = c(min(datapoints$ymin), max(datapoints$ymax)),\n type_info = list(\n gradient = gradient,\n palette = palette,\n breaks = breaks,\n probs = probs,\n manbreaks = manbreaks,\n yaxt = yaxt,\n raster = raster,\n x_by = x_by,\n y_by = y_by,\n fill_by = fill_by,\n col = col,\n alpha = alpha\n )\n )\n return(out)\n }\n return(fun)\n}\n\n\n#\n## Underlying draw_ridge function\ndraw_ridge = function() {\n fun = function(ix, iy, iz, ibg, icol, iymin, iymax, type_info, ...) {\n ridge_theme = identical(.tpar[[\"tinytheme\"]], \"ridge\") || identical(.tpar[[\"tinytheme\"]], \"ridge2\")\n d = data.frame(x = ix, y = iy, ymin = iymin, ymax = iymax)\n dsplit = split(d, d$y)\n if (is.null(ibg)) {\n default_bg = if (!ridge_theme && !is.null(.tpar[[\"palette.qualitative\"]])) seq_palette(by_col(), n = 2)[2] else \"gray\"\n ibg = if (isTRUE(type_info[[\"fill_by\"]])) seq_palette(icol, n = 2)[2] else default_bg\n }\n if (!is.null(type_info[[\"alpha\"]]) && is.null(type_info[[\"palette\"]])) {\n ibg = adjustcolor(ibg, alpha.f = type_info[[\"alpha\"]])\n }\n if (!is.null(type_info[[\"col\"]])) icol = type_info[[\"col\"]]\n lab = if (is.factor(d$y)) levels(d$y) else unique(d$y)\n if (isTRUE(type_info[[\"y_by\"]])) {\n # avoid duplicating the y-axis labs for the special y==by case\n # val = match(lab, levels(d$y)) - 1\n val = match(d$y[1], levels(d$y))\n lab = lab[val]\n val = val - 1\n } else {\n val = cumsum(rep(1, length(lab))) - 1\n }\n if (ridge_theme) abline(h = val, col = .tpar[[\"grid.col\"]])\n draw_segments = if (type_info[[\"raster\"]]) segmented_raster else segmented_polygon\n for (i in rev(seq_along(dsplit))) {\n if (type_info[[\"gradient\"]]) {\n with(\n dsplit[[i]],\n draw_segments(\n x, ymax, ymin = ymin[1L],\n breaks = type_info[[\"breaks\"]],\n probs = type_info[[\"probs\"]],\n manbreaks = type_info[[\"manbreaks\"]],\n col = if (is.null(type_info[[\"palette\"]])) ibg else type_info[[\"palette\"]],\n # border = if (is.null(type_info[[\"palette\"]])) icol else \"transparent\",\n alpha = type_info[[\"alpha\"]]\n )\n )\n }\n with(dsplit[[i]], polygon(x, ymax, col = if (type_info[[\"gradient\"]]) \"transparent\" else ibg, border = NA))\n with(dsplit[[i]], lines(x, ymax, col = icol))\n }\n # tinyAxis(x = d$y, side = 2, at = val, labels = lab, type = type_info[[\"yaxt\"]], padj = padj)\n if (ridge_theme) {\n tinyAxis(x = d$y, side = 2, at = val, labels = lab, type = type_info[[\"yaxt\"]],\n padj = 0,\n mgp = c(3, 1, 0) - c(0.5, 0.5 + 0.3, 0),\n tcl = 0)\n if (identical(.tpar[[\"tinytheme\"]], \"ridge2\")) axis(1, labels = FALSE)\n } else {\n tinyAxis(x = d$y, side = 2, at = val, labels = lab, type = type_info[[\"yaxt\"]])\n }\n }\n return(fun)\n}\n\n\n#\n## Auxiliary functions\n\n## auxiliary function for drawing shaded segmented polygon\nsegmented_polygon = function(x, y, ymin = 0, breaks = range(x), probs = NULL, manbreaks = FALSE, col = \"lightgray\", border = \"transparent\", alpha = NULL) {\n\n if (!is.null(probs)) {\n ## map quantiles to breaks\n if (!(missing(breaks) || is.null(breaks))) stop(\"only one of 'breaks' and 'probs' must be specified\")\n breaks = quantile.density(list(x = x, y = y - ymin), probs = probs)\n }\n\n ## sanity check\n if (breaks[1L] > x[1L] || breaks[length(breaks)] < x[length(x)]) stop(\"'breaks' do no span range of 'x'\")\n\n # ## recycle color (if necessary) rather use colorRampPalette below\n # col = rep_len(col, length(breaks) - 1L)\n \n # Create individual polygons\n if (isFALSE(manbreaks)) {\n # Special case for length(breaks)==length(x). We can take a fully vectorised\n # shortcut\n xx = c(rbind(x[-length(x)], x[-1], x[-1], x[-length(x)], NA))\n yy = c(rbind(y[-length(y)], y[-1], ymin, ymin, NA))\n } else {\n # For other cases, we'll do a bit more work to make sure that the polygons\n # overlap\n bvals = do.call(c, sapply(seq_along(breaks[-1]), function(b) tail(x[x= xrange[1] & breaks < xrange[2])\n idx = c(idx, length(idx)+1)\n col = col[idx]\n col = colorRampPalette(col, alpha = TRUE)(length(x)) # support alpha?\n }\n } else if (isFALSE(manbreaks) || length(col) > length(x) || length(x) %% length(col) != 0) {\n xrange = range(xx, na.rm = TRUE)\n idx = which(breaks >= xrange[1] & breaks < xrange[2])\n idx = c(idx, length(idx)+1)\n col = col[idx]\n col = colorRampPalette(col, alpha = TRUE)(length(x)) # support alpha?\n }\n }\n border = if (is.null(alpha)) col else adjustcolor(col = col, alpha.f = alpha/2)\n \n ## draw all polygons\n polygon(xx, yy, col = col, border = border, lwd = 0.5)\n}\n\n#' @importFrom graphics rasterImage\n#' @importFrom grDevices as.raster\nsegmented_raster = function(x, y, ymin = 0, breaks = range(x), probs = NULL, manbreaks = FALSE, col = \"lightgray\", border = \"transparent\", alpha = NULL) {\n ## set up raster matrix on x-grid and 500 y-pixels \n n = length(x) - 1L\n m = 500L ## FIXME: hard-coded?\n r = matrix(1:n, ncol = n, nrow = m, byrow = TRUE)\n\n ## map quantiles to breaks\n if (!is.null(probs)) {\n if (!(missing(breaks) || is.null(breaks))) stop(\"only one of 'breaks' and 'probs' must be specified\")\n breaks = quantile.density(list(x = x, y = y - ymin), probs = probs)\n }\n\n if (!is.null(alpha)) col = adjustcolor(col, alpha.f = alpha)\n col = rev(col) ## uncomment to make extreme cols dark\n ## map colors to intervals and fill colors by column\n col = col[cut(x, breaks = breaks, include.lowest = TRUE)]\n r[] = col[r]\n\n ## clip raster pixels above density line\n ymax = max(y)\n ix = cbind(as.vector(row(r)), as.vector(col(r)))\n ix = ix[seq(from = ymax, to = ymin, length.out = m)[row(r)] > y[col(r)], , drop = FALSE]\n r[ix] = NA\n\n ## plot density and add raster gradient\n rasterImage(as.raster(r), min(x), ymin, max(x), ymax, interpolate = length(breaks) >= 20L) ## FIXME: improve quality for \"few\" breaks?\n}\n\n## auxiliary function for determining quantiles based on density function\n\n#' @importFrom stats median approx\nquantile.density = function(x, probs = seq(0, 1, 0.25), ...) {\n ## sanity check for probabilities\n if (any(probs < 0 | probs > 1)) stop(\"'probs' outside [0,1]\")\n\n ## probability density function, extrapolated to zero, use midpoints\n n = length(x$x)\n pdf = x$y\n pdf = c(0, pdf, 0)\n\n ## x variable, also extrapolated, use midpoints\n x = x$x\n delta = median(diff(x))\n x = c(x[1L] - delta, x, x[n] + delta)\n\n ## numerical integration of density\n cdf = c(0, cumsum(diff(x) * (pdf[-1L] + pdf[-(n + 2L)])/2))\n cdf = cdf/cdf[n + 2L]\n\n ## approximate quantiles\n approx(cdf, x, xout = probs, rule = 2)$y \n}\n"], ["/tinyplot/R/tinytheme.R", "#' Set or Reset Plot Themes for `tinyplot`\n#'\n#' @md\n#' @description\n#' The `tinytheme` function sets or resets the theme for plots created with\n#' `tinyplot`. Themes control the appearance of plots, such as text alignment,\n#' font styles, axis labels, and even dynamic margin adjustment to reduce\n#' whitespace.\n#'\n#' @param theme A character string specifying the name of the theme to apply.\n#' Themes are arranged in an approximate hierarchy, adding or subtracting\n#' elements in the order presented below. Note that several themes are\n#' _dynamic_, in the sense that they attempt to reduce whitespace in a way\n#' that is responsive to the length of axes labels, tick marks, etc. These\n#' dynamic plots are marked with an asterisk (*) below.\n#' \n#' - `\"default\"`: inherits the user's default base graphics settings.\n#' - `\"basic\"`: light modification of `\"default\"`, only adding filled points, a panel background grid, and light gray background to facet titles.\n#' - `\"clean\"` (*): builds on `\"basic\"` by moving the subtitle above the plotting area, adding horizontal axis labels, employing tighter default plot margins and title gaps to reduce whitespace, and setting different default palettes (\"Tableau 10\" for discrete colors and \"agSunset\" for gradient colors). The first of our dynamic themes and the foundation for several derivative themes that follow below.\n#' - `\"clean2\"` (*): removes the plot frame (box) from `\"clean\"`.\n#' - `\"classic\"` (*): connects the axes in a L-shape, but removes the other top and right-hand edges of the plot frame (box). Also sets the \"Okabe-Ito\" palette as a default for discrete colors. Inspired by the **ggplot2** theme of the same name. \n#' - `\"bw\"` (*): similar to `\"clean\"`, except uses thinner lines for the plot frame (box), solid grid lines, and sets the \"Okabe-Ito\" palette as a default for discrete colors. Inspired by the **ggplot2** theme of the same name. \n#' - `\"minimal\"` (*): removes the plot frame (box) from `\"bw\"`, as well as the background for facet titles. Inspired by the **ggplot2** theme of the same name. \n#' - `\"ipsum\"` (*): similar to `\"minimal\"`, except subtitle is italicised and axes titles are aligned to the far edges. Inspired by the **hrbrthemes** theme of the same name for **ggplot2**. \n#' - `\"dark\"` (*): similar to `\"minimal\"`, but set against a dark background with foreground and a palette colours lightened for appropriate contrast.\n#' - `\"ridge\"` (*): a specialized theme for ridge plots (see [`type_ridge()`]). Builds off of `\"clean\"`, but adds ridge-specific tweaks (e.g. default \"Zissou 1\" palette for discrete colors, solid horizontal grid lines, and minor adjustments to y-axis labels). Not recommended for non-ridge plots.\n#' - `\"ridge2\"` (*): removes the plot frame (box) from `\"ridge\"`, but retains the x-axis line. Again, not recommended for non-ridge plots.\n#' - `\"tufte\"`: floating axes and minimalist plot artifacts in the style of Edward Tufte.\n#' - `\"void\"`: switches off all axes, titles, legends, etc.\n#' @param ... Named arguments to override specific theme settings. These\n#' arguments are passed to `tpar()` and take precedence over the predefined\n#' settings in the selected theme.\n#'\n#' @details\n#' Sets a list of graphical parameters using `tpar()`\n#'\n#' To reset the theme to default settings (no customization), call `tinytheme()`\n#' without arguments.\n#' \n#' **Caveat emptor:** Themes are a somewhat experimental feature of `tinyplot`.\n#' While we feel confident that themes should work as expected for most\n#' \"standard\" cases, there may be some sharp edges. Please report any unexpected\n#' behaviour to our GitHub repo:\n#' \n#' \n#' Known current limitations include:\n#' \n#' - Themes do not work well when `legend = \"top!\"`.\n#' - Dynamic margin spacing does not account for multi-line strings (e.g., axes\n#' or main titles that contain \"\\\\n\").\n#'\n#' @return The function returns nothing. It is called for its side effects.\n#' \n#' @seealso [`tpar`] which does the heavy lifting under the hood.\n#'\n#' @examples\n#' # Reusable plot function\n#' p = function() tinyplot(\n#' lat ~ long | depth, data = quakes,\n#' main = \"Earthquakes off Fiji\",\n#' sub = \"Data courtesy of the Harvard PRIM-H project\"\n#' )\n#' p()\n#' \n#' # Set a theme\n#' tinytheme(\"bw\")\n#' p()\n#'\n#' # Try a different theme\n#' tinytheme(\"dark\")\n#' p()\n#' \n#' # Customize the theme by overriding default settings\n#' tinytheme(\"bw\", fg = \"green\", font.main = 2, font.sub = 3, family = \"Palatino\")\n#' p()\n#' \n#' # Another custom theme example\n#' tinytheme(\"bw\", font.main = 2, col.axis = \"darkcyan\", family = \"HersheyScript\")\n#' p()\n#' \n#' # Aside: One or two specialized themes are only meant for certain plot types\n#' tinytheme(\"ridge2\")\n#' tinyplot(I(cut(lat, 10)) ~ depth, data = quakes, type = \"ridge\")\n#'\n#' # Reset the theme\n#' tinytheme()\n#' p()\n#' \n#' # Themes showcase\n#' ## We'll use a slightly more intricate plot (long y-axis labs and facets)\n#' ## to demonstrate dynamic margin adjustment etc.\n#' \n#' thms = eval(formals(tinytheme)$theme)\n#' \n#' for (thm in thms) {\n#' tinytheme(thm)\n#' tinyplot(\n#' I(Sepal.Length*1e4) ~ Petal.Length | Species, facet = \"by\", data = iris,\n#' main = \"Demonstration of tinyplot themes\",\n#' sub = paste0('tinytheme(\"', thm, '\")')\n#' )\n#' }\n#' \n#' # Reset\n#' tinytheme()\n#'\n#' @export\ntinytheme = function(\n theme = c(\n \"default\", \"basic\",\n \"clean\", \"clean2\", \"bw\", \"classic\",\n \"minimal\", \"ipsum\", \"dark\",\n \"ridge\", \"ridge2\",\n \"tufte\", \"void\"\n ),\n ...\n ) {\n \n theme = match.arg(theme)\n\n # in notebooks, we don't want to close the device because no image.\n # init_tpar() tries to be smart, but may fail.\n init_tpar(rm_hook = TRUE)\n\n assert_choice(\n theme,\n c(\n \"default\",\n sort(c(\"basic\", \"bw\", \"classic\", \"clean\", \"clean2\", \"dark\", \"ipsum\",\n \"minimal\", \"ridge\", \"ridge2\", \"tufte\", \"void\"))\n )\n )\n\n settings = switch(theme,\n \"default\" = theme_default,\n \"basic\" = theme_basic,\n \"bw\" = theme_bw,\n \"classic\" = theme_classic,\n \"clean\" = theme_clean,\n \"clean2\" = theme_clean2,\n \"dark\" = theme_dark,\n \"ipsum\" = theme_ipsum,\n \"minimal\" = theme_minimal,\n \"ridge\" = theme_ridge,\n \"ridge2\" = theme_ridge2,\n \"tufte\" = theme_tufte,\n \"void\" = theme_void,\n )\n\n dots = list(...)\n for (n in names(dots)) {\n settings[[n]] = dots[[n]]\n }\n\n if (length(settings) > 0) {\n if (theme == \"default\") {\n # for default theme, we want to revert the original pars and turn off the\n # before.new.plot hook (otherwise manual par(x = y) changes won't work) \n tpar(settings, hook = FALSE)\n old_hooks = get_environment_variable(\".tpar_hooks\")\n remove_hooks(old_hooks)\n } else {\n tpar(settings, hook = TRUE)\n }\n }\n\n return(invisible(NULL))\n}\n\n\n\n#\n## Themes (these are read and set at initial load time)\n\n# theme_default = list()\n\ntheme_default = list(\n tinytheme = \"default\",\n adj = par(\"adj\"), # 0.5,\n adj.main = par(\"adj\"), # 0.5,\n adj.sub = par(\"adj\"), # 0.5,\n bg = \"white\", # par(\"bg\") # \"white\"\n bty = par(\"bty\"), #\"o\",\n cex.axis = par(\"cex.axis\"), #1,\n cex.main = par(\"cex.main\"), #1.2,\n cex.xlab = par(\"cex.axis\"), #1,\n cex.ylab = par(\"cex.axis\"), #1,\n col.axis = par(\"col.axis\"), #1,\n col.xaxs = par(\"col.axis\"), #1,\n col.yaxs = par(\"col.axis\"), #1,\n col.lab = par(\"col.lab\"), #\"black\",\n col.main = par(\"col.main\"), #\"black\",\n col.sub = par(\"col.sub\"), #\"black\",\n dynmar = FALSE,\n facet.bg = NULL,\n facet.border = NA,\n family = par(\"family\"), # \"\"\n fg = par(\"fg\"),\n font = par(\"font\"), # 1,\n font.axis = par(\"font.axis\"), # 1,\n font.lab = par(\"font.lab\"), # 1,\n font.main = par(\"font.main\"), # 2,\n font.sub = par(\"font.sub\"), # 2,\n grid = FALSE,\n grid.col = \"lightgray\",\n grid.lty = \"dotted\",\n grid.lwd = 1,\n lab = par(\"lab\"), # c(5, 5, 7),\n las = par(\"las\"), # 0,\n lwd = par(\"lwd\"), # 1,\n lwd.axis = par(\"lwd\"), # 1,\n mar = c(5.1, 4.1, 4.1, 2.1), ## test\n mgp = par(\"mgp\"),\n # palette.qualitative = \"R4\",\n # palette.sequential = \"Viridis\",\n pch = par(\"pch\"), # 1,\n side.sub = 1,\n tck = NA,\n xaxt = \"standard\",\n yaxt = \"standard\"\n)\n\n# derivatives of \"default\" \n# - basic\n# - tufte\n# - void\n\ntheme_basic = modifyList(theme_default, list(\n tinytheme = \"basic\",\n facet.bg = \"gray90\",\n facet.border = \"black\",\n grid = TRUE,\n pch = 16\n))\n\ntheme_tufte = modifyList(theme_default, list(\n tinytheme = \"tufte\",\n adj.main = 0,\n adj.sub = 0,\n bty = \"n\",\n font.main = 1,\n lab = c(10, 10, 7),\n # palette.sequential = \"Grays\",\n pch = 16,\n side.sub = 3,\n tcl = 0.2\n))\n\ntheme_void = modifyList(theme_default, list(\n tinytheme = \"void\",\n adj.main = 0,\n adj.sub = 0,\n font.main = 1,\n palette.qualitative = \"Tableau 10\",\n palette.sequential = \"ag_Sunset\",\n pch = 16,\n side.sub = 3,\n # tck = -.02,\n xaxt = \"none\",\n yaxt = \"none\"\n))\n\n# derivatives of \"basic\" \n# - clean\n\ntheme_clean = modifyList(theme_basic, list(\n ## Notes:\n ## - 1. Reduce axis title gap by 0.5 lines and also reduce tcl to 0.3 lines.\n ## - 2. Sub moves to top.\n ## - 3. Also want to remove excess white on rhs of plot margin (when no legend).\n ## - Together, 1, 2, and 3 imply that...\n ## -- mgp[1] should be adjusted by 0.8 (= 0.5 + 0.3)\n ## -- mgp[2] should be adjusted by 0.3\n ## -- mar[1] should be adjusted by 1.8 (= 1 (no sub) + 0.5 + 0.3 (tighter axis labs))\n ## -- mar[2] should be adjusted by 0.8 (= 0.5 + 0.3)\n ## -- mar[3] should remain unchanged (main + sub will adjust automatically)\n ## -- mar[4] should be adjusted by 1.5 (relative to 2.1)\n ##\n tinytheme = \"clean\",\n adj.main = 0,\n adj.sub = 0,\n dynmar = TRUE,\n las = 1,\n mar = c(5.1, 4.1, 4.1, 2.1) - c(1+0.5+0.3, 0.5+0.3, 0, 1.5), ## test\n mgp = c(3, 1, 0) - c(0.5+0.3, 0.3, 0), # i.e., subtract 0.5 lines + the (abs) value of the tcl adjustment\n palette.qualitative = \"Tableau 10\",\n palette.sequential = \"ag_Sunset\",\n side.sub = 3,\n tcl = -0.3\n))\n\n# derivatives of \"clean\" \n# - clean2\n# - classic\n# - bw\n\ntheme_clean2 = modifyList(theme_clean, list(\n tinytheme = \"clean2\",\n facet.border = \"gray90\",\n xaxt = \"labels\",\n yaxt = \"labels\"\n))\n\ntheme_classic = modifyList(theme_clean, list(\n tinytheme = \"classic\",\n bty = \"l\",\n facet.bg = NULL,\n font.main = 1,\n grid = FALSE,\n palette.qualitative = \"Okabe-Ito\"\n))\n\ntheme_bw = modifyList(theme_clean, list(\n tinytheme = \"bw\",\n font.main = 1,\n grid.lty = 1,\n grid.lwd = 0.5,\n lwd = 0.5,\n lwd.axis = 0.5,\n palette.qualitative = \"Okabe-Ito\"\n))\n\n# derivatives of \"bw\"\n# - minimal\n# - ipsum\n# - dark\n \ntheme_minimal = modifyList(theme_bw, list(\n tinytheme = \"minimal\",\n bty = \"n\",\n facet.bg = NULL,\n facet.border = NULL,\n xaxt = \"labels\",\n yaxt = \"labels\"\n))\n\ntheme_ipsum = modifyList(theme_minimal, list(\n tinytheme = \"ipsum\",\n bty = \"n\",\n font.sub = 3,\n adj.ylab = 1,\n adj.xlab = 1\n))\n\ntheme_dark = modifyList(theme_minimal, list(\n tinytheme = \"dark\",\n bg = \"#1A1A1A\",\n fg = \"#BBBBBB\",\n # col = \"white\",\n col.xaxs = \"#BBBBBB\",\n col.yaxs = \"#BBBBBB\",\n col.lab = \"#BBBBBB\",\n col.main = \"#BBBBBB\",\n col.sub = \"#BBBBBB\",\n col.axis = \"#BBBBBB\",\n # facet.bg = \"gray20\",\n grid.col = \"#6D6D6D\",\n palette.qualitative = \"Set 2\",\n palette.sequential = \"Sunset\"\n))\n\n# derivative of clean/clean2\n\ntheme_ridge = modifyList(theme_clean, list(\n tinytheme = \"ridge\",\n palette.qualitative = \"Zissou 1\",\n grid = FALSE\n))\ntheme_ridge2 = modifyList(theme_clean2, list(\n tinytheme = \"ridge2\",\n palette.qualitative = \"Zissou 1\",\n grid = FALSE\n))\n"], ["/tinyplot/R/type_abline.R", "#' Add straight lines to a plot\n#' @description\n#' These functions add straight line(s) through the current plot.\n#' @details\n#' While `type_abline`, `type_hline`, and `type_vline` can be called in a base\n#' plot layer, we expect that they will typically be called as subsequent\n#' layers via [`tinyplot_add`].\n#' @section Recycling logic: \n#' The recycling behaviour of the line parameters (i.e., `a`, `b`, `h`, or `v`)\n#' is adaptive, depending on whether `by` or `facet` grouping is detected. While\n#' this leads to different recycling scenarios, the underlying code logic\n#' follows sensible heuristics designed to match user expectations.\n#' \n#' Parameter lengths must equal one of four options:\n#' \n#' 1. Single value (i.e., length = 1), i.e. simplest case where the same line is\n#' applied uniformly across all groups and facets. Uses the default user colour\n#' (e.g. `\"black\"`, or `tpar(\"palette.qualitative\")[1]` if a theme is set).\n#' 2. Number of `by` groups, i.e. one parameter per group. For example,\n#' `tinyplot(mpg ~ wt | factor(cyl), data = mtcars, type = type_hline(h = 21:23))`\n#' will give three horizontal lines, with colours matching the user's qualitative\n#' palette.\n#' 3. Number of `facet` groups, i.e. one parameter per facet panel. For example:\n#' `tinyplot(mpg ~ wt, facet = ~am, data = mtcars, type = type_hline(h = c(20,30)))`\n#' would give separate horizontal lines per facet, but both using the same\n#' default color.\n#' 4. Product of `by` and `facet` groups, i.e. one parameter for each unique\n#' by-facet combination. Orders over facets first and then, within that, by\n#' group. For example:\n#' `tinyplot(mpg ~ wt | factor(cyl), facet = ~am, data = mtcars, type = type_hline(h = 21:26))`\n#' will give six separate lines, with the first three (`21:23`) coloured by\n#' group in the first facet, and second three (`24:26`) coloured by by group\n#' in the second facet.\n#' \n#' Alongside these general rules, we also try to accomodate special cases when\n#' other aesthetic parameters like `lwd` or `lty` are invoked by the user. See\n#' Examples.\n#' \n#' @param a,b the intercept (default: `a` = 0) and slope (default: `b` = 1)\n#' terms. Numerics of length 1, or equal to the number of groups or number of\n#' facets (or the product thereof).\n#' @examples\n#' #\n#' ## abline\n#' \n#' tinyplot(x = -10:10, y = rnorm(21) + -10:10, grid = TRUE)\n#' tinyplot_add(type = \"abline\")\n#' # same as...\n#' # tinyplot_add(type = type_abline(a = 0, b = 1))\n#' \n#' # customize by passing bespoke intercept and slope values\n#' tinyplot_add(type = type_abline(a = -1, b = -0.5))\n#' \n#' # note that calling as abline & co. as a base plot layer will still lead to\n#' # axes limits that respect the range of the data\n#' tinyplot(x = -10:10, y = -10:10, grid = TRUE, type = \"abline\")\n#' \n#' #\n#' ## hline and vline\n#'\n#' # Base plot layer\n#' tinyplot(mpg ~ hp | cyl, facet = \"by\", data = mtcars, ylim = c(0, 40))\n#' \n#' # Add horizontal lines at the (default) 0 y-intercept\n#' tinyplot_add(type = \"hline\", col = \"grey\")\n#' \n#' # Note that group+facet aesthetics will be inherited. We can use this to\n#' # add customized lines (here: the mean `mpg` for each `cyl` group) \n#' tinyplot_add(type = type_hline(with(mtcars, tapply(mpg, cyl, mean))), lty = 2)\n#' \n#' # Similar idea for vline\n#' tinyplot_add(type = type_vline(with(mtcars, tapply(hp, cyl, mean))), lty = 2)\n#' \n#' #\n#' ## Recycling logic\n#' \n#' # length(h) == no. of groups\n#' tinyplot(mpg ~ wt | factor(cyl), data = mtcars, type = type_hline(h = 21:23))\n#' \n#' # length(h) == no. of facets\n#' tinyplot(mpg ~ wt, facet = ~am, data = mtcars, type = type_hline(h = c(20, 30)))\n#' \n#' # length(h) == no. of groups x no. of facets\n#' tinyplot(mpg ~ wt | factor(cyl), facet = ~am, data = mtcars,\n#' type = type_hline(h = 21:26))\n#' \n#' # special adjustment case (here: lwd by group)\n#' tinyplot(mpg ~ wt | factor(cyl), facet = ~am, data = mtcars,\n#' type = type_hline(c(20, 30)), lwd = c(21, 14, 7))\n#' \n#' @export\ntype_abline = function(a = 0, b = 1) {\n data_abline = function(datapoints, lwd, lty, col, ...) {\n if (nrow(datapoints) == 0) {\n msg = \"`type_abline() only works on existing plots with x and y data points.\"\n stop(msg, call. = FALSE)\n }\n # keep track of unique lty and lwd (needed for group catch / escape hatch\n # later in draw_hline)\n ul_lwd = length(unique(lwd))\n ul_lty = length(unique(lty))\n ul_col = length(unique(col))\n return(list(type_info = list(ul_lty = ul_lty, ul_lwd = ul_lwd, ul_col = ul_col)))\n }\n draw_abline = function() {\n fun = function(\n ifacet, iby, data_facet, icol, ilty, ilwd,\n ngrps, nfacets, by_continuous, facet_by,\n type_info,\n ...\n ) {\n \n # flag for aesthetics by groups\n grp_aes = type_info[[\"ul_col\"]] == 1 || type_info[[\"ul_lty\"]] == ngrps || type_info[[\"ul_lwd\"]] == ngrps\n \n if (length(a) != 1) {\n if (!length(a) %in% c(ngrps, nfacets, ngrps*nfacets)) {\n msg = \"Length of 'a' must be 1, or equal to the number of facets or number of groups (or product thereof).\"\n stop(msg, call. = FALSE)\n }\n if (!facet_by && length(a) == nfacets) {\n a = a[ifacet]\n if (!grp_aes && type_info[[\"ul_col\"]]!=ngrps) {\n icol = 1\n } else if (by_continuous) {\n icol = 1\n }\n } else if (!by_continuous && length(a) == ngrps * nfacets) {\n a = a[ifacet * ngrps - c(ngrps - iby)]\n } else if (!by_continuous) {\n a = a[iby]\n }\n } else if (!grp_aes) {\n icol = 1\n }\n \n if (length(b) != 1) {\n if (!length(b) %in% c(ngrps, nfacets, ngrps*nfacets)) {\n msg = \"Length of 'b' must be 1, or equal to the number of facets or number of groups (or product thereof).\"\n stop(msg, call. = FALSE)\n }\n if (!facet_by && length(b) == nfacets) {\n b = b[ifacet]\n if (!grp_aes && type_info[[\"ul_col\"]]!=ngrps) {\n icol = 1\n } else if (by_continuous) {\n icol = 1\n }\n } else if (!by_continuous && length(b) == ngrps * nfacets) {\n b = b[ifacet * ngrps - c(ngrps - iby)]\n } else if (!by_continuous) {\n b = b[iby]\n }\n } else if (!grp_aes) {\n icol = 1\n }\n \n if (type_info[[\"ul_col\"]]!=1 && !(type_info[[\"ul_lty\"]]==ngrps || type_info[[\"ul_lwd\"]]==ngrps)) {\n icol = 1\n }\n\n abline(a = a, b = b, col = icol, lty = ilty, lwd = ilwd)\n }\n return(fun)\n }\n out = list(\n draw = draw_abline(),\n data = data_abline,\n name = \"abline\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_barplot.R", "#' Barplot type\n#'\n#' @description Type function for producing barplots. For formulas of type\n#' `~ x` (without left-hand side) the barplot visualizes the counts (absolute\n#' frequencies) of the levels of `x`. For formulas of type `y ~ x` the value\n#' of `y` within each level of `x` is visualized, if necessary aggregated\n#' using some function (default: mean).\n#'\n#' @param width numeric, optional vector of bar widths. (The distance between\n#' the midpoints of the bars is always 1.)\n#' @param beside logical. In case of a `by` grouping variable, should bars be\n#' juxtaposed? Default is to use stacked bars instead.\n#' @param center logical or numeric. In case of stacked barplots (`beside = FALSE`)\n#' should the bars be centered (or all start at zero, default)? If set to\n#' `TRUE` the center is at the mid-point of the middle category (in case of\n#' uneven number of categories) or between the two middle categories (in case\n#' of an even number). Additionally it is possible to set `center = 2` or\n#' `center = 2.5` to indicate that centering should be after the second category\n#' or the mid-way in the third category, respectively.\n#' @param FUN a function to compute the summary statistic for `y` within each\n#' group of `x` in case of using a two-sided formula `y ~ x` (default: mean).\n#' @param xlevels a character or numeric vector specifying the ordering of the\n#' levels of the `x` variable (if character) or the corresponding indexes\n#' (if numeric) for the plot.\n#' @param xaxlabels a character vector with the axis labels for the `x` variable,\n#' defaulting to the levels of `x`.\n#' @param drop.zeros logical. Should bars with zero height be dropped? If set\n#' to `FALSE` (default) a zero height bar is still drawn for which the border\n#' lines will still be visible.\n#'\n#' @examples\n#' # Basic examples of frequency tables (without y variable)\n#' tinyplot(~ cyl, data = mtcars, type = \"barplot\")\n#' tinyplot(~ cyl | vs, data = mtcars, type = \"barplot\")\n#' tinyplot(~ cyl | vs, data = mtcars, type = \"barplot\", beside = TRUE)\n#' tinyplot(~ cyl | vs, data = mtcars, type = \"barplot\", beside = TRUE, fill = 0.2)\n#' \n#' # Reorder x variable categories either by their character levels or numeric indexes\n#' tinyplot(~ cyl, data = mtcars, type = \"barplot\", xlevels = c(\"8\", \"6\", \"4\"))\n#' tinyplot(~ cyl, data = mtcars, type = \"barplot\", xlevels = 3:1)\n#' \n#' # Note: Above we used automatic argument passing for `beside`. But this\n#' # wouldn't work for `width`, since it would conflict with the top-level\n#' # `tinyplot(..., width = )` argument. It's safer to pass these args\n#' # through the `type_barplot()` functional equivalent.\n#' tinyplot(~ cyl | vs, data = mtcars, fill = 0.2,\n#' type = type_barplot(beside = TRUE, drop.zeros = TRUE, width = 0.65))\n#'\n#' tinytheme(\"clean2\")\n#' \n#' # Example for numeric y aggregated by x (default: FUN = mean) + facets\n#' tinyplot(extra ~ ID | group, facet = \"by\", data = sleep,\n#' type = \"barplot\", fill = 0.6)\n#' \n#' # Fancy frequency table:\n#' tinyplot(Freq ~ Sex | Survived, facet = ~ Class, data = as.data.frame(Titanic),\n#' type = \"barplot\", facet.args = list(nrow = 1), flip = TRUE, fill = 0.6)\n#'\n#' # Centered barplot for conditional proportions of hair color (black/brown vs.\n#' # red/blond) given eye color and sex\n#' tinytheme(\"clean2\", palette.qualitative = c(\"black\", \"sienna\", \"indianred\", \"goldenrod\"))\n#' hec = as.data.frame(proportions(HairEyeColor, 2:3))\n#' tinyplot(Freq ~ Eye | Hair, facet = ~ Sex, data = hec, type = \"barplot\",\n#' center = TRUE, flip = TRUE, facet.args = list(ncol = 1), yaxl = \"percent\")\n#'\n#' tinytheme()\n#' \n#' @export\ntype_barplot = function(width = 5/6, beside = FALSE, center = FALSE, FUN = NULL, xlevels = NULL, xaxlabels = NULL, drop.zeros = FALSE) {\n out = list(\n data = data_barplot(width = width, beside = beside, center = center, FUN = FUN, xlevels = xlevels, xaxlabels = xaxlabels, drop.zeros = drop.zeros),\n draw = draw_rect(),\n name = \"barplot\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n#' @importFrom stats aggregate\ndata_barplot = function(width = 5/6, beside = FALSE, center = FALSE, FUN = NULL, xlevels = NULL, xaxlabels = NULL, drop.zeros = FALSE) {\n fun = function(datapoints, col, bg, lty, lwd, palette, xlab = NULL, ylab = NULL, xlim = NULL, ylim = NULL, xaxt = NULL, yaxl = NULL, yaxt = NULL, axes = TRUE, null_by, facet_by, ...) {\n\n \n ## tabulate/aggregate datapoints\n if (is.null(datapoints$y)) {\n xlab = ylab\n ylab = \"Count\"\n \n datapoints$y = numeric(nrow(datapoints)) \n if (!is.null(FUN)) warning(\"without 'y' variable 'FUN' specification is ignored\")\n FUN = length\n } else {\n if (is.null(FUN)) FUN = function(x, ...) mean(x, ..., na.rm = TRUE)\n }\n if (!is.factor(datapoints$x)) datapoints$x = factor(datapoints$x)\n if (!is.null(xlevels)) {\n xlevels = if(is.numeric(xlevels)) levels(datapoints$x)[xlevels] else xlevels\n if (any(is.na(xlevels)) || !all(xlevels %in% levels(datapoints$x))) warning(\"not all 'xlevels' correspond to levels of 'x'\")\n datapoints$x = factor(datapoints$x, levels = xlevels)\n }\n if (!is.null(xaxlabels)) levels(datapoints$x) <- xaxlabels\n datapoints = aggregate(datapoints[, \"y\", drop = FALSE], datapoints[, c(\"x\", \"by\", \"facet\")], FUN = FUN, drop = FALSE)\n datapoints$y[is.na(datapoints$y)] = 0 #FIXME: always?#\n if (!is.factor(datapoints$by)) datapoints$by = factor(datapoints$by)\n if (!is.factor(datapoints$facet)) datapoints$facet = factor(datapoints$facet)\n \n if (isFALSE(null_by) && isFALSE(facet_by) && !beside && any(datapoints$y < 0)) {\n warning(\"'beside' must be TRUE if there are negative 'y' values\")\n beside = TRUE\n }\n if (beside & !isFALSE(center)) {\n warning(\"'center' is currently only supported for 'beside = FALSE'\")\n }\n offset_sum = function(z, center = TRUE, na.rm = TRUE) {\n n = length(z)\n if (isFALSE(center) || n < 1L) return(0)\n mid = if (isTRUE(center)) n/2 else center\n z[floor(mid) + 1L] = (mid - floor(mid)) * z[floor(mid) + 1L]\n sum(z[0L:floor(mid) + 1L], na.rm = TRUE)\n }\n if (is.null(xlim)) xlim = c(1, length(levels(datapoints$x))) + c(-0.5, 0.5) * width\n if (is.null(ylim)) ylim = if (beside || length(unique(datapoints$by)) == 1L) {\n c(pmin(0, min(datapoints$y, na.rm = TRUE) * 1.02), pmax(0, max(datapoints$y, na.rm = TRUE) * 1.02))\n } else {\n range(unlist(tapply(\n datapoints$y,\n interaction(datapoints$x, datapoints$facet),\n function(z) c(0, sum(z, na.rm = TRUE)) - offset_sum(z, center = center)\n ))) * 1.02\n }\n\n ## default color palette\n ngrps = length(unique(datapoints$by))\n if (ngrps == 1L && is.null(palette)) {\n if (is.null(col)) col = par(\"fg\")\n if (is.null(bg)) bg = \"grey\"\n } else {\n if (is.null(bg)) bg = \"by\"\n }\n\n ## calculate bar rectangles per facet \n sdat = split(datapoints, datapoints$facet)\n datapoints = lapply(sdat, function(df) {\n \n df = df[order(df$x), , drop = FALSE]\n nx = length(levels(df$x))\n nb = length(levels(df$by))\n \n if (beside) { \n xl = as.numeric(df$x) - width/2 + (as.numeric(df$by) - 1) * width/nb * as.numeric(!facet_by)\n xr = if (facet_by) xl + width else xl + width/nb\n yb = 0\n yt = df$y\n } else {\n cs = tapply(df$y, df$x, function(z) cumsum(c(0, z)) - offset_sum(z, center = center))\n xl = as.numeric(df$x) - width/2\n xr = xl + width\n yb = if (facet_by) 0 else unlist(lapply(cs, `[`, -(nb + 1L)))\n yt = if (facet_by) df$y else unlist(lapply(cs, `[`, -1L))\n }\n \n df$xmin = xl\n df$xmax = xr\n df$ymin = yb\n df$ymax = yt\n df$nx = nx\n \n if (drop.zeros) {\n yb = rep_len(yb, length(yt))\n yok = abs(yt - yb) > 0\n df = df[yok, , drop = FALSE]\n }\n \n return(df)\n })\n datapoints = do.call(\"rbind\", datapoints)\n nx = datapoints$nx[1]\n datapoints$nx = NULL\n xlabs = 1L:nx\n names(xlabs) = levels(datapoints$x)\n \n if (!isFALSE(center)) {\n if (is.null(yaxl)) {\n yaxl = abs\n } else if (is.character(yaxl)) {\n yaxl = paste0(\"abs_\", yaxl)\n }\n }\n \n out = list(\n datapoints = datapoints,\n xlab = xlab,\n ylab = ylab,\n xlim = xlim,\n ylim = ylim,\n axes = FALSE, #FIXME\n axes = TRUE,\n xlabs = xlabs, \n frame.plot = FALSE,\n xaxs = \"r\",\n xaxt = if (xaxt == \"s\") \"l\" else xaxt,\n yaxl = yaxl,\n yaxs = \"i\",\n col = col,\n bg = bg\n )\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/tpar.R", "#' @title Set or query graphical parameters\n#'\n#' @description Extends \\code{\\link[graphics]{par}}, serving as a (near) drop-in\n#' replacement for setting or querying graphical parameters. The key\n#' differences is that, beyond supporting the standard group of R graphical\n#' parameters in \\code{\\link[graphics]{par}}, `tpar` also supports additional\n#' graphical parameters that are provided by `tinyplot`. Similar to\n#' \\code{\\link[graphics]{par}}, parameters are set by passing appropriate\n#' `key = value` argument pairs, and multiple parameters can be set or queried\n#' at the same time.\n#'\n#' @param ... arguments of the form `key = value`. This includes all of the\n#' parameters typically supported by \\code{\\link[graphics]{par}}, as well as\n#' the `tinyplot`-specific ones described in the 'Graphical Parameters'\n#' section below.\n#' @param hook Logical. If `TRUE`, base graphical parameters persist across \n#' plots via a hook applied before each new plot (see `?setHook`).\n#'\n#' @md\n#' @details The `tinyplot`-specific parameters are saved in an internal\n#' environment called `.tpar` for performance and safety reasons. However,\n#' they can also be set at package load time via \\code{\\link[base]{options}},\n#' which may prove convenient for users that want to enable different default\n#' behaviour at startup (e.g., through an `.Rprofile` file). These options all\n#' take a `tinyplot_*` prefix, e.g.\n#' `options(tinyplot_grid = TRUE, tinyplot_facet.bg = \"grey90\")`.\n#'\n#' For their part, any \"base\" graphical parameters are caught dynamically and\n#' passed on to \\code{\\link[graphics]{par}} as appropriate. Technically, only\n#' parameters that satisfy `par(..., no.readonly = TRUE)` are evaluated.\n#'\n#' However, note the important distinction: `tpar` only evaluates parameters\n#' from \\code{\\link[graphics]{par}} if they are passed _explicitly_ by the\n#' user. This means that `tpar` should not be used to capture the (invisible)\n#' state of a user's entire set of graphics parameters, i.e. `tpar()` !=\n#' `par()`. If you want to capture the _all_ existing graphics settings, then\n#' you should rather use `par()` instead.\n#'\n#' @returns When parameters are set, their previous values are returned in an\n#' invisible named list. Such a list can be passed as an argument to `tpar` to\n#' restore the parameter values.\n#'\n#' When just one parameter is queried, the value of that parameter is returned\n#' as (atomic) vector. When two or more parameters are queried, their values\n#' are returned in a list, with the list names giving the parameters.\n#'\n#' Note the inconsistency: setting one parameter returns a list, but querying\n#' one parameter returns a vector.\n#'\n#' @section Additional Graphical Parameters:\n#'\n#' * `adj.xlab`: Numeric value between 0 and 1 controlling the alignment of the x-axis label.\n#' * `adj.ylab`: Numeric value between 0 and 1 controlling the alignment of the y-axis label.\n#' * `cairo`: Logical indicating whether \\code{\\link[grDevices]{cairo_pdf}} should be used when writing plots to PDF. If `FALSE`, then \\code{\\link[grDevices]{pdf}} will be used instead, with implications for embedding (non-standard) fonts. Only used if `tinyplot(..., file = \".pdf\")` is called. Defaults to the value of `capabilities(\"cairo\")`.\n#' * `dynmar`: Logical indicating whether `tinyplot` should attempt dynamic adjustment of margins to reduce whitespace and/or account for spacing of text elements (e.g., long horizontal y-axis labels). Note that this parameter is tightly coupled to internal `tinythemes()` logic and should _not_ be adjusted manually unless you really know what you are doing or don't mind risking unintended consequences to your plot.\n#' * `facet.bg`: Character or integer specifying the facet background colour. If an integer, will correspond to the user's default colour palette (see `palette`). Passed to `rect`. Defaults to `NULL` (none).\n#' * `facet.border`: Character or integer specifying the facet border colour. If an integer, will correspond to the user's default colour palette (see `palette`). Passed to `rect`. Defaults to `NA` (none).\n#' * `facet.cex`: Expansion factor for facet titles. Defaults to `1`.\n#' * `facet.col`: Character or integer specifying the facet text colour. If an integer, will correspond to the user's default global colour palette (see `palette`). Defaults to `NULL`, which is equivalent to \"black\".\n#' * `facet.font`: An integer corresponding to the desired font face for facet titles. For most font families and graphics devices, one of four possible values: `1` (regular), `2` (bold), `3` (italic), or `4` (bold italic). Defaults to `NULL`, which is equivalent to `1` (i.e., regular).\n#' * `file.height`: Numeric specifying the height (in inches) of any plot that is written to disk using the `tinyplot(..., file = X)` argument. Defaults to `7`.\n#' * `file.res`: Numeric specifying the resolution (in dots per square inch) of any plot that is written to disk in bitmap format (i.e., PNG or JPEG) using the `tinyplot(..., file = X)` argument. Defaults to `300`.\n#' * `file.width`: Numeric specifying the width (in inches) of any plot that is written to disk using the `tinyplot(..., file = X)` argument. Defaults to `7`.\n#' * `fmar`: A numeric vector of form `c(b,l,t,r)` for controlling the (base) margin padding, in terms of lines, between the individual facets in a faceted plot. Defaults to `c(1,1,1,1)`. If more than three facets are detected, the `fmar` parameter is scaled by 0.75 to reduce excess whitespace. For 2x2 plots, the padding better matches the `cex` expansion logic of base graphics.\n#' * `grid.col`: Character or (integer) numeric that specifies the color of the panel grid lines. Defaults to `\"lightgray\"`.\n#' * `grid.lty`: Character or (integer) numeric that specifies the line type of the panel grid lines. Defaults to `\"dotted\"`.\n#' * `grid.lwd`: Non-negative numeric giving the line width of the panel grid lines. Defaults to `1`.\n#' * `grid`: Logical indicating whether a background panel grid should be added to plots automatically. Defaults to `NULL`, which is equivalent to `FALSE`.\n#' * `lmar`: A numeric vector of form `c(inner, outer)` that gives the margin padding, in terms of lines, around the automatic `tinyplot` legend. Defaults to `c(1.0, 0.1)`. The inner margin is the gap between the legend and the plot region, and the outer margin is the gap between the legend and the edge of the graphics device.\n#' * `palette.qualitative`: Palette for qualitative colors. See the `palette` argument in `?tinyplot`.\n#' * `palette.sequential`: Palette for sequential colors. See the `palette` argument in `?tinyplot`.\n#' * `ribbon.alpha`: Numeric factor in the range `[0,1]` for modifying the opacity alpha of \"ribbon\" and \"area\" type plots. Default value is `0.2`.\n#'\n#' @importFrom graphics par\n#' @importFrom utils modifyList\n#' \n#' @seealso [`graphics::par`] which `tpar` builds on top of. [`get_saved_par`]\n#' is a convenience function for retrieving graphical parameters at different\n#' stages of a `tinyplot` call (and used for internal accounting purposes).\n#' [`tinytheme`] allows users to easily set a group of graphics parameters\n#' in a single function call, according to a variety of predefined themes.\n#' \n#' @examples\n#' # Return a list of existing base and tinyplot graphic params\n#' tpar(\"las\", \"pch\", \"facet.bg\", \"facet.cex\", \"grid\")\n#'\n#' # Simple facet plot with these default values\n#' tinyplot(mpg ~ wt, data = mtcars, facet = ~am)\n#'\n#' # Set params to something new. Similar to graphics::par(), note that we save\n#' # the existing values at the same time by assigning to an object.\n#' op = tpar(\n#' las = 1,\n#' pch = 2,\n#' facet.bg = \"grey90\",\n#' facet.cex = 2,\n#' grid = TRUE\n#' )\n#'\n#' # Re-plot with these new params\n#' tinyplot(mpg ~ wt, data = mtcars, facet = ~am)\n#'\n#' # Reset back to original values\n#' tpar(op)\n#'\n#' # Important: tpar() only evalutes parameters that have been passed explicitly\n#' # by the user. So it it should not be used to query and set (restore)\n#' # parameters that weren't explicitly requested, i.e. tpar() != par().\n#'\n#' # Note: The tinyplot-specific parameters can also be be set via `options`\n#' # with a `tinyplot_*` prefix, which can be convenient for enabling\n#' # different default behaviour at startup time (e.g., via an .Rprofile\n#' # file). Example:\n#' # options(tinyplot_grid = TRUE, tinyplot_facet.bg = \"grey90\")\n#'\n#' @export\ntpar = function(..., hook = FALSE) {\n\n opts = list(...)\n if (length(opts) == 1 && is.null(names(opts))) {\n if (inherits(opts[[1]], \"list\") && !is.null(names(opts[[1]]))) {\n opts = opts[[1]]\n }\n }\n\n ###### Assign parameters\n\n # assign tinyplot-specific arguments with known names to .tpar\n assign_tpar(opts)\n\n # return informative error messages if the input is invalid\n assert_tpar(.tpar)\n\n # if tpar(...) includes arguments that are not known to be tinyplot-specific,\n # we set a hook to set them using par() when the graphic device is started\n nam = names(opts)\n if (!is.null(nam)) {\n base_par = setdiff(nam, known_tpar)\n base_par = opts[base_par]\n if (length(base_par) > 0) {\n if (isTRUE(hook)) {\n # append new hook to existing ones\n new_hooks = list(\"before.plot.new\" = function() par(base_par))\n set_hooks(new_hooks, action = \"append\")\n # save new hook to tinyplot environment for later removal\n old_hooks = get_environment_variable(\".tpar_hooks\")\n set_environment_variable(\".tpar_hooks\", c(old_hooks, new_hooks))\n } else {\n par_names = names(par(no.readonly = TRUE))\n base_par = base_par[names(base_par) %in% par_names]\n base_par_old = par(base_par)\n par(base_par)\n }\n }\n }\n\n\n ###### Retrieve parameters\n\n # User didn't assign any new values, but may have requested explicit (print\n # of) some existing value(s)\n tpar_old = as.list(.tpar)\n if (is.null(nam)) {\n known_par = names(par(no.readonly = TRUE))\n if (!is.null(nam)) {\n used_par = intersect(nam, known_par)\n } else {\n used_par = intersect(opts, known_par)\n }\n if (length(used_par)) {\n if (!is.null(nam)) used_par = opts[used_par]\n used_par_old = par(used_par)\n tpar_old = modifyList(as.list(.tpar), used_par_old, keep.null = TRUE)\n }\n if (!is.null(opts) && length(opts) != 0) {\n # specific values requested\n opts = Filter(is.character, opts)\n ret = (`names<-`(lapply(opts, function(x) .tpar[[x]]), opts))\n if (length(used_par)) {\n ret_par = par(used_par)\n ret = modifyList(ret, ret_par, keep.null = TRUE)\n }\n if (length(ret) == 1) ret = ret[[1]]\n return(ret)\n } else {\n # no specific request; return all existing values invisibly\n return(invisible(tpar_old))\n }\n # assign new values, but still return old values for saving existing settings\n # a la `oldpar = par(param = new_value)`\n } else {\n `names<-`(lapply(nam, function(x) .tpar[[x]]), nam)\n if (length(base_par) > 0 && isFALSE(hook)) tpar_old = modifyList(tpar_old, base_par_old, keep.null = TRUE)\n return(invisible(tpar_old))\n }\n}\n\n\n# Two levels of priority: .tpar[[\"name\"]] -> par(\"name\")\nget_tpar = function(opts, default = NULL) {\n # parameter priority\n # .tpar[[\"name\"]] -> par(\"name\")\n for (o in opts) {\n tp = .tpar[[o]]\n if (!is.null(tp)) {\n return(tp)\n } else {\n p = suppressWarnings(par(o))\n if (!is.null(p)) {\n return(p)\n }\n }\n\n }\n return(default)\n}\n\n\nknown_tpar = c(\n \"adj.main\",\n \"adj.sub\",\n \"adj.xlab\",\n \"adj.ylab\",\n \"cex.xlab\",\n \"cex.ylab\",\n \"col.xaxs\",\n \"col.yaxs\",\n \"cairo\",\n \"dynmar\",\n \"facet.bg\",\n \"facet.border\",\n \"facet.cex\",\n \"facet.col\",\n \"facet.font\",\n \"file.height\",\n \"file.res\",\n \"file.width\",\n \"fmar\",\n \"grid\",\n \"grid.bg\",\n \"grid.col\",\n \"grid.lty\",\n \"grid.lwd\",\n \"lmar\",\n \"lty.xaxs\",\n \"lty.yaxs\",\n \"lwd.xaxs\",\n \"lwd.yaxs\",\n \"lwd.axis\",\n \"pch\",\n \"palette.qualitative\",\n \"palette.sequential\",\n \"ribbon.alpha\",\n \"side.sub\",\n \"tinytheme\",\n \"xaxt\",\n \"yaxt\"\n)\n\n\nassign_tpar = function(opts) {\n for (n in intersect(names(opts), known_tpar)) {\n .tpar[[n]] = opts[[n]]\n }\n}\n\n\nassert_tpar = function(.tpar) {\n assert_numeric(.tpar[[\"adj.main\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"adj.main\")\n assert_numeric(.tpar[[\"adj.sub\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"adj.sub\")\n assert_numeric(.tpar[[\"adj.xlab\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"adj.xlab\")\n assert_numeric(.tpar[[\"adj.ylab\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"adj.ylab\")\n assert_flag(.tpar[[\"cairo\"]], name = \"cairo\")\n assert_flag(.tpar[[\"dynmar\"]], null.ok = FALSE, name = \"dynmar\")\n assert_numeric(.tpar[[\"lmar\"]], len = 2, null.ok = TRUE, name = \"lmar\")\n assert_numeric(.tpar[[\"ribbon.alpha\"]], len = 1, lower = 0, upper = 1, null.ok = TRUE, name = \"ribbon.alpha\")\n assert_numeric(.tpar[[\"grid.lwd\"]], len = 1, lower = 0, null.ok = TRUE, name = \"grid.lwd\")\n assert_flag(.tpar[[\"grid\"]], null.ok = TRUE, name = \"grid\")\n assert_numeric(.tpar[[\"file.res\"]], len = 1, lower = 0, null.ok = TRUE, name = \"file.res\")\n assert_numeric(.tpar[[\"file.height\"]], len = 1, lower = 0, null.ok = TRUE, name = \"file.height\")\n assert_numeric(.tpar[[\"file.width\"]], len = 1, lower = 0, null.ok = TRUE, name = \"file.width\")\n assert_numeric(.tpar[[\"facet.font\"]], len = 1, null.ok = TRUE, name = \"facet.font\")\n assert_numeric(.tpar[[\"facet.cex\"]], len = 1, null.ok = TRUE, name = \"facet.cex\")\n assert_numeric(.tpar[[\"side.sub\"]], len = 1, null.ok = TRUE, name = \"side.sub\")\n assert_string(.tpar[[\"grid.bg\"]], null.ok = TRUE, name = \"grid.bg\")\n assert_numeric(.tpar[[\"fmar\"]], len = 4, null.ok = TRUE, name = \"fmar\")\n\n facet.col = .tpar[[\"facet.col\"]]\n if (!is.null(facet.col)) {\n if (!is.null(facet.col) && !is.numeric(facet.col) && !is.character(facet.col)) {\n stop(\"facet.col needs to be NULL, or a numeric or character\", call. = FALSE)\n }\n assert_true(length(facet.col) == 1, name = \"length(facet.col)==1\")\n }\n\n facet.bg = .tpar$facet.bg\n if (!is.null(facet.bg)) {\n if (!is.numeric(facet.bg) && !is.character(facet.bg)) {\n stop(\"facet.bg needs to be NULL, or a numeric or character\", call. = FALSE)\n }\n assert_true(length(facet.bg) == 1, name = \"length(facet.bg)==1\")\n }\n\n facet.border = .tpar$facet.border\n if (!is.null(facet.border)) {\n if (!is.numeric(facet.border) && !is.character(facet.border) && !is.na(facet.border)) {\n stop(\"facet.border needs to be NULL, or a numeric, character, or NA\", call. = FALSE)\n }\n assert_true(length(facet.border) == 1, name = \"length(facet.border)==1\")\n }\n}\n\n\ninit_tpar = function(rm_hook = FALSE) {\n rm(list = names(.tpar), envir = .tpar)\n\n if (isTRUE(rm_hook)) {\n old_hooks = get_environment_variable(\".tpar_hooks\")\n if (length(old_hooks) > 0) {\n remove_hooks(old_hooks)\n set_environment_variable(\".tpar_hooks\", NULL)\n }\n }\n\n .tpar$cairo = if (is.null(getOption(\"tinyplot_cairo\"))) capabilities(\"cairo\") else as.logical(getOption(\"tinyplot_cairo\"))\n \n \n .tpar$dynmar = if (is.null(getOption(\"tinyplot_dynmar\"))) FALSE else as.logical(getOption(\"tinyplot_dynmar\"))\n \n # Figure output options if written to file\n .tpar$file.width = if (is.null(getOption(\"tinyplot_file.width\"))) 7 else as.numeric(getOption(\"tinyplot_file.width\"))\n .tpar$file.height = if (is.null(getOption(\"tinyplot_file.height\"))) 7 else as.numeric(getOption(\"tinyplot_file.height\"))\n .tpar$file.res = if (is.null(getOption(\"tinyplot_file.res\"))) 300 else as.numeric(getOption(\"tinyplot_file.res\"))\n\n # Facet margin, i.e. gap between the individual facet windows\n .tpar$fmar = if (is.null(getOption(\"tinyplot_fmar\"))) c(1, 1, 1, 1) else as.numeric(getOption(\"tinyplot_fmar\"))\n\n # Other facet options\n .tpar$facet.cex = if (is.null(getOption(\"tinyplot_facet.cex\"))) 1 else as.numeric(getOption(\"tinyplot_facet.cex\"))\n .tpar$facet.font = if (is.null(getOption(\"tinyplot_facet.font\"))) NULL else as.numeric(getOption(\"tinyplot_facet.font\"))\n .tpar$facet.col = if (is.null(getOption(\"tinyplot_facet.col\"))) NULL else getOption(\"tinyplot_facet.col\")\n .tpar$facet.bg = if (is.null(getOption(\"tinyplot_facet.bg\"))) NULL else getOption(\"tinyplot_facet.bg\")\n .tpar$facet.border = if (is.null(getOption(\"tinyplot_facet.border\"))) NA else getOption(\"tinyplot_facet.border\")\n\n # Plot grid\n .tpar$grid = if (is.null(getOption(\"tinyplot_grid\"))) FALSE else as.logical(getOption(\"tinyplot_grid\"))\n .tpar$grid.col = if (is.null(getOption(\"tinyplot_grid.col\"))) \"lightgray\" else getOption(\"tinyplot_grid.col\")\n .tpar$grid.lty = if (is.null(getOption(\"tinyplot_grid.lty\"))) \"dotted\" else getOption(\"tinyplot_grid.lty\")\n .tpar$grid.lwd = if (is.null(getOption(\"tinyplot_grid.lwd\"))) 1 else as.numeric(getOption(\"tinyplot_grid.lwd\"))\n\n # Legend margin, i.e. gap between the legend and the plot elements\n .tpar$lmar = if (is.null(getOption(\"tinyplot_lmar\"))) c(1.0, 0.1) else as.numeric(getOption(\"tinyplot_lmar\"))\n\n # Alpha fill (transparency) default for ribbon and area plots\n .tpar$ribbon.alpha = if (is.null(getOption(\"tinyplot_ribbon.alpha\"))) 0.2 else as.numeric(getOption(\"tinyplot_ribbon.alpha\"))\n}\n"], ["/tinyplot/R/tinylabel.R", "#' Format labels\n#' \n#' @description Function for formatting label appearance, e.g. axis\n#' ticks labels. This is what the top-level `xaxl` and `yaxl` arguments\n#' from [`tinyplot`] ultimately get passed to.\n#' @param x a numeric or character vector\n#' @param labeller a formatting function to be applied to `x`, e.g. [`format`],\n#' [`toupper`], [`abs`], or other custom function (including from the popular\n#' **scales** package). Can also be one of the following convenience strings\n#' (symbols), for which common formatting transformations are provided:\n#' `\"percent\"` (`\"%\"`), `\"comma\"` (`\",\"`), `\"log\"` (`\"l\"`), `\"dollar\"`\n#' (`\"$\"`), `\"euro\"` (`\"€\"`), or `\"sterling\"` (`\"£\"`).\n#' @examples\n#' x = 1e4\n#' tinylabel(x, \"comma\")\n#' tinylabel(x, \",\") # same\n#' tinylabel(x, \"$\") # or \"dollar\"\n#' \n#' # pass to xaxl/yaxl for adjusting axes tick labels in a tinyplot call\n#' tinyplot(I(mpg/hp) ~ hp, data = mtcars, yaxl = \"%\")\n#' \n#' # log example (combined with axis scaling)\n#' tinyplot(x = 10^c(10:0), y = 0:10, type = \"b\", log = \"x\", xaxl = \"log\")\n#' \n#' # combine with `x/yaxb` to adjust the actual tick marks (\"break points\")\n#' # at the same time\n#' tinyplot(x = 10^c(10:0), y = 0:10, type = \"b\", log = \"x\", xaxl = \"log\",\n#' xaxb = 10^c(1,3,5,7,9))\n#' \n#' #\n#' ## custom function examples\n#' \n#' ## example I: date formatting\n#' \n#' dat = data.frame(\n#' date = seq(as.Date(\"2000/1/1\"), by = \"month\", length.out = 12),\n#' trend = 1:12 + rnorm(12, sd = 1)\n#' )\n#' \n#' tinyplot(trend ~ date, data = dat, xaxl = function(x) format(x, \"%b, %Y\"))\n#' \n#' ## example II: string wrapping \n#' \n#' # create a \"vectorised\" version of `base::strwrap` that breaks long\n#' # strings into new lines every 18 characters\n#' strwrap18 = function(x) sapply(\n#' strwrap(x, width = 18, simplify = FALSE),\n#' paste,\n#' collapse = \"\\n\"\n#' )\n#' \n#' # now demonstrate on a dataset with long y-tick labels\n#' dat2 = data.frame(\n#' x = rep(rnorm(100), 3),\n#' y = c(\n#' \"tinyplot is a lightweight extension of the base R graphics system.\",\n#' \"R is a language for statistical computing.\",\n#' \"Data visualization is an essential skill.\"\n#' )\n#' )\n#' \n#' tinytheme(\"bw\")\n#' tinyplot(y ~ x, data = dat2, type = \"j\", yaxl = strwrap18)\n#' tinytheme()\n#' @export\ntinylabel = function(x, labeller = NULL) {\n if (is.null(labeller)) return(x)\n if (is.character(labeller)) labeller = labeller_fun((labeller))\n return(labeller(x))\n}\n\n\nlabeller_fun = function(label = \"percent\") {\n \n labels = c(\n \"%\" = \"percent\",\n \",\" = \"comma\",\n \"$\" = \"dollar\",\n \"\\u20ac\" = \"euro\",\n \"\\u00a3\" = \"sterling\",\n \"l\" = \"log\"\n )\n if (label %in% names(labels)) label = labels[label]\n \n ## all labels plus absolute value version\n # labels = c(\"percent\", \"comma\", \"dollar\", \"euro\", \"sterling\")\n labels = c(labels, paste0(\"abs_\", labels))\n\n ## match full label first, then store abs_ info separately\n label = match.arg(label, labels)\n abs_ = substr(label, 1L, 4L) == \"abs_\"\n if (abs_) label = substr(label, 5L, nchar(label))\n\n ## actual formatting function\n format_percent = function(x) {\n sprintf(\"%.0f%%\", x * 100)\n }\n \n format_comma = function(x) {\n prettyNum(x, big.mark = \",\", scientific = FALSE)\n }\n \n format_dollar = function(x) {\n paste0(\"$\", prettyNum(x, big.mark = \",\", scientific = FALSE))\n }\n \n format_euro = function(x) {\n paste0(\"\\u20ac\", prettyNum(x, big.mark = \",\", scientific = FALSE))\n }\n \n format_sterling = function(x) {\n paste0(\"\\u00a3\", prettyNum(x, big.mark = \",\", scientific = FALSE))\n }\n \n format_log = function(x) {\n parse(text = paste0(10, \"^\", format(log10(x), digits = 3)))\n }\n \n fun = switch(\n label,\n percent = format_percent,\n comma = format_comma,\n dollar = format_dollar,\n euro = format_euro,\n sterling = format_sterling,\n log = format_log\n )\n\n ## combine with absolute value if necessary\n if (abs_) function(x) fun(abs(x)) else fun\n}\n"], ["/tinyplot/R/type_spineplot.R", "#' Spineplot and spinogram types\n#'\n#' @description Type function(s) for producing spineplots and spinograms, which\n#' are modified versions of histograms or mosaic plots, and particularly\n#' useful for visualizing factor variables. Note that [`tinyplot`] defaults\n#' to `type_spineplot()` if `y` is a factor variable.\n#' @param xlevels,ylevels a character or numeric vector specifying the ordering of the\n#' levels of the `x` and `y` variables (if character) or the corresponding indexes\n#' (if numeric) for the plot.\n#' @inheritParams graphics::spineplot\n#' @examples\n#' # \"spineplot\" type convenience string\n#' tinyplot(Species ~ Sepal.Width, data = iris, type = \"spineplot\")\n#' \n#' # Aside: specifying the type is redundant for this example, since tinyplot()\n#' # defaults to \"spineplot\" if y is a factor (just like base plot).\n#' tinyplot(Species ~ Sepal.Width, data = iris)\n#' \n#' # Use `type_spineplot()` to pass extra arguments for customization\n#' tinyplot(Species ~ Sepal.Width, data = iris, type = type_spineplot(breaks = 4))\n#' \n#' p = palette.colors(3, \"Pastel 1\")\n#' tinyplot(Species ~ Sepal.Width, data = iris, type = type_spineplot(breaks = 4, col = p))\n#' rm(p)\n#' \n#' # More idiomatic tinyplot way of drawing the previous plot: use y == by\n#' tinyplot(\n#' Species ~ Sepal.Width | Species, data = iris, type = type_spineplot(breaks = 4),\n#' palette = \"Pastel 1\", legend = FALSE\n#' )\n#' \n#' # Grouped and faceted spineplots\n#' \n#' ttnc = as.data.frame(Titanic)\n#' \n#' tinyplot(\n#' Survived ~ Sex, facet = ~ Class, data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq)\n#' )\n#' \n#' # For grouped \"by\" spineplots, it's better visually to facet as well\n#' tinyplot(\n#' Survived ~ Sex | Class, facet = \"by\", data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq)\n#' )\n#' \n#' # Fancier version. Note the smart inheritance of spacing etc.\n#' tinyplot(\n#' Survived ~ Sex | Class, facet = \"by\", data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq),\n#' palette = \"Dark 2\", facet.args = list(nrow = 1), axes = \"t\"\n#' )\n#'\n#' # Reorder x and y variable categories either by their character levels or numeric indexes\n#' tinyplot(\n#' Survived ~ Sex, facet = ~ Class, data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq, xlevels = c(\"Female\", \"Male\"), ylevels = 2:1)\n#' )\n#'\n#' # Note: It's possible to use \"by\" on its own (without faceting), but the\n#' # overlaid result isn't great. We will likely overhaul this behaviour in a\n#' # future version of tinyplot...\n#' tinyplot(Survived ~ Sex | Class, data = ttnc,\n#' type = type_spineplot(weights = ttnc$Freq), alpha = 0.3\n#' )\n#' \n#' @export\ntype_spineplot = function(breaks = NULL, tol.ylab = 0.05, off = NULL, xlevels = NULL, ylevels = NULL, col = NULL, xaxlabels = NULL, yaxlabels = NULL, weights = NULL) {\n col = col\n out = list(\n data = data_spineplot(off = off, breaks = breaks, xlevels = xlevels, ylevels = ylevels, xaxlabels = xaxlabels, yaxlabels = yaxlabels, weights = weights),\n draw = draw_spineplot(tol.ylab = tol.ylab, off = off, col = col, xaxlabels = xaxlabels, yaxlabels = yaxlabels),\n name = \"spineplot\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n#' @importFrom grDevices nclass.Sturges\ndata_spineplot = function(off = NULL, breaks = NULL, xlevels = xlevels, ylevels = ylevels, xaxlabels = NULL, yaxlabels = NULL, weights = NULL) {\n fun = function(\n datapoints,\n by = NULL, col = NULL, bg = NULL, palette = NULL,\n facet = NULL, facet.args = NULL,\n xlim = NULL, ylim = NULL,\n axes = TRUE, xaxt = NULL, yaxt = NULL, xaxb = NULL, yaxb = NULL,\n null_by, null_facet, \n ...\n ) {\n \n ## process weights\n if (!is.null(weights)) {\n ny = length(datapoints$y)\n if (length(weights) != ny && length(weights) != 1L) {\n stop(sprintf(\"'weights' must have either length 1 or %s\", ny))\n }\n }\n datapoints$weights = weights\n \n ## process x variable\n if (is.factor(datapoints$x)) {\n breaks = NULL\n off = if(is.null(off)) 0.02 else off/100\n if (is.null(xlim)) xlim = c(0, 1 + (nlevels(datapoints$x) - 1L) * off)\n } else {\n off = 0\n if (is.null(xlim)) xlim = c(0, 1)\n \t x = as.numeric(datapoints$x)\n if (is.null(breaks)) {\n breaks = if (!is.null(xaxb)) xaxb else if (is.null(weights)) nclass.Sturges(x) else ceiling(log2(sum(weights)) + 1)\n\t }\n breaks = as.numeric(breaks)\n if (length(breaks) == 1L) {\n if (!is.numeric(breaks) || !is.finite(breaks) || breaks < 1L) stop(\"invalid number of 'breaks'\")\n if (breaks > 1e6) {\n warning(gettextf(\"'breaks = %g' is too large and set to 1e6\", breaks))\n breaks = 1000000L\n }\n rg = if (is.null(weights)) range(x, na.rm = TRUE) else range(x[weights > 0], na.rm = TRUE)\n breaks = pretty(rg, n = breaks, min.n = 1L) \n }\n }\n\n ## process y variable\n if (!is.factor(datapoints$y)) datapoints$y = factor(datapoints$y)\n if (is.null(ylim)) ylim = c(0, 1)\n\n ## adjust facet margins\n if (!is.null(facet) && is.null(facet.args[[\"fmar\"]])) {\n facet.args[[\"fmar\"]] = c(2, 2, 2, 2)\n }\n \n x_by = identical(datapoints$x, datapoints$by)\n y_by = identical(datapoints$y, datapoints$by)\n \n x.categorical = is.factor(datapoints$x)\n if (!is.null(xlevels) && x.categorical) {\n xlevels = if(is.numeric(xlevels)) levels(datapoints$x)[xlevels] else xlevels\n if (any(is.na(xlevels)) || !all(xlevels %in% levels(datapoints$x))) warning(\"not all 'xlevels' correspond to levels of 'x'\")\n datapoints$x = factor(datapoints$x, levels = xlevels)\n if (x_by) datapoints$by = datapoints$x\n }\n if (!is.null(ylevels)) {\n ylevels = if(is.numeric(ylevels)) levels(datapoints$y)[ylevels] else ylevels\n if (any(is.na(ylevels)) || !all(ylevels %in% levels(datapoints$y))) warning(\"not all 'ylevels' correspond to levels of 'y'\")\n datapoints$y = factor(datapoints$y, levels = ylevels)\n if (y_by) datapoints$by = datapoints$y\n }\n \n x = datapoints$x\n y = datapoints$y\n \n # if either x_by or y_by are TRUE, we'll only split by facets and then\n # use some simple logic to assign colouring on the backend\n if (isTRUE(x_by) || isTRUE(y_by)) {\n datapoints = split(datapoints, list(datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n } else {\n datapoints = split(datapoints, list(datapoints$by, datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n }\n \n # construct spineplot rectangles and breaks points for each by-facet combo\n datapoints = Map(function(dat, x.categorical, off) {\n ## set up frequency table\n x = dat$x\n if(!x.categorical) {\n x = cut(as.numeric(x), breaks = breaks, include.lowest = TRUE)\n }\n ## TODO: process by grouping via: interaction + spacing + labeling\n ## (for now just do interaction)\n ## FIXME: data_facet only contains the first by group?\n ## if (any(dat$by != \"\")) x = interaction(dat$by, x)\n if(is.null(dat$weights)) {\n tab = table(x, dat$y)\n } else {\n tab = as.table(tapply(dat$weights, list(x, dat$y), FUN = sum, na.rm = TRUE))\n tab[is.na(tab)] = 0\n }\n nx = nrow(tab)\n ny = ncol(tab)\n \n ## compute coordinates\n ## cumulative proportions of x (plus off) vs. conditional cumulative proportions of y\n yat = rbind(0, apply(proportions(tab[, ny:1L, drop = FALSE], 1L), 1L, cumsum))\n yat[is.na(yat)] = 1\n xat = c(0, cumsum(proportions(marginSums(tab, 1L)) + off))\n \n ybottom = as.vector(yat[-(ny + 1L),])\n ytop = as.vector(yat[-1L,])\n xleft = rep(xat[1L:nx], rep(ny, nx))\n xright = rep(xat[2L:(nx+1L)] - off, rep(ny, nx))\n \n out = data.frame(\n by = dat$by[1], # already split\n facet = dat$facet[1], # already split\n ymin = ybottom,\n ymax = ytop,\n xmin = xleft,\n xmax = xright\n )\n \n attr(out, \"nx\") = nx\n attr(out, \"ny\") = ny\n attr(out, \"xat\") = xat\n attr(out, \"yat\") = yat\n return(out)\n }, \n dat = datapoints,\n x.categorical = x.categorical,\n off = off\n )\n \n nx = attr(datapoints[[1]], \"nx\") ## should be the same for all by/facet groups\n ny = attr(datapoints[[1]], \"ny\") ## ditto\n xat = lapply(datapoints, attr, \"xat\")\n yat = lapply(datapoints, attr, \"yat\")\n datapoints = do.call(rbind, datapoints)\n \n if (is.null(yaxlabels)) yaxlabels = rev(levels(y))\n \n ## axis labels\n yaxlabels = if(is.null(yaxlabels)) levels(y) else rep_len(yaxlabels, ny)\n if (!is.null(yaxb)) {\n # yaxlabels = yaxlabels[yaxlabels %in% yaxb]\n ## rather use the \"\" assignment workaround below, since otherwise we \n ## get a mismatch between the label names and ticks \n yaxlabels[!(yaxlabels %in% yaxb)] = \"\"\n }\n if(x.categorical) {\n xaxlabels = if(is.null(xaxlabels)) {\n levels(x)\n } else {\n rep_len(xaxlabels, nx)\n }\n } else {\n xaxlabels = if(is.null(xaxlabels)) {\n if(is.numeric(x)) breaks else c(x[1L], x[c(diff(as.numeric(x)) > 0, TRUE)])\n } else {\n rep_len(xaxlabels, nx + 1L)\n }\n }\n \n # catch for x_by / y/by\n if (isTRUE(x_by)) datapoints$by = factor(rep(xaxlabels, each = ny)) # each x label extends over ny rows\n if (isTRUE(y_by)) datapoints$by = factor(rep(yaxlabels, length.out = nrow(datapoints)))\n \n ## grayscale flag\n grayscale = null_by && is.null(palette) && is.null(.tpar[[\"palette.qualitative\"]])\n \n out = list(\n x = c(datapoints$xmin, datapoints$xmax), \n y = c(datapoints$ymin, datapoints$ymax),\n ymin = datapoints$ymin, \n ymax = datapoints$ymax, \n xmin = datapoints$xmin, \n xmax = datapoints$xmax, \n col = col,\n bg = bg,\n datapoints = datapoints,\n by = if (null_by) by else datapoints$by, \n facet = if (null_facet) facet else datapoints$facet,\n axes = FALSE,\n frame.plot = FALSE,\n xaxt = \"n\",\n yaxt = \"n\",\n xaxs = \"i\",\n yaxs = \"i\",\n ylabs = yaxlabels,\n type_info = list(\n off = off,\n x.categorical = x.categorical,\n nx = nx,\n ny = ny,\n xat = xat,\n yat = yat,\n xaxlabels = xaxlabels,\n yaxlabels = yaxlabels,\n breaks = breaks,\n axes = axes,\n xaxt = xaxt, \n yaxt = yaxt,\n grayscale = grayscale,\n x_by = x_by,\n y_by = y_by\n ),\n facet.args = facet.args\n )\n \n return(out)\n \n }\n return(fun)\n}\n\n#' @importFrom grDevices gray.colors\ndraw_spineplot = function(tol.ylab = 0.05, off = NULL, col = NULL, xaxlabels = NULL, yaxlabels = NULL) {\n fun = function(ixmin, iymin, ixmax, iymax, ilty, ilwd, icol, ibg, \n flip,\n facet_window_args,\n type_info,\n ifacet,\n ...) {\n \n if (is.null(off)) off = type_info[[\"off\"]]\n if (is.null(xaxlabels)) xaxlabels = type_info[[\"xaxlabels\"]]\n if (is.null(yaxlabels)) yaxlabels = type_info[[\"yaxlabels\"]]\n xat = type_info[[\"xat\"]][[ifacet]]\n yat = type_info[[\"yat\"]][[ifacet]]\n nx = type_info[[\"nx\"]]\n ny = type_info[[\"ny\"]]\n x.categorical = type_info[[\"x.categorical\"]]\n grayscale = type_info[[\"grayscale\"]]\n x_by = type_info[[\"x_by\"]]\n y_by = type_info[[\"y_by\"]]\n \n ## graphical parameters\n if (is.null(col)) {\n if (is.null(ibg)) ibg = icol\n if (isFALSE(y_by)) {\n ibg = if (isTRUE(grayscale)) gray.colors(ny) else seq_palette(ibg, ny)\n }\n ibg = rep_len(ibg, ny)\n } else {\n ibg = col\n }\n \n if (type_info[[\"xaxt\"]] %in% c(\"l\", \"t\", \"n\") &&\n type_info[[\"yaxt\"]] %in% c(\"l\", \"t\", \"n\") &&\n !all(c(type_info[[\"xaxt\"]], type_info[[\"yaxt\"]]) == \"n\")) ilwd = 0\n \n rect(\n xleft = ixmin, ybottom = iymin, xright = ixmax, ytop = iymax,\n lty = ilty,\n lwd = ilwd,\n border = par(\"fg\"), #icol,\n col = ibg\n )\n \n ## axes\n ## - standard categorical axes (xaxt/yaxt == \"s\") _without_ ticks\n ## - never draw additional axis lines, box always for spinogram\n if(type_info[[\"axes\"]]) {\n if (x.categorical) {\n spine_axis(if (flip) 2 else 1, at = (xat[1L:nx] + xat[2L:(nx+1L)] - off)/2, labels = xaxlabels,\n type = type_info[[\"xaxt\"]], categorical = TRUE)\n } else {\n spine_axis(if (flip) 2 else 1, at = xat, labels = xaxlabels,\n type = type_info[[\"xaxt\"]], categorical = FALSE)\n }\n yat = yat[, if(flip) ncol(yat) else 1L]\n equidist = any(diff(yat) < tol.ylab)\n yat = if(equidist) seq.int(1/(2*ny), 1-1/(2*ny), by = 1/ny) else (yat[-1L] + yat[-length(yat)])/2\n spine_axis(if (flip) 3 else 2, at = yat, labels = yaxlabels,\n type = type_info[[\"yaxt\"]], categorical = TRUE)\n if (is_facet_position(if(flip) \"bottom\" else \"right\", ifacet, facet_window_args)) spine_axis(if (flip) 1 else 4,\n type = type_info[[\"yaxt\"]], categorical = FALSE)\n }\n if(!x.categorical && (is.null(ilwd) || ilwd > 0)) box()\n \n }\n return(fun)\n}\n\n\n\n\nspine_axis = function(side, ..., type = \"standard\", categorical = TRUE) {\n type = match.arg(type, c(\"standard\", \"none\", \"labels\", \"ticks\", \"axis\"))\n ## standard: with axis, ticks (unless categorical), and labels\n ## none: no axes\n ## labels: only labels without ticks and axis line\n ## ticks: only ticks and labels without axis line\n ## axis: only axis line and labels but no ticks\n\n if (type == \"none\") {\n invisible(numeric(0L))\n } else {\n args = list(side = side, ...)\n if (type == \"labels\") {\n args$tick = FALSE\n } else if (type == \"ticks\") {\n args$lwd = 0\n if (!(\"lwd.ticks\" %in% names(args))) args$lwd.ticks = if (categorical) 0 else 1\n } else if (type == \"axis\") {\n if (categorical) {\n args$tick = FALSE\n } else {\n args$lwd.ticks = 0\n }\n } else {\n args$tick = !categorical\n }\n do.call(\"axis\", args)\n }\n}\n\n#' @importFrom grDevices col2rgb convertColor hcl\nto_hcl = function(x) {\n x = t(col2rgb(x, alpha = TRUE)/255)\n alpha = x[, 4]\n x = x[, 1:3]\n x = convertColor(x, from = \"sRGB\", to = \"Luv\")\n x = cbind(H = atan2(x[, 3L], x[, 2L]) * 180/pi, C = sqrt(x[, 2L]^2 + x[, 3L]^2), L = x[, 1L])\n x[is.na(x[, 1L]), 1L] = 0\n x[x[, 1L] < 0, 1L] = x[x[, 1L] < 0, 1L] + 360\n attr(x, \"alpha\") = alpha\n return(x)\n}\n\nseq_palette = function(x, n, power = 1.5) {\n x = drop(to_hcl(x[1L]))\n alpha = attr(x, \"alpha\")\n hcl(\n h = x[1L],\n c = seq.int(from = x[2L]^(1/power), to = 0, length.out = n + 1)[1L:n]^power,\n l = 100 - seq.int(from = (100 - x[3L])^(1/power), to = pmin(8, (100 - x[3L])/2)^(1/power), length.out = n)^power,\n alpha = alpha\n )[1L:n]\n}\n"], ["/tinyplot/R/type_rug.R", "#' Add a rug to a plot\n#' \n#' @description\n#' Adds a rug representation (1-d plot) of the data to the plot.\n#' \n#' @details\n#' This function should only be used as part of [`tinyplot_add()`], i.e. adding\n#' to an existing plot.\n#' \n#' In most cases, determining which variable receives the rug representation\n#' will be based on the `side` argument (i.e., x-variable if side is 1 or 3, and\n#' y-variable if side is 2 or 4). An exception is if the preceding plot type was\n#' either `\"density\"` or `\"histogram\"`; for these latter cases, the x-variable\n#' will always be used. See Examples.\n#' \n#' @inheritParams graphics::rug\n#' @param jitter Logical. Add jittering to separate ties? Default is `FALSE`.\n#' @param amount Numeric. Amount of jittering (see \\code{\\link[base]{jitter}}).\n#' Only used if `jitter` is `TRUE`.\n#' @examples\n#' tinyplot(~wt | am, data = mtcars, type = \"density\", facet = \"by\", fill = \"by\")\n#' tinyplot_add(type = \"rug\")\n#' # use type_rug() to pass extra options\n#' tinyplot_add(type = type_rug(side = 3, ticksize = 0.05))\n#' \n#' # For ties, use jittering\n#' tinyplot(eruptions ~ waiting, data = faithful, type = \"lm\")\n#' tinyplot_add(type = type_rug(jitter = TRUE, amount = 0.3))\n#' tinyplot_add(type = type_rug(jitter = TRUE, amount = 0.1, side = 2))\n#' # Add original points just for reference\n#' tinyplot_add(type = \"p\")\n#' \n#' @importFrom graphics rug\n#' @export\ntype_rug = function(ticksize = 0.03, side = 1, quiet = getOption(\"warn\") < 0, jitter = FALSE, amount = NULL) {\n data_rug = function(datapoints, ...) {\n if (nrow(datapoints) == 0) {\n msg = \"`type_rug() only works on existing plots with x and y data points.\"\n stop(msg, call. = FALSE)\n }\n return(datapoints)\n }\n draw_rug = function(.ticksize = ticksize, .side = side, .quiet = quiet, .jitter = jitter, .amount = amount) {\n fun = function(ix, iy, icol, ilwd, ...) {\n lc = getOption(\"tinyplot_last_call\", default = NULL)\n swapy = !is.null(lc$type) && lc$type %in% c(\"density\", \"hist\", \"histogram\")\n rugx = if (swapy) iy else if (side %in% c(1, 3)) ix else iy\n if (isTRUE(jitter)) rugx = jitter(rugx, amount = .amount)\n rug(\n x = rugx,\n col = icol,\n lwd = ilwd,\n ticksize = .ticksize,\n side = .side,\n quiet = .quiet\n )\n }\n return(fun)\n }\n\n out = list(\n draw = draw_rug(),\n data = data_rug,\n name = \"rug\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_violin.R", "#' Violin plot type\n#' \n#' @md\n#' @description Type function for violin plots, which are an alternative to box\n#' plots for visualizing continuous distributions (by group) in the form of\n#' mirrored densities.\n#' @inheritParams type_density\n#' @param trim logical indicating whether the violins should be trimmed to the\n#' range of the data. Default is `FALSE`.\n#' @param width numeric (ideally in the range `[0, 1]`, although this isn't\n#' enforced) giving the normalized width of the individual violins.\n#' @inherit stats::density details\n#' @details See [`type_density`] for more details and considerations related to\n#' bandwidth selection and kernel types.\n#' \n#' @examples\n#' # \"violin\" type convenience string\n#' tinyplot(count ~ spray, data = InsectSprays, type = \"violin\")\n#' \n#' # aside: to match the defaults of `ggplot2::geom_violin()`, use `trim = TRUE`\n#' # and `joint.bw = FALSE`\n#' tinyplot(count ~ spray, data = InsectSprays, type = \"violin\",\n#' trim = TRUE, joint.bw = FALSE)\n#' \n#' # use flip = TRUE to reorient the axes\n#' tinyplot(count ~ spray, data = InsectSprays, type = \"violin\", flip = TRUE)\n#' \n#' # for flipped plots with long group labels, it's better to use a theme for\n#' # dynamic plot resizing\n#' tinytheme(\"clean\")\n#' tinyplot(weight ~ feed, data = chickwts, type = \"violin\", flip = TRUE)\n#' \n#' # you can group by the x var to add colour (here with the original orientation)\n#' tinyplot(weight ~ feed | feed, data = chickwts, type = \"violin\", legend = FALSE)\n#' \n#' # dodged grouped violin plot example (different dataset)\n#' tinyplot(len ~ dose | supp, data = ToothGrowth, type = \"violin\", fill = 0.2)\n#' \n#' # note: above we relied on `...` argument passing alongside the \"violin\"\n#' # type convenience string. But this won't work for `width`, since it will\n#' # clash with the top-level `tinyplot(..., width = )` arg. To ensure\n#' # correct arg passing, it's safer to use the formal `type_violin()` option.\n#' tinyplot(len ~ dose | supp, data = ToothGrowth, fill = 0.2,\n#' type = type_violin(width = 0.8))\n#' \n#' # reset theme\n#' tinytheme()\n#' \n#' @importFrom stats density weighted.mean\n#' @importFrom stats bw.SJ bw.bcv bw.nrd bw.nrd0 bw.ucv \n#' @export\ntype_violin = function(\n bw = \"nrd0\",\n joint.bw = c(\"mean\", \"full\", \"none\"),\n adjust = 1,\n kernel = c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"),\n n = 512,\n # more args from density here?\n trim = FALSE,\n width = 0.9\n ) {\n kernel = match.arg(kernel, c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"))\n if (is.logical(joint.bw)) {\n joint.bw = ifelse(joint.bw, \"mean\", \"none\")\n }\n joint.bw = match.arg(joint.bw, c(\"mean\", \"full\", \"none\"))\n out = list(\n data = data_violin(bw = bw, adjust = adjust, kernel = kernel, n = n,\n joint.bw = joint.bw, trim = trim, width = width),\n # draw = NULL,\n # name = \"polygon\"\n draw = draw_polygon(density = NULL),\n name = \"violin\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\ndata_violin = function(bw = \"nrd0\", adjust = 1, kernel = \"gaussian\", n = 512,\n joint.bw = \"none\", trim = FALSE, width = 0.9) {\n fun = function(datapoints, by, facet, ylab, col, bg, palette, log, null_by, null_facet, ...) {\n \n # Handle ordering based on by and facet variables\n ngrps = if (null_by) 1 else length(unique(datapoints$by))\n nfacets = if (null_facet) 1 else length(unique(datapoints$facet))\n \n # catch for special cases\n x_by = y_by = facet_by = FALSE\n if (!null_by) {\n x_by = identical(datapoints$x, datapoints$by)\n y_by = identical(datapoints$y, datapoints$by)\n if (!null_facet) facet_by = identical(datapoints$facet, datapoints$by)\n }\n \n # FIXME (once we add support for gradient fill to draw_polygon)\n if (y_by) {\n warning(\"\\n`y` == `by` is not currently supported for `type_violin`. We hope to support this in a future release, but for now `y` grouping will be turned off automatically.\\n\")\n by = NULL\n datapoints$by = \"\"\n ngrps = 1\n null_by = TRUE\n }\n \n # Convert x to factor if it's not already\n datapoints$x = as.factor(datapoints$x)\n if (x_by) datapoints$by = datapoints$x\n\n # Handle factor levels and maintain order\n xlvls = levels(datapoints$x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n # xlabs = levels(datapoints$x)\n datapoints$x = as.integer(datapoints$x)\n\n if (null_by && null_facet) {\n xord = order(datapoints$x)\n } else if (null_facet) {\n xord = order(datapoints$by, datapoints$x)\n } else if (null_by) {\n xord = order(datapoints$facet, datapoints$x)\n } else {\n xord = order(datapoints$by, datapoints$facet, datapoints$x)\n }\n\n if (length(unique(datapoints[[\"by\"]])) == 1 && is.null(palette)) {\n if (is.null(col)) col = par(\"fg\")\n if (is.null(bg)) bg = \"lightgray\"\n } else if (is.null(bg)) {\n bg = \"by\"\n }\n\n # Reorder x, y, ymin, and ymax based on the order determined\n datapoints = datapoints[xord,]\n\n \n datapoints = split(datapoints, list(datapoints$x, datapoints$by, datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n \n if (joint.bw == \"none\" || is.numeric(bw)) {\n dens_bw = bw\n } else {\n if (joint.bw == \"mean\") {\n # Use weighted mean of subgroup bandwidths\n bws = sapply(datapoints, function(dat) bw_fun(kernel = bw, dat$y))\n ws = sapply(datapoints, nrow)\n dens_bw = weighted.mean(bws, ws)\n } else if (joint.bw == \"full\") {\n dens_bw = bw_fun(kernel = bw, unlist(sapply(datapoints, `[[`, \"x\")))\n }\n }\n \n datapoints = lapply(seq_along(datapoints), function(d) {\n dat = datapoints[[d]]\n if (trim) {\n yrng = range(dat$y)\n dens = density(dat$y, bw = dens_bw, kernel = kernel, n = n, from = yrng[1], to = yrng[2])\n } else {\n dens = density(dat$y, bw = dens_bw, kernel = kernel, n = n)\n }\n \n x = dens$y\n y = dens$x\n \n \n if (log %in% c(\"y\", \"xy\")) {\n if (x[1] <= 0) {\n warning(\"\\nNon-positive density values have been trimmed as part of the logarthmic transformation.\\n\")\n xidx = x > 0\n x = x[xidx]\n y = y[xidx]\n } \n }\n \n x = c(x, rev(-x))\n y = c(y, rev(y))\n \n xwidth = xwidth_orig = width\n # dodge groups (if any)\n if ((ngrps > 1) && isFALSE(x_by) && isFALSE(facet_by)) {\n xwidth = xwidth_orig / ngrps - 0.01\n x = rescale_num(x, to = c(0, xwidth))\n x = x + as.numeric(sub(\"^([0-9]+)\\\\..*\", \"\\\\1\", names(datapoints)[d])) - xwidth/2\n x = x + seq(-((xwidth_orig - xwidth) / 2), ((xwidth_orig - xwidth) / 2), length.out = ngrps)[dat$by[1]]\n } else if (nfacets > 1) {\n x = rescale_num(x, to = c(0, xwidth))\n x = x + as.numeric(sub(\"^([0-9]+)\\\\..*\", \"\\\\1\", names(datapoints)[d])) - xwidth/2\n } else {\n x = rescale_num(x, to = c(0, xwidth))\n x = x + d - xwidth/2\n }\n \n x = c(x, NA)\n y = c(y, NA)\n \n out = data.frame(\n by = dat$by[1], # already split\n facet = dat$facet[1], # already split\n y = y,\n x = x\n )\n return(out)\n })\n datapoints = do.call(rbind, datapoints)\n datapoints = datapoints[1:(nrow(datapoints)-1), ]\n \n out = list(\n datapoints = datapoints,\n by = if (length(unique(datapoints$by)) == 1) by else datapoints$by, \n facet = if (length(unique(datapoints$facet)) == 1) facet else datapoints$facet,\n ylab = ylab,\n xlabs = xlabs,\n col = col,\n bg = bg\n )\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_density.R", "#' Density plot type\n#' \n#' @md\n#' @description Type function for density plots.\n#' @inheritParams stats::density\n#' @param kernel a character string giving the smoothing kernel to be used. This\n#' must partially match one of `\"gaussian\"`, `\"rectangular\"`, `\"triangular\"`,\n#' `\"epanechnikov\"`, `\"biweight\"`, `\"cosine\"` or `\"optcosine\"`, with default\n#' `\"gaussian\"`, and may be abbreviated to a unique prefix (single letter).\n#'\n#' `\"cosine\"` is smoother than `\"optcosine\"`, which is the usual 'cosine'\n#' kernel in the literature and almost MSE-efficient. However, `\"cosine\"` is\n#' the version used by S.\n#' @inheritParams type_ribbon\n#' @param joint.bw character string indicating whether (and how) the smoothing\n#' bandwidth should be computed from the joint data distribution when there\n#' are multiple subgroups. The options are `\"mean\"` (the default), `\"full\"`,\n#' and `\"none\"`. Also accepts a logical argument, where `TRUE` maps to\n#' `\"mean\"` and `FALSE` maps to `\"none\"`. See the \"Bandwidth selection\"\n#' section below for a discussion of practical considerations.\n#' @inherit stats::density details\n#' @section Bandwidth selection: While the choice of smoothing bandwidth will\n#' always stand to affect a density visualization, it gains an added\n#' importance when multiple densities are drawn simultaneously (e.g., for\n#' subgroups with respect to `by` or `facet`). Allowing each subgroup to\n#' compute its own separate bandwidth independently offers greater flexibility\n#' in capturing the unique characteristics of each subgroup, particularly when\n#' distributions differ substantially in location and/or scale. However, this\n#' approach may overemphasize small random variations and make it harder to\n#' visually compare densities across subgroups. Hence, it is often useful to\n#' employ the same (\"joint\") bandwidth across all subgroups. The following\n#' strategies are available via the `joint.bw` argument:\n#' \n#' - The default `joint.bw = \"mean\"` first computes the individual bandwidths\n#' for each group but then computes their mean, weighted by the number of\n#' observations in each group. This will work well when all groups have\n#' similar amounts of scatter (similar variances), even when they have\n#' potentially rather different locations. The weighted averaging stabilizes\n#' potential fluctuations in the individual bandwidths, especially when some\n#' subgroups are rather small.\n#' \n#' - Alternatively, `joint.bw = \"full\"` can be used to compute the joint\n#' bandwidth from the full joint distribution (merging all groups). This will\n#' yield an even more robust bandwidth, especially when the groups overlap\n#' substantially (i.e., have similar locations and scales). However, it may\n#' lead to too large bandwidths and thus too much smoothing, especially when\n#' the locations of the groups differ substantially.\n#' \n#' - Finally, `joint.bw = \"none\"` disables the joint bandwidth so that each\n#' group just employs its individual bandwidth. This is often the best choice\n#' if the amounts of scatter differ substantially between the groups, thus\n#' necessitating different amounts of smoothing.\n#' @section Titles: This tinyplot method for density plots differs from the base\n#' \\code{\\link[stats]{plot.density}} function in its treatment of titles. The\n#' x-axis title displays only the variable name, omitting details about the\n#' number of observations and smoothing bandwidth. Additionally, the main\n#' title is left blank by default for a cleaner appearance.\n#' @examples\n#' # \"density\" type convenience string\n#' tinyplot(~Sepal.Length, data = iris, type = \"density\")\n#' \n#' # grouped density example\n#' tinyplot(~Sepal.Length | Species, data = iris, type = \"density\")\n#' \n#' # use `bg = \"by\"` (or, equivalent `fill = \"by\"`) to get filled densities\n#' tinyplot(~Sepal.Length | Species, data = iris, type = \"density\", fill = \"by\")\n#' \n#' # use `type_density()` to pass extra arguments for customization\n#' tinyplot(\n#' ~Sepal.Length | Species, data = iris,\n#' type = type_density(bw = \"SJ\"),\n#' main = \"Bandwidth computed using Sheather & Jones (1991)\"\n#' )\n#' \n#' # The default for grouped density plots is to use the mean of the\n#' # individual subgroup bandwidths (weighted by group size) as the\n#' # joint bandwidth. Alternatively, the bandwidth from the \"full\"\n#' # data or separate individual bandwidths (\"none\") can be used.\n#' tinyplot(~Sepal.Length | Species, data = iris,\n#' ylim = c(0, 1.25), type = \"density\") # mean (default)\n#' tinyplot_add(joint.bw = \"full\", lty = 2) # full data\n#' tinyplot_add(joint.bw = \"none\", lty = 3) # none (individual)\n#' legend(\"topright\", c(\"Mean\", \"Full\", \"None\"), lty = 1:3, bty = \"n\", title = \"Joint BW\")\n#' \n#' @importFrom stats density weighted.mean\n#' @importFrom stats bw.SJ bw.bcv bw.nrd bw.nrd0 bw.ucv \n#' @export\ntype_density = function(\n bw = \"nrd0\",\n joint.bw = c(\"mean\", \"full\", \"none\"),\n adjust = 1,\n kernel = c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"),\n n = 512,\n # more args from density here?\n alpha = NULL\n ) {\n kernel = match.arg(kernel, c(\"gaussian\", \"epanechnikov\", \"rectangular\", \"triangular\", \"biweight\", \"cosine\", \"optcosine\"))\n if (is.logical(joint.bw)) {\n joint.bw = ifelse(joint.bw, \"mean\", \"none\")\n }\n joint.bw = match.arg(joint.bw, c(\"mean\", \"full\", \"none\"))\n out = list(\n data = data_density(bw = bw, adjust = adjust, kernel = kernel, n = n,\n joint.bw = joint.bw, alpha = alpha),\n draw = NULL,\n name = \"density\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\ndata_density = function(bw = \"nrd0\", adjust = 1, kernel = \"gaussian\", n = 512,\n joint.bw = \"none\", alpha = NULL) {\n fun = function(by, facet, ylab, col, bg, ribbon.alpha, datapoints, ...) {\n \n ribbon.alpha = if (is.null(alpha)) .tpar[[\"ribbon.alpha\"]] else (alpha)\n \n if (is.null(ylab)) ylab = \"Density\"\n \n datapoints = split(datapoints, list(datapoints$by, datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n \n if (joint.bw == \"none\" || is.numeric(bw)) {\n dens_bw = bw\n } else {\n if (joint.bw == \"mean\") {\n # Use weighted mean of subgroup bandwidths\n bws = sapply(datapoints, function(dat) bw_fun(kernel = bw, dat$x))\n ws = sapply(datapoints, nrow)\n dens_bw = weighted.mean(bws, ws)\n } else if (joint.bw == \"full\") {\n dens_bw = bw_fun(kernel = bw, unlist(sapply(datapoints, `[[`, \"x\")))\n }\n }\n \n datapoints = lapply(datapoints, function(dat) {\n d = density(dat$x, bw = dens_bw, kernel = kernel, n = n)\n out = data.frame(\n by = dat$by[1], # already split\n facet = dat$facet[1], # already split\n y = d$y,\n x = d$x\n )\n return(out)\n })\n datapoints = do.call(rbind, datapoints)\n datapoints$ymax = datapoints$y\n datapoints$ymin = rep.int(0, nrow(datapoints))\n \n # flags for legend and fill\n dtype = if (!is.null(bg)) \"ribbon\" else \"l\"\n dwas_area_type = !is.null(bg)\n \n out = list(\n ylab = ylab,\n type = dtype,\n was_area_type = dwas_area_type,\n ribbon.alpha = ribbon.alpha,\n datapoints = datapoints,\n by = if (length(unique(datapoints$by)) == 1) by else datapoints$by, \n facet = if (length(unique(datapoints$facet)) == 1) facet else datapoints$facet\n )\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_boxplot.R", "#' Boxplot type\n#' \n#' @description Type function for producing box-and-whisker plots.\n#' Arguments are passed to \\code{\\link[graphics]{boxplot}}, although `tinyplot`\n#' scaffolding allows added functionality such as grouping and faceting.\n#' Box-and-whisker plots are the default plot type if `x` is a factor and `y` is\n#' numeric.\n#'\n#' @inheritParams graphics::boxplot\n#' @examples\n#' # \"boxplot\" type convenience string\n#' tinyplot(count ~ spray, data = InsectSprays, type = \"boxplot\")\n#' \n#' # Note: Specifying the type here is redundant. Like base plot, tinyplot\n#' # automatically produces a boxplot if x is a factor and y is numeric\n#' tinyplot(count ~ spray, data = InsectSprays)\n#' \n#' # Grouped boxplot example\n#' tinyplot(len ~ dose | supp, data = ToothGrowth, type = \"boxplot\")\n#' \n#' # Use `type_boxplot()` to pass extra arguments for customization\n#' tinyplot(\n#' len ~ dose | supp, data = ToothGrowth, lty = 1,\n#' type = type_boxplot(boxwex = 0.3, staplewex = 0, outline = FALSE)\n#' )\n#' @export\ntype_boxplot = function(\n range = 1.5,\n width = NULL,\n varwidth = FALSE,\n notch = FALSE,\n outline = TRUE,\n boxwex = 0.8,\n staplewex = 0.5,\n outwex = 0.5) {\n out = list(\n draw = draw_boxplot(\n range = range,\n width = width,\n varwidth = varwidth,\n notch = notch,\n outline = outline,\n boxwex = boxwex,\n staplewex = staplewex,\n outwex = outwex),\n data = data_boxplot(),\n name = \"boxplot\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\n\ndraw_boxplot = function(range, width, varwidth, notch, outline, boxwex, staplewex, outwex) {\n fun = function(iby, ix, iy, ipch, ilty, icol, ibg, x_by = FALSE, facet_by = FALSE, ngrps = 1, flip, ...) {\n\n at_ix = unique(ix)\n if (isTRUE(x_by)) boxwex = boxwex * 2\n\n # Handle multiple groups\n if (ngrps > 1 && isFALSE(x_by) && isFALSE(facet_by)) {\n boxwex_orig = boxwex\n boxwex = boxwex / ngrps - 0.01\n at_ix = at_ix + seq(\n -((boxwex_orig - boxwex) / 2),\n ((boxwex_orig - boxwex) / 2),\n length.out = ngrps\n )[iby]\n }\n\n boxplot(\n formula = iy ~ ix,\n pch = ipch,\n lty = ilty,\n border = icol,\n col = ibg,\n horizontal = flip,\n add = TRUE, axes = FALSE,\n at = at_ix,\n range = range,\n width = width,\n varwidth = varwidth,\n notch = notch,\n outline = outline,\n boxwex = boxwex,\n staplewex = staplewex,\n outwex = outwex\n )\n }\n return(fun)\n}\n\n\n\ndata_boxplot = function() {\n fun = function(datapoints, bg, col, palette, null_by, null_facet, ...) {\n # Convert x to factor if it's not already\n datapoints$x = as.factor(datapoints$x)\n\n # Handle factor levels and maintain order\n xlvls = levels(datapoints$x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n datapoints$x = as.integer(datapoints$x)\n\n if (null_by && null_facet) {\n xord = order(datapoints$x)\n } else if (null_facet) {\n xord = order(datapoints$by, datapoints$x)\n } else if (null_by) {\n xord = order(datapoints$facet, datapoints$x)\n } else {\n xord = order(datapoints$by, datapoints$facet, datapoints$x)\n }\n\n if (length(unique(datapoints[[\"by\"]])) == 1 && is.null(palette)) {\n if (is.null(col)) col = par(\"fg\")\n if (is.null(bg)) bg = \"lightgray\"\n } else {\n bg = \"by\"\n }\n\n # Reorder x, y, ymin, and ymax based on the order determined\n datapoints = datapoints[xord,]\n\n # Return the result as a list called 'out'\n out = list(\n x = datapoints$x,\n y = datapoints$y,\n ymin = datapoints$ymin,\n ymax = datapoints$ymax,\n xlabs = xlabs,\n datapoints = datapoints,\n col = col,\n bg = bg)\n\n if (length(unique(datapoints$by)) > 1) out[[\"by\"]] = datapoints$by\n if (length(unique(datapoints$facet)) > 1) out[[\"facet\"]] = datapoints$facet\n\n return(out)\n }\n return(fun)\n}\n\n\n\n\n"], ["/tinyplot/R/type_histogram.R", "#' Histogram plot type\n#' \n#' @md\n#' @description Type function for histogram plots. `type_hist` is an alias for\n#' `type_histogram`.\n#' @param breaks Passed to \\code{\\link[graphics]{hist}}. One of:\n#' - a vector giving the breakpoints between histogram cells,\n#' - a function to compute the vector of breakpoints,\n#' - a single number giving the number of cells for the histogram,\n#' - a character string naming an algorithm to compute the number of cells (see ‘Details’ of \\code{\\link[graphics]{hist}}),\n#' - a function to compute the number of cells.\n#' In the last three cases the number is a suggestion only; as the breakpoints\n#' will be set to pretty values, the number is limited to 1e6 (with a warning if\n#' it was larger). If breaks is a function, the x vector is supplied to it as\n#' the only argument (and the number of breaks is only limited by the amount of\n#' available memory).\n#' @param free.breaks Logical indicating whether the breakpoints should be\n#' computed separately for each group or facet? Default is `FALSE`, meaning\n#' that the breakpoints are computed from the full dataset; thus ensuring\n#' common bin widths across each group/facet. Can also use `free` as an\n#' acceptable argument alias. Ignored if there are no groups and/or facets.\n#' @param drop.zeros Logical indicating whether bins with zero counts should be\n#' dropped before plotting. Default is `TRUE`. Note that switching to `FALSE`\n#' may interfere with faceted plot behaviour if `facet.args = list(free)`,\n#' since the `x` variable is effectively recorded over the full range of the\n#' x-axis (even if it does not extend over this range for every group).\n#' @inheritParams graphics::hist\n#' @examples\n#' # \"histogram\"/\"hist\" type convenience string(s)\n#' tinyplot(Nile, type = \"histogram\")\n#' \n#' # Use `type_histogram()` to pass extra arguments for customization\n#' tinyplot(Nile, type = type_histogram(breaks = 30))\n#' tinyplot(Nile, type = type_histogram(breaks = 30, freq = FALSE))\n#' # etc.\n#' \n#' # Grouped histogram example\n#' tinyplot(\n#' ~Petal.Width | Species,\n#' type = \"histogram\",\n#' data = iris\n#' )\n#' \n#' # Faceted version\n#' tinyplot(\n#' ~Petal.Width, facet = ~Species,\n#' type = \"histogram\",\n#' data = iris\n#' )\n#' \n#' # For visualizing faceted histograms across varying scales, you may also wish\n#' # to impose free histogram breaks too (i.e., calculate breaks separately for\n#' # each group). Compare:\n#' \n#' # free facet scales + shared histogram breaks, versus...\n#' tinyplot(\n#' ~Petal.Width, facet = ~Species,\n#' facet.args = list(free = TRUE),\n#' type = type_histogram(),\n#' data = iris\n#' )\n#' # ... free facet scales + free histogram breaks\n#' tinyplot(\n#' ~Petal.Width, facet = ~Species,\n#' facet.args = list(free = TRUE),\n#' type = type_histogram(free = TRUE),\n#' data = iris\n#' )\n#' \n#' @export\ntype_histogram = function(breaks = \"Sturges\",\n freq = NULL, right = TRUE,\n free.breaks = FALSE, drop.zeros = TRUE) {\n out = list(\n data = data_histogram(breaks = breaks,\n free.breaks = free.breaks, drop.zeros = drop.zeros,\n freq = freq, right = right),\n draw = draw_rect(),\n name = \"histogram\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n#' @export\n#' @name type_hist\n#' @rdname type_histogram\ntype_hist = type_histogram\n\n\ndata_histogram = function(breaks = \"Sturges\",\n free.breaks = FALSE, drop.zeros = TRUE,\n freq = NULL, right = TRUE) {\n \n hbreaks = breaks\n hfree.breaks = free.breaks\n hdrop.zeros = drop.zeros\n hfreq = freq\n hright = right\n \n fun = function(by, facet, ylab, col, bg, ribbon.alpha, datapoints, .breaks = hbreaks, .freebreaks = hfree.breaks, .freq = hfreq, .right = hright, .drop.zeros = hdrop.zeros, ...) {\n \n hbreaks = ifelse(!sapply(.breaks, is.null), .breaks, \"Sturges\")\n \n if (is.null(by) && is.null(palette)) {\n if (is.null(col)) col = par(\"fg\")\n if (is.null(bg)) bg = \"lightgray\"\n } else {\n if (is.null(bg)) bg = ribbon.alpha\n }\n\n if (!.freebreaks) xbreaks = hist(datapoints$x, breaks = hbreaks, right = .right, plot = FALSE)$breaks\n datapoints = split(datapoints, list(datapoints$by, datapoints$facet))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n \n datapoints = lapply(datapoints, function(k) {\n if (.freebreaks) xbreaks = breaks\n h = hist(k$x, breaks = xbreaks, right = .right, plot = FALSE)\n # zero count cases\n if (.drop.zeros) {\n nzidx = which(h$counts > 0)\n h$density = h$density[nzidx]\n h$counts = h$counts[nzidx]\n h$breaks = h$breaks[c(1, nzidx+1)]\n h$mids = h$mids[nzidx]\n }\n freq = if(!is.null(.freq)) .freq else is.null(.freq) && h$equidist\n out = data.frame(\n by = k$by[1], # already split\n facet = k$facet[1], # already split\n ymin = 0,\n ymax = if (freq) h$counts else h$density,\n xmin = h$breaks[-1],\n xmax = h$mids + (h$mids - h$breaks[-1]),\n freq = freq\n )\n return(out)\n })\n datapoints = do.call(rbind, datapoints)\n \n if (is.null(ylab)) {\n ylab = ifelse(datapoints$freq[1], \"Frequency\", \"Density\")\n }\n\n out = list(\n x = c(datapoints$xmin, datapoints$xmax), \n y = c(datapoints$ymin, datapoints$ymax),\n ymin = datapoints$ymin, \n ymax = datapoints$ymax, \n xmin = datapoints$xmin, \n xmax = datapoints$xmax, \n ylab = ylab, \n col = col, \n bg = bg, \n datapoints = datapoints,\n by = if (length(unique(datapoints$by)) == 1) by else datapoints$by, \n facet = if (length(unique(datapoints$facet)) == 1) facet else datapoints$facet\n )\n return(out)\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_qq.R", "#' Quantile-Quantile plot (QQ)\n#'\n#' @description Plots the theoretical quantiles of `x` on the horizontal axis\n#' against observed values of `x` on the vertical axis.\n#'\n#' @param distribution Distribution function to use.\n#' @examples\n#' tinyplot(~mpg, data = mtcars, type = type_qq())\n#'\n#' # suppress the line\n#' tinyplot(~mpg, data = mtcars, lty = 0, type = type_qq())\n#' @importFrom stats qnorm ppoints quantile\n#' @export\ntype_qq = function(distribution = qnorm) {\n data_qq = function(distribution) {\n fun = function(datapoints, ...) {\n y = sort(datapoints$y)\n x = datapoints$x\n x = distribution(ppoints(x))\n datapoints$x = x\n datapoints$y = y\n out = list(datapoints = datapoints)\n return(out)\n }\n }\n\n draw_qq = function() {\n fun = function(ix, iy, icol, ibg, ipch, ilwd, ilty, cex, xlab, ...) {\n points(\n x = ix,\n y = iy,\n col = icol,\n bg = ibg,\n type = \"p\",\n pch = ipch,\n lwd = ilwd,\n cex = cex\n )\n\n if (!is.null(ilty)) {\n iy <- quantile(iy, c(0.25, 0.75))\n ix <- quantile(ix, c(0.25, 0.75))\n slope <- diff(iy) / diff(ix)\n intercept <- iy[1] - slope * ix[1]\n abline(a = intercept, b = slope, lty = ilty, col = icol, lwd = ilwd)\n }\n }\n return(fun)\n }\n\n out = list(\n draw = draw_qq(),\n data = data_qq(distribution = distribution),\n name = \"qq\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_vline.R", "#' @param v x-value(s) for vertical line(s). Numeric of length 1, or equal to\n#' the number of groups or number of facets (or the product thereof).\n#' @rdname type_abline\n#' @export\ntype_vline = function(v = 0) {\n assert_numeric(v)\n data_vline = function(datapoints, lwd, lty, col, ...) {\n if (nrow(datapoints) == 0) {\n msg = \"`type_vline() only works on existing plots with x and y data points.\"\n stop(msg, call. = FALSE)\n }\n # keep track of unique lty and lwd (needed for group catch / escape hatch\n # later in draw_hline)\n ul_lwd = length(unique(lwd))\n ul_lty = length(unique(lty))\n ul_col = length(unique(col))\n return(list(type_info = list(ul_lty = ul_lty, ul_lwd = ul_lwd, ul_col = ul_col)))\n }\n draw_vline = function() {\n fun = function(\n ifacet, iby, data_facet, icol, ilty, ilwd,\n ngrps, nfacets, by_continuous, facet_by,\n type_info,\n ...\n ) {\n\n # flag for aesthetics by groups\n grp_aes = type_info[[\"ul_col\"]] == 1 || type_info[[\"ul_lty\"]] == ngrps || type_info[[\"ul_lwd\"]] == ngrps\n \n if (length(v) != 1) {\n if (!length(v) %in% c(ngrps, nfacets, ngrps*nfacets)) {\n msg = \"Length of 'v' must be 1, or equal to the number of facets or number of groups (or product thereof).\"\n stop(msg, call. = FALSE)\n }\n if (!facet_by && length(v) == nfacets) {\n v = v[ifacet]\n if (!grp_aes && type_info[[\"ul_col\"]]!=ngrps) {\n icol = 1\n } else if (by_continuous) {\n icol = 1\n }\n } else if (!by_continuous && length(v) == ngrps * nfacets) {\n v = v[ifacet * ngrps - c(ngrps - iby)]\n } else if (!by_continuous) {\n v = v[iby]\n }\n } else if (!grp_aes) {\n icol = 1\n }\n \n abline(v = v, col = icol, lty = ilty, lwd = ilwd)\n }\n return(fun)\n }\n out = list(\n draw = draw_vline(),\n data = data_vline,\n name = \"vline\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_ribbon.R", "#' Ribbon and area plot types\n#' \n#' @param alpha numeric value between 0 and 1 specifying the opacity of ribbon shading\n#' If no `alpha` value is provided, then will default to `tpar(\"ribbon.alpha\")` \n#' (i.e., probably `0.2` unless this has been overridden by the user in their global \n#' settings.)\n#'\n#' @description Type constructor functions for producing polygon ribbons, which \n#' define a `y` interval (usually spanning from `ymin` to `ymax`) for each\n#' `x` value. Area plots are a special case of ribbon plot where `ymin` is\n#' set to 0 and `ymax` is set to `y`.\n#' \n#' @examples\n#' x = 1:100/10\n#' y = sin(x)\n#' \n#' #\n#' ## Ribbon plots\n#' \n#' # \"ribbon\" convenience string\n#' tinyplot(x = x, ymin = y-1, ymax = y+1, type = \"ribbon\")\n\n#' # Same result with type_ribbon()\n#' tinyplot(x = x, ymin = y-1, ymax = y+1, type = type_ribbon())\n#' \n#' # y will be added as a line if it is specified\n#' tinyplot(x = x, y = y, ymin = y-1, ymax = y+1, type = \"ribbon\")\n#'\n#' #\n#' ## Area plots\n#' \n#' # \"area\" type convenience string\n#' tinyplot(x, y, type = \"area\")\n#' \n#' # Same result with type_area()\n#' tinyplot(x, y, type = type_area())\n#' \n#' # Area plots are often used for time series charts\n#' tinyplot(AirPassengers, type = \"area\")\n#' @export\ntype_ribbon = function(alpha = NULL) {\n out = list(\n draw = draw_ribbon(),\n data = data_ribbon(ribbon.alpha = alpha),\n name = \"ribbon\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_ribbon = function() {\n fun = function(ix, iy, ixmin, ixmax, iymin, iymax, ibg, ilty, ilwd, icol, ipch, i, flip = FALSE, ...) {\n polyg = type_polygon()$draw\n lin = type_lines()$draw\n if (isFALSE(flip)) {\n polyg(ix = c(ix, rev(ix)), iy = c(iymin, rev(iymax)), icol = NA, ibg = ibg)\n } else {\n polyg(c(ixmin, rev(ixmax)), iy = c(iy, rev(iy)), icol = NA, ibg = ibg)\n }\n lin(ix = ix, iy = iy, icol = icol, ipch = ipch, ibg = ibg, ilty = ilty, ilwd = ilwd, type = \"l\")\n }\n return(fun)\n}\n\n\ndata_ribbon = function(ribbon.alpha = NULL) {\n ribbon.alpha = sanitize_ribbon.alpha(ribbon.alpha)\n fun = function(datapoints, xlabs, null_by, null_facet, ...) {\n # Convert x to factor if it's not already\n if (is.character(datapoints$x)) {\n datapoints$x = as.factor(datapoints$x)\n }\n\n if (is.factor(datapoints$x)) {\n xlvls = levels(datapoints$x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n datapoints$x = as.integer(datapoints$x)\n } else {\n xlabs = NULL\n }\n\n if (null_by && null_facet) {\n xord = order(datapoints$x)\n } else if (null_facet) {\n xord = order(datapoints$by, datapoints$x)\n } else if (null_by) {\n xord = order(datapoints$facet, datapoints$x)\n } else {\n xord = order(datapoints$by, datapoints$facet, datapoints$x)\n }\n\n # Reorder x, y, ymin, and ymax based on the order determined\n datapoints = datapoints[xord,]\n\n # Catch for missing ymin and ymax \n if (is.null(datapoints$ymin)) datapoints$ymin = datapoints$y \n if (is.null(datapoints$ymax)) datapoints$ymax = datapoints$y\n\n out = list(\n x = datapoints$x,\n y = datapoints$y,\n ymin = datapoints$ymin,\n ymax = datapoints$ymax,\n xlabs = xlabs,\n datapoints = datapoints,\n ribbon.alpha = ribbon.alpha)\n\n if (length(unique(datapoints$by)) > 1) out[[\"by\"]] = datapoints$by\n if (length(unique(datapoints$facet)) > 1) out[[\"facet\"]] = datapoints$facet\n\n return(out)\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_function.R", "#' Plot a function\n#'\n#' @details\n#' When using `type_function()` in a `tinyplot()` call, the `x` value indicates\n#' the range of values to plot on the x-axis.\n#'\n#' @param fun Function of `x` to plot. Defaults to \\code{\\link[stats]{dnorm}}.\n#' @param args List of additional arguments to be passed to `fun`.\n#' @param n Number of points to interpolate on the x axis.\n#' @param ... Additional arguments are passed to the `lines()` function,\n#' ex: `type=\"p\"`, `col=\"pink\"`.\n#' @importFrom stats dnorm\n#' \n#' @examples\n#' # Plot the normal density (default function)\n#' tinyplot(x = -4:4, type = \"function\")\n#' # tinyplot(x = -4:4, type = type_function()) # same\n#'\n#' # Customize by passing explicit arguments to your function\n#' tinyplot(x = -1:10, type = type_function(\n#' fun = dnorm, args = list(mean = 3)\n#' ))\n#'\n#' # Additional arguments are passed to the `lines()` function.\n#' tinyplot(x = -4:4, type = type_function(\n#' fun = dnorm,\n#' col = \"pink\", type = \"p\", pch = 3\n#' ))\n#' \n#' # Custom function example\n#' ## (Here using `function(x)`, but you could also use the shorter `\\(x)`\n#' ## anonymous function syntax introduced in R 4.1.0)\n#' tinyplot(x = -4:4, type = type_function(fun = function(x) 0.5 * exp(-abs(x))))\n#'\n#' @export\ntype_function = function(fun = dnorm, args = list(), n = 101, ...) {\n assert_function(fun)\n lines_args = list(...)\n data_function = function(args, fun) {\n funky = function(xlim, ylim, datapoints, ...) {\n if (nrow(datapoints) == 0 || !\"x\" %in% names(datapoints)) {\n stop(\"Need to provide x values to plot the function.\", call. = FALSE)\n }\n if (is.null(xlim)) {\n xlim = range(datapoints[[\"x\"]])\n }\n if (is.null(ylim)) {\n tmp = c(list(datapoints[[\"x\"]]), args)\n tmp = range(tmp)\n tmp = seq(tmp[1], tmp[2], length.out = n)\n tmp = c(list(tmp), args)\n tmp = do.call(fun, tmp)\n ylim = c(min(tmp), max(tmp))\n }\n out = list(xlim = xlim, ylim = ylim)\n return(out)\n }\n }\n draw_function = function() {\n funky = function(ifacet, data_facet, ...) {\n xrange = range(data_facet[[ifacet]][[\"x\"]])\n x = seq(xrange[1], xrange[2], length.out = n)\n y = do.call(fun, c(list(x), args))\n tmp = c(list(x, y), lines_args)\n do.call(lines, tmp)\n }\n return(funky)\n }\n out = list(\n draw = draw_function(),\n data = data_function(args = args, fun = fun),\n name = \"function\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/get_saved_par.R", "#' @title Retrieve the saved graphical parameters\n#' \n#' @description Convenience function for retrieving the graphical parameters\n#' (i.e., the full list of `tag = value` pairs held in\n#' \\code{\\link[graphics]{par}}) from either immediately before or\n#' immediately after the most recent [tinyplot] call.\n#'\n#' @param when character. From when should the saved parameters be retrieved?\n#' Either \"before\" (the default) or \"after\" the preceding `tinyplot` call.\n#' \n#' @details A potential side-effect of [tinyplot] is that it can change a user's\n#' \\code{\\link[graphics]{par}} settings. For example, it may adjust the inner\n#' and outer plot margins to make space for an automatic legend; see\n#' [draw_legend]. While it is possible to immediately restore the original\n#' \\code{\\link[graphics]{par}} settings upon exit via the\n#' `tinyplot(..., restore.par = TRUE)` argument, this is not the default\n#' behaviour. The reason being that we need to preserve the adjusted parameter\n#' settings in case users want to add further graphical annotations to their\n#' plot (e.g., \\code{\\link[graphics]{abline}}, \\code{\\link[graphics]{text}},\n#' etc.) Nevertheless, it may still prove desirable to recall and reset these\n#' original graphical parameters after the fact (e.g., once all these extra\n#' annotations have been added). That is the purpose of this [get_saved_par]\n#' function.\n#' \n#' Of course, users may prefer to manually capture and reset graphical\n#' parameters, as per the standard method described in the\n#' \\code{\\link[graphics]{par}} documentation. For example:\n#' \n#' ```\n#' op = par(no.readonly = TRUE) # save current par settings \n#' # \n#' par(op) # reset original pars\n#' ```\n#' \n#' This standard manual approach may be safer than [get_saved_par] because it\n#' offers more precise control. Specifically, the value of [get_saved_par] \n#' itself will be reset after ever new [tinyplot] call; i.e. it may inherit an\n#' already-changed set of parameters. Users should bear these trade-offs in\n#' mind when deciding which approach to use. As a general rule,\n#' [get_saved_par] offers the convenience of resetting the original\n#' \\code{\\link[graphics]{par}} settings even if a user forgot to save them\n#' beforehand. But one should avoid invoking it after a series of consecutive\n#' [tinyplot] calls.\n#' \n#' Finally, note that users can always call \\code{\\link[grDevices]{dev.off}}\n#' to reset all \\code{\\link[graphics]{par}} settings to their defaults.\n#' \n#' @returns A list of \\code{\\link[graphics]{par}} settings.\n#' \n#' @examples\n#' #\n#' # Contrived example where we draw a grouped scatterplot with a legend and\n#' # manually add corresponding best fit lines for each group...\n#' #\n#' \n#' # First draw the grouped scatterplot\n#' tinyplot(Sepal.Length ~ Petal.Length | Species, iris)\n#' \n#' # Preserving adjusted par settings is good for adding elements to our plot\n#' for (s in levels(iris$Species)) {\n#' abline(\n#' lm(Sepal.Length ~ Petal.Length, iris, subset = Species==s),\n#' col = which(levels(iris$Species)==s)\n#' )\n#' }\n#' \n#' # Get saved par from before the preceding tinyplot call (but don't use yet)\n#' sp = get_saved_par(\"before\")\n#' \n#' # Note the changed margins will affect regular plots too, which is probably\n#' # not desirable\n#' plot(1:10)\n#' \n#' # Reset the original parameters (could use `par(sp)` here)\n#' tpar(sp)\n#' # Redraw our simple plot with our corrected right margin\n#' plot(1:10)\n#' \n#' #\n#' # Quick example going the other way, \"correcting\" for par.restore = TRUE...\n#' #\n#' \n#' tinyplot(Sepal.Length ~ Petal.Length | Species, iris, restore.par = TRUE)\n#' # Our added best lines will be wrong b/c of misaligned par\n#' for (s in levels(iris$Species)) {\n#' abline(\n#' lm(Sepal.Length ~ Petal.Length, iris, subset = Species==s),\n#' col = which(levels(iris$Species)==s), lty = 2\n#' )\n#' }\n#' # grab the par settings from the _end_ of the preceding tinyplot call to fix\n#' tpar(get_saved_par(\"after\"))\n#' # now the best lines are correct\n#' for (s in levels(iris$Species)) {\n#' abline(\n#' lm(Sepal.Length ~ Petal.Length, iris, subset = Species==s),\n#' col = which(levels(iris$Species)==s)\n#' )\n#' }\n#' \n#' # reset again to original saved par settings before exit\n#' tpar(sp)\n#'\n#' @export\nget_saved_par = function(when = c(\"before\", \"after\", \"first\")) {\n when = match.arg(when)\n par_env_name = paste0(\".saved_par_\", when)\n return(get(par_env_name, envir = get(\".tinyplot_env\", envir = parent.env(environment()))))\n}\n\n# (non-exported) companion function(s) for setting the original pars\nset_saved_par = function(when = c(\"before\", \"after\", \"first\"), value) {\n when = match.arg(when)\n par_env_name = paste0(\".saved_par_\", when)\n assign(par_env_name, value, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n}\n"], ["/tinyplot/R/type_errorbar.R", "#' Error bar and pointrange plot types\n#' \n#' @description Type function(s) for producing error bar and pointrange plots.\n#' \n#' @inheritParams graphics::arrows\n#' @examples\n#' mod = lm(mpg ~ wt * factor(am), mtcars)\n#' coefs = data.frame(names(coef(mod)), coef(mod), confint(mod))\n#' colnames(coefs) = c(\"term\", \"est\", \"lwr\", \"upr\")\n#' \n#' op = tpar(pch = 19)\n#' \n#' # \"errorbar\" and \"pointrange\" type convenience strings\n#' tinyplot(est ~ term, ymin = lwr, ymax = upr, data = coefs, type = \"errorbar\")\n#' tinyplot(est ~ term, ymin = lwr, ymax = upr, data = coefs, type = \"pointrange\")\n#' \n#' # Use `type_errorbar()` to pass extra arguments for customization\n#' tinyplot(est ~ term, ymin = lwr, ymax = upr, data = coefs, type = type_errorbar(length = 0.2))\n#' \n#' tpar(op)\n#' \n#' @export\ntype_errorbar = function(length = 0.05) {\n out = list(\n draw = draw_errorbar(length = length),\n data = data_pointrange(),\n name = \"p\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_errorbar = function(length = 0.05) {\n fun = function(ix, iy, ixmin, iymin, ixmax, iymax, icol, ibg, ipch, ilwd, cex, ...) {\n arrows(\n x0 = ixmin,\n y0 = iymin,\n x1 = ixmax,\n y1 = iymax,\n col = icol,\n lwd = ilwd,\n length = length,\n angle = 90,\n code = 3\n )\n draw_points()(ix = ix, iy = iy, icol = icol, ibg = ibg, ipch = ipch, ilwd = ilwd, cex = cex)\n }\n return(fun)\n}\n\n\n"], ["/tinyplot/R/type_points.R", "#' Points plot type\n#'\n#' @description Type function for plotting points, i.e. a scatter plot.\n#' \n#' @examples\n#' # \"p\" type convenience character string\n#' tinyplot(Sepal.Length ~ Petal.Length, data = iris, type = \"p\")\n#' \n#' # Same result with type_points()\n#' tinyplot(Sepal.Length ~ Petal.Length, data = iris, type = type_points())\n#' \n#' # Note: Specifying the type here is redundant. Like base plot, tinyplot\n#' # automatically produces a scatter plot if x and y are numeric\n#' tinyplot(Sepal.Length ~ Petal.Length, data = iris)\n#' \n#' # Grouped scatter plot example\n#' tinyplot(Sepal.Length ~ Petal.Length | Species, data = iris)\n#' \n#' # Continuous grouping (with gradient legend)\n#' tinyplot(Sepal.Length ~ Petal.Length | Sepal.Width, data = iris, pch = 19)\n#' \n#' @export\ntype_points = function() {\n out = list(\n draw = draw_points(),\n data = data_points(),\n name = \"p\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\ndata_points = function() {\n fun = function(datapoints, ...) {\n # catch for factors (we should still be able to \"force\" plot these with points)\n if (is.factor(datapoints$x)) {\n xlvls = levels(datapoints$x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n datapoints$x = as.integer(datapoints$x)\n } else {\n xlabs = NULL\n }\n if (is.factor(datapoints$y)) {\n ylvls = levels(datapoints$y)\n ylabs = seq_along(ylvls)\n names(ylabs) = ylvls\n datapoints$y = as.integer(datapoints$y)\n } else {\n ylabs = NULL\n }\n \n out = list(\n datapoints = datapoints,\n xlabs = xlabs,\n ylabs = ylabs\n )\n return(out)\n }\n}\n\ndraw_points = function() {\n fun = function(ix, iy, icol, ibg, ipch, ilwd, cex, ...) {\n points(\n x = ix,\n y = iy,\n col = icol,\n bg = ibg,\n type = \"p\",\n pch = ipch,\n lwd = ilwd,\n cex = cex\n )\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/tinyAxis.R", "#' @title Generic function for adding an axis to a (tiny)plot\n#' \n#' @description Internal function used for adding an axis to a [`tinyplot`]\n#' call.\n#' @details `tinyAxis` provides a thin(ish) wrapper around\n#' \\code{\\link[graphics]{Axis}}, but with enhanced flexibility to (i) match\n#' parameter combinations based on the axis type and plotting theme, (ii)\n#' provide better support for date-time variables, and (iii) enable convenient\n#' formatting of axis tick labels.\n#' @inheritParams graphics::Axis\n#' @param type the type of axis to be drawn; inherited from the `xaxt` or `yaxt`\n#' arguments of the parent [`tinyplot()`] call. One of either: `\"standard\"`\n#' (default that draws the axis, ticks, and labels), `\"none\"` (no axes),\n#' `\"ticks\"` (only ticks and labels without axis line), `\"labels\"` (only\n#' labels without ticks and axis line), or `\"axis\"` (only axis line and labels\n#' but no ticks). Partial matching is allowed, e.g. `type = \"s\"`.\n#' @inheritParams tinylabel\n#' @examples\n#' \\dontrun{\n#' \n#' # plot without axes\n#' tinyplot(0:10, axes = \"n\")\n#' # add x-axis (labels only)\n#' tinyplot:::tinyAxis(x = 0:10, side = 1, type = \"l\")\n#' # add y-axis (with custom label formatting)\n#' tinyplot:::tinyAxis(x = 0:10, side = 2, type = \"s\", labeller = \"$\")\n#' }\n#' @keywords internal\ntinyAxis = function(x = NULL, ..., type = \"standard\", labeller = NULL) {\n type = match.arg(type, c(\"standard\", \"none\", \"labels\", \"ticks\", \"axis\"))\n if (type == \"none\") {\n invisible(numeric(0L))\n } else {\n args = list(x = x, ...)\n if (type == \"labels\") {\n args$tick = FALSE\n } else if (type == \"ticks\") {\n args$lwd = 0\n if (!(\"lwd.ticks\" %in% names(args))) args$lwd.ticks = 1\n } else if (type == \"axis\") {\n args$lwd.ticks = 0\n } else {\n args$tick = TRUE\n }\n if (!is.null(labeller)) {\n if (!is.null(args$at)) {\n args$labels = if (!is.null(args$labels)) tinylabel(args$labels, labeller) else tinylabel(args$at, labeller)\n } else {\n args$at = if (!inherits(x, c(\"POSIXt\", \"Date\"))) axTicks(args$side) else axTicksDateTime(args$side, x = x) \n args$labels = tinylabel(args$at, labeller)\n }\n }\n do.call(\"Axis\", args)\n }\n}\n\n# Special case for Date-Time, adapted/simplified from axis.date()\naxTicksDateTime = function(side, x, ...) {\n if (inherits(x, \"POSIXt\")) {\n tz = attr(x, \"tz\")\n range = extendrange(x)\n rangeDateTime = .POSIXct(range, tz = tz)\n } else {\n range = sort(par(\"usr\")[if (side%%2) 1L:2L else 3:4L])\n range[1L] = ceiling(range[1L])\n range[2L] = floor(range[2L])\n rangeDateTime = range\n class(rangeDateTime) = \"Date\"\n }\n z = pretty(rangeDateTime, n = par(\"lab\")[2 - side%%2])\n keep = z >= range[1L] & z <= range[2L]\n z = z[keep]\n return(z)\n}\n"], ["/tinyplot/R/type_hline.R", "#' @rdname type_abline\n#' @param h y-value(s) for horizontal line(s). Numeric of length 1, or equal to\n#' the number of groups or number of facets (or the product thereof).\n#' @export\ntype_hline = function(h = 0) {\n assert_numeric(h)\n data_hline = function(datapoints, lwd, lty, col, ...) {\n if (nrow(datapoints) == 0) {\n msg = \"`type_hline() only works on existing plots with x and y data points.\"\n stop(msg, call. = FALSE)\n }\n # keep track of unique lty and lwd (needed for group catch / escape hatch\n # later in draw_hline)\n ul_lwd = length(unique(lwd))\n ul_lty = length(unique(lty))\n ul_col = length(unique(col))\n return(list(type_info = list(ul_lty = ul_lty, ul_lwd = ul_lwd, ul_col = ul_col)))\n }\n draw_hline = function() {\n fun = function(\n ifacet, iby, data_facet, icol, ilty, ilwd,\n ngrps, nfacets, by_continuous, facet_by,\n type_info,\n ...\n ) {\n \n # flag for aesthetics by groups\n grp_aes = type_info[[\"ul_col\"]] == 1 || type_info[[\"ul_lty\"]] == ngrps || type_info[[\"ul_lwd\"]] == ngrps\n \n if (length(h) != 1) {\n if (!length(h) %in% c(ngrps, nfacets, ngrps*nfacets)) {\n msg = \"Length of 'h' must be 1, or equal to the number of facets or number of groups (or product thereof).\"\n stop(msg, call. = FALSE)\n }\n if (!facet_by && length(h) == nfacets) {\n h = h[ifacet]\n if (!grp_aes && type_info[[\"ul_col\"]]!=ngrps) {\n icol = 1\n } else if (by_continuous) {\n icol = 1\n }\n } else if (!by_continuous && length(h) == ngrps * nfacets) {\n h = h[ifacet * ngrps - c(ngrps - iby)]\n } else if (!by_continuous) {\n h = h[iby]\n }\n } else if (!grp_aes) {\n icol = 1\n }\n\n abline(h = h, col = icol, lty = ilty, lwd = ilwd)\n }\n return(fun)\n }\n out = list(\n draw = draw_hline(),\n data = data_hline,\n name = \"hline\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/type_glm.R", "#' Generalized linear model plot type\n#' \n#' @description Type function for plotting a generalized model fit.\n#' Arguments are passed to \\code{\\link[stats]{glm}}.\n#' \n#' @param se logical. If TRUE, confidence intervals are drawn.\n#' @inheritParams stats::glm\n#' @inheritParams stats::predict.glm\n#' @inheritParams stats::confint\n#' @importFrom stats glm predict\n#' @examples\n#' # \"glm\" type convenience string\n#' tinyplot(am ~ mpg, data = mtcars, type = \"glm\")\n#' \n#' # Use `type_glm()` to pass extra arguments for customization\n#' tinyplot(am ~ mpg, data = mtcars, type = type_glm(family = \"binomial\"))\n#' @export\ntype_glm = function(family = \"gaussian\", se = TRUE, level = 0.95, type = \"response\") {\n assert_flag(se)\n out = list(\n draw = draw_ribbon(),\n data = data_glm(family = family, se = se, level = level, type = type),\n name = if (isTRUE(se)) \"ribbon\" else \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_glm = function(family, se, level, type, ...) {\n fun = function(datapoints, ...) {\n dat = split(datapoints, list(datapoints$facet, datapoints$by))\n dat = lapply(dat, function(x) {\n if (nrow(x) == 0) return(x)\n if (nrow(x) < 3) {\n x$y = NA\n return(x)\n }\n fit = glm(y ~ x, data = x, family = family)\n nd = data.frame(x = seq(min(x$x, na.rm = TRUE), max(x$x, na.rm = TRUE), length.out = 100))\n nd$by = x$by[1]\n nd$facet = x$facet[1]\n if (se == TRUE) {\n if (identical(type, \"response\")) {\n p = predict(fit, newdata = nd, type = \"link\", se.fit = TRUE)\n p = ci(p$fit, p$se.fit, conf.level = level, fit$df.residual, backtransform = stats::family(fit)$linkinv)\n nd$y = p$estimate\n nd$ymax = p$conf.high\n nd$ymin = p$conf.low\n\n } else {\n nd$y = predict(fit, newdata = nd, type = type)\n nd = ci(nd$y, nd$se, level, fit$df.residual, backtransform = stats::family(fit)$linkinv)\n }\n } else {\n nd$y = predict(fit, nd, type = type)\n }\n nd\n })\n datapoints = do.call(rbind, dat)\n datapoints = datapoints[order(datapoints$facet, datapoints$by, datapoints$x), ]\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\n\n#' Calculate confidence intervals\n#' @importFrom stats qt\n#' @keywords internal\nci = function(estimate, std.error, conf.level, df, backtransform = identity) {\n crit = qt(1 - (1 - conf.level) / 2, df)\n out = list(\n estimate = backtransform(estimate),\n conf.low = backtransform(estimate - crit * std.error),\n conf.high = backtransform(estimate + crit * std.error)\n )\n return(out)\n}\n"], ["/tinyplot/R/type_summary.R", "#' Plot summary values of `y` at unique values of `x`\n#'\n#' @md\n#' @description\n#' Applies a summary function to `y` along unique values of `x`. For example,\n#' plot the mean `y` value for each `x` value. Internally,\n#' `type_summary()` applies a thin wrapper around \\code{\\link[stats]{ave}} and\n#' then passes the result to [`type_lines`] for drawing.\n#'\n#' @param fun summarizing function. Should be compatible with\n#' \\code{\\link[stats]{ave}}. Defaults to \\code{\\link[base]{mean}}.\n#' @param ... Additional arguments are passed to the `lines()` function,\n#' ex: `type=\"p\"`, `col=\"pink\"`.\n#' @seealso [`ave`] which performs the summarizing (averaging) behind the\n#' scenes.\n#' @examples\n#' # Plot the mean chick weight over time\n#' tinyplot(weight ~ Time, data = ChickWeight, type = \"summary\")\n#' \n#' # Note: \"mean\" is the default function, so these are also equivalent:\n#' # tinyplot(weight ~ Time, data = ChickWeight, type = type_summary())\n#' # tinyplot(weight ~ Time, data = ChickWeight, type = type_summary(mean))\n#' \n#' # Plot the median instead\n#' tinyplot(weight ~ Time, data = ChickWeight, type = type_summary(median))\n#' \n#' # Works with groups and/or facets too\n#' tinyplot(weight ~ Time | Diet, facet = \"by\", data = ChickWeight, type = \"summary\")\n#'\n#' # Custom/complex function example\n#' tinyplot(\n#' weight ~ Time | Diet, facet = \"by\", data = ChickWeight,\n#' type = type_summary(function(y) quantile(y, probs = 0.9)/max(y))\n#' )\n#' \n#' @importFrom stats ave\n#' @export\ntype_summary = function(fun = mean, ...) {\n assert_function(fun)\n lines_args = list(...)\n data_summary = function(fun) {\n funky = function(datapoints, ...) {\n datapoints = split(datapoints, list(datapoints$facet, datapoints$by), drop = TRUE)\n datapoints = lapply(datapoints, function(dat) {\n newy = ave(dat$y, dat$x, FUN = fun)\n dat$y = newy\n dat = dat[order(dat$x), ]\n return(dat)\n })\n datapoints = do.call(rbind, datapoints)\n out = list(datapoints = datapoints)\n return(out)\n }\n return(funky)\n }\n out = list(\n draw = draw_lines(...),\n data = data_summary(fun = fun),\n name = \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n"], ["/tinyplot/R/by_aesthetics.R", "by_col = function(ngrps = 1L, col = NULL, palette = NULL, gradient = NULL, ordered = NULL, alpha = NULL) {\n if (is.null(alpha)) alpha = 1\n if (is.null(ordered)) ordered = FALSE\n if (is.null(gradient)) gradient = FALSE\n assert_logical(ordered)\n assert_logical(gradient)\n if (gradient) {\n ngrps = 100L\n }\n \n # pal_qual = get_tpar(\"palette.qualitative\", default = NULL)\n pal_theme = get_tpar(\"palette.qualitative\", default = NULL)\n theme_flag = !is.null(pal_theme)\n\n # palette = substitute(palette, env = parent.env(environment()))\n\n # special \"by\" convenience keyword (will treat as NULL & handle grouping below)\n if (!anyNA(col) && !is.null(col) && length(col) == 1 && col == \"by\") col = NULL\n\n #\n ## Base case: If no color or palette provided, pass colors as a sequence of\n ## numbers (will inherit from / cycle over the user's default palette)\n \n if (is.null(col) && (is.null(palette) && !theme_flag)) {\n if (ngrps <= length(palette()) && !ordered) {\n col = palette()[seq_len(ngrps)]\n if (alpha) col = adjustcolor(col, alpha.f = alpha)\n } else {\n # fallback to restricted viridis palette\n col = colorRampPalette(\n hcl.colors(n = 100, palette = \"Viridis\", alpha = alpha)[(100 * 0.1 + 1):(100 * 0.9)],\n alpha = TRUE\n )(ngrps)\n }\n if (gradient || ordered) col = rev(col)\n return(col)\n }\n\n #\n ## Next simplest case: No palette, but color(s) provided directly. We do\n ## some simple sanity checks, apply alpha transparency and return as-is.\n\n if (is.atomic(col) && is.vector(col)) {\n if (length(col) == 1) {\n col = rep(col, ngrps)\n if (alpha) col = adjustcolor(col, alpha.f = alpha)\n return(col)\n } else if (length(col) < ngrps) {\n # if (!gradient) {\n # stop(sprintf(\"`col` must be of length 1, or greater than or equal to %s.\", ngrps), call. = FALSE)\n # } else {\n # # interpolate gradient colors\n # col = colorRampPalette(colors = col, alpha = TRUE)(ngrps)\n # }\n # if manual colours < ngrps, either (1) interpolate for gradient\n # colors, or (2) recycle for discrete colours\n if (gradient) {\n col = colorRampPalette(colors = col, alpha = TRUE)(ngrps)\n } else {\n ncolsstr = paste0(\"(\", length(col), \")\")\n ngrpsstr = paste0(\"(\", ngrps, \")\")\n warning(\n \"\\nFewer colours \", ncolsstr, \" provided than than there are groups \",\n ngrpsstr, \". Recycling to make up the shortfall.\"\n )\n col = rep(col, length.out = ngrps)\n }\n \n }\n if (gradient) {\n col = rev(col)\n } else if (!ordered && is.numeric(col)) {\n # col = palette()[col]\n if (ngrps <= length(palette())) {\n col = palette()[col]\n # if (alpha) col = adjustcolor(col, alpha.f = alpha)\n } else {\n col = hcl.colors(max(col), alpha = alpha)[col]\n }\n }\n if (anyNA(col) || is.character(col)) {\n if (alpha) col = adjustcolor(col, alpha.f = alpha)\n return(col)\n }\n }\n \n \n #\n ## Theme case: No palette provided, but fallback to tinytheme palette\n\n # we need to fix palette string, determine if in palette.pals() and then\n # determine no. of groups, before kicking over to sequential\n if (is.null(palette) && theme_flag) {\n if (length(pal_theme) == 1) {\n qual_match = match_pal(pal_theme, palette.pals())\n if (!is.na(qual_match)) {\n if (ngrps >= get_pal_lens(pal_theme) || ordered) {\n pal_theme = get_tpar(\"palette.sequential\", default = NULL)\n }\n # mostly a catch for x-gradient fills, e.g. type_ridge\n } else if (gradient && !is.na(match_pal(pal_theme, hcl.pals()))) {\n pal_theme = get_tpar(\"palette.sequential\", default = NULL)\n }\n }\n if (length(pal_theme) == 1) {\n palette_fun = gen_pal_fun(pal = pal_theme, gradient = gradient, alpha = alpha)\n args = list(n = ngrps, palette = pal_theme, alpha = alpha)\n }\n palette = pal_theme\n }\n \n if (is.null(palette)) {\n if (ngrps <= length(palette()) && !ordered && !gradient) {\n palette_fun = function(alpha) adjustcolor(palette(), alpha) # must be function to avoid arg ambiguity\n args = list(alpha = alpha)\n } else {\n if (ngrps <= 8 && !ordered) { # ngrps < 100 so we know gradient is FALSE too\n palette = \"R4\"\n palette_fun = palette.colors\n } else {\n palette = \"Viridis\"\n if (!gradient && !ordered) {\n palette_fun = hcl.colors\n } else {\n palette_fun_gradient = function(n, palette, from = 0.1, to = 0.9, alpha = 1) {\n colorRampPalette(\n hcl.colors(n = 100, palette = palette, alpha = alpha)[(100 * from + 1):(100 * to)],\n alpha = TRUE\n )(n)\n }\n palette_fun = palette_fun_gradient\n }\n }\n args = list(n = ngrps, palette = palette, alpha = alpha)\n }\n } else {\n if (is.character(palette)) {\n # special case: if vector of character strings, we assume that the user\n # must have passed a vector of colours (e.g., c(\"red\", \"blue\")) rather\n # than a known/named colour palette (e.g. \"Harmonic\")\n if (length(palette) > 1) {\n palette_fun = \"c\"\n if (!is.null(alpha)) palette = adjustcolor(palette, alpha.f = alpha)\n args = as.list(palette)\n if (length(args) < ngrps && length(args) != 1) {\n # if manual colours < ngrps, either (1) interpolate for gradient\n # colors, or (2) recycle for discrete colours\n if (gradient) {\n args = list(colorRampPalette(args, alpha = TRUE)(ngrps))\n } else {\n ncolsstr = paste0(\"(\", length(args), \")\")\n ngrpsstr = paste0(\"(\", ngrps, \")\")\n warning(\n \"\\nFewer colours \", ncolsstr, \" provided than than there are groups \",\n ngrpsstr, \". Recycling to make up the shortfall.\"\n )\n args = rep(args, length.out = ngrps)\n }\n }\n } else {\n palette_fun = gen_pal_fun(palette, gradient = gradient, alpha = alpha, n = ngrps)\n args = list(n = ngrps, palette = palette, alpha = alpha)\n }\n } else if (inherits(palette, c(\"call\", \"name\"))) {\n # catch for when using passes palette as named object (e.g,\n # pal26 = palette.colors(\"Alphabet\"))\n if (inherits(palette, \"name\") && is.character(eval(palette))) {\n args = as.list(eval(palette))\n palette_fun = \"c\"\n } else {\n args = as.list(palette)\n palette_fun = paste(args[[1]])\n args[[1]] = NULL\n }\n # catch for direct vector or list\n if (palette_fun %in% c(\"c\", \"list\")) {\n if (palette_fun == \"list\") palette_fun = \"c\"\n if (!is.null(alpha)) args = lapply(args, function(a) adjustcolor(a, alpha.f = alpha))\n if (length(args) < ngrps && length(args) != 1) {\n # if manual colours < ngrps, either (1) interpolate for gradient\n # colors, or (2) recycle for discrete colours\n if (gradient) {\n args = list(colorRampPalette(args, alpha = TRUE)(ngrps))\n } else {\n ncolsstr = paste0(\"(\", length(args), \")\")\n ngrpsstr = paste0(\"(\", ngrps, \")\")\n warning(\n \"\\nFewer colours \", ncolsstr, \" provided than than there are groups \",\n ngrpsstr, \". Recycling to make up the shortfall.\"\n )\n args = rep(args, length.out = ngrps)\n }\n }\n } else {\n args[[\"n\"]] = ngrps\n # remove unnamed arguments to prevent unintentional argument sliding\n if (any(names(args) == \"\")) args[[which(names(args) == \"\")]] = NULL\n }\n } else if (inherits(palette, \"function\")) {\n args = list()\n palette_fun = palette\n } else {\n stop(\n \"\\nInvalid palette argument. Must be a recognized keyword, or a \",\n \"palette-generating function with named arguments.\\n\"\n )\n }\n }\n\n cols = tryCatch(\n do.call(palette_fun, args),\n error = function(e) do.call(eval(palette), args) # catch for bespoke palette generating funcs\n )\n\n if (length(cols) > ngrps) cols = cols[1:ngrps]\n\n # For gradient and ordered colors, we'll run high to low\n if (gradient || ordered) cols = rev(cols)\n\n return(cols)\n}\n\n# Some utility functions for palette matching, etc.\n\nmatch_pal = function(pal, pals) {\n fx = function(x) tolower(gsub(\"[-, _, \\\\,, (, ), \\\\ , \\\\.]\", \"\", x))\n charmatch(fx(pal), fx(pals))\n}\n\nget_pal_lens = function(pal) {\n pal_lens = c(\n R3 = 8L, R4 = 8L, ggplot2 = 8L, `Okabe-Ito` = 9L, Accent = 8L,\n `Dark 2` = 8L, Paired = 12L, `Pastel 1` = 9L, `Pastel 2` = 8L, \n `Set 1` = 9L, `Set 2` = 8L, `Set 3` = 12L, `Tableau 10` = 10L, \n `Classic Tableau` = 10L, `Polychrome 36` = 36L, Alphabet = 26L\n )\n pal_lens[pal]\n}\n\n# take a character string, match to either palette.pals() pr hcl.pals(), and\n# generate the corresponding function factor with alpha transparency\ngen_pal_fun = function(pal, gradient = FALSE, alpha = NULL, n = NULL) {\n pal_match = match_pal(pal, palette.pals())\n if (!is.na(pal_match)) {\n if (pal_match < 1L) stop(\"'palette' is ambiguous\")\n pal_fun = palette.colors\n if (!is.null(n) && n >= get_pal_lens(pal_match)) {\n warning(\n \"\\nFewer colours \", get_pal_lens(pal_match), \" provided than than there are groups \",\n n, \". Recycling to make up the shortfall.\"\n )\n pal_fun = function(n, palette, alpha) palette.colors(n = n, palette = pal, alpha = alpha, recycle = TRUE)\n }\n if (gradient) {\n pal_fun = function(n, palette, alpha) colorRampPalette(palette.colors(palette = pal, alpha = alpha))(n)\n }\n } else {\n pal_match = match_pal(pal, hcl.pals())\n if (!is.na(pal_match)) {\n if (pal_match < 1L) stop(\"'palette' is ambiguous\")\n pal_fun = hcl.colors\n } else {\n stop(\n \"\\nPalette string not recogized. Must be a value produced by either\",\n \"`palette.pals()` or `hcl.pals()`.\\n\",\n call. = FALSE\n )\n }\n }\n return(pal_fun)\n}\n\n\nby_pch = function(ngrps, type, pch = NULL) {\n no_pch = FALSE\n if (identical(type, \"text\")) {\n pch <- rep(15, ngrps)\n } else if (!type %in% c(\"p\", \"b\", \"o\", \"pointrange\", \"errorbar\", \"boxplot\", \"qq\")) {\n no_pch = TRUE\n pch = NULL\n\n # special \"by\" convenience keyword\n } else if (!is.null(pch) && length(pch) == 1 && pch == \"by\") {\n no_pch = TRUE # skip checks below\n pch = 1:ngrps + par(\"pch\") - 1\n # correctly recycle if over max pch type\n pch_ceiling = 25 # see ?pch\n if (max(pch) > pch_ceiling) {\n pch_below = pch[pch <= pch_ceiling]\n pch_above = pch[pch > pch_ceiling]\n pch_above = rep_len(0:pch_ceiling, length(pch_above))\n pch = c(pch_below, pch_above)\n }\n\n # return NULL if not a valid point type\n } else if (is.null(pch)) {\n pch = par(\"pch\")\n }\n\n if (!no_pch) {\n if (!is.atomic(pch) || !is.vector(pch) || !(is.numeric(pch) || is.character(pch)) || (length(pch) != 1 && length(pch) != ngrps)) {\n # if (!is.atomic(pch) || !is.vector(pch) || !is.numeric(pch) || (length(pch) != 1 && length(pch) != ngrps)) {\n stop(sprintf(\"`pch` must be `NULL`, or a numeric or character vector of length 1 or %s.\", ngrps), call. = FALSE)\n }\n\n if (length(pch) == 1) {\n pch = rep(pch, ngrps)\n }\n }\n\n return(pch)\n}\n\n\nby_lty = function(ngrps, type, lty = NULL) {\n # We only care about line types, otherwise return NULL\n if (!type %in% c(\"l\", \"b\", \"o\", \"c\", \"h\", \"s\", \"S\", \"ribbon\", \"barplot\", \"boxplot\", \"rect\", \"segments\", \"qq\", \"abline\", \"hline\", \"vline\")) {\n out = NULL\n\n # special \"by\" convenience keyword\n } else if (!is.null(lty) && length(lty) == 1 && lty == \"by\") {\n lty_dict = c(\"solid\", \"dashed\", \"dotted\", \"dotdash\", \"longdash\", \"twodash\")\n par_lty = par(\"lty\")\n\n if (!par_lty %in% lty_dict) {\n warning(\n \"\\nBesoke lty specifications (i.e., using string combinations) are not\",\n \"currently supported alongside the lty='by' keyword argument.\",\n \"Defaulting to 1 and looping from there.\\n\"\n )\n par_lty = 1\n } else {\n par_lty = which(par_lty == lty_dict)\n }\n out = 1:ngrps + par_lty - 1\n # correctly recycle if over max pch type\n lty_ceiling = 6 # see ?pch\n if (max(out) > lty_ceiling) {\n lty_below = out[out <= lty_ceiling]\n lty_above = out[out > lty_ceiling]\n lty_above = rep_len(1:lty_ceiling, length(lty_above))\n out = c(lty_below, lty_above)\n }\n\n # NULL -> solid (or default) line\n } else if (is.null(lty)) {\n if (identical(type, \"boxplot\")) {\n out = NULL\n } else {\n out = rep(par(\"lty\"), ngrps)\n }\n\n # atomic vector: sanity check length\n } else if (is.atomic(lty) && is.vector(lty)) {\n if (length(lty) == 1) {\n out = rep(lty, ngrps)\n } else {\n if (length(lty) != ngrps) {\n stop(sprintf(\"`lty` must be `NULL` or a numeric vector of length 1 or %s.\", ngrps), call. = FALSE)\n }\n out = lty\n }\n }\n\n return(out)\n}\n\n\nby_lwd = function(ngrps, type, lwd = NULL) {\n lwd_base = par(\"lwd\")\n lwd_floor = lwd_base / min(5, max((ngrps - 1), 1))\n lwd_ceiling = lwd_base * min(5, ngrps)\n\n no_lwd = FALSE\n # special \"by\" convenience keyword\n if (!is.null(lwd) && length(lwd) == 1 && lwd == \"by\") {\n no_lwd = TRUE # skip checks below\n lwd = seq(lwd_floor, lwd_ceiling, length.out = ngrps)\n } else if (is.null(lwd)) {\n no_lwd = TRUE\n lwd = NULL\n }\n\n if (!no_lwd) {\n if (!is.atomic(lwd) || !is.vector(lwd) || !is.numeric(lwd) || (length(lwd) != 1 && length(lwd) != ngrps)) {\n stop(sprintf(\"`lwd` must be `NULL` or a numeric vector of length 1 or %s.\", ngrps), call. = FALSE)\n }\n if (length(lwd) == 1) {\n lwd = rep(lwd, ngrps)\n }\n }\n\n return(lwd)\n}\n\n\nby_bg = function(\n adjustcolor,\n alpha,\n bg,\n by,\n by_continuous,\n by_ordered,\n col,\n fill,\n ngrps,\n palette,\n ribbon.alpha,\n type) {\n if (is.null(bg) && !is.null(fill)) bg = fill\n if (!is.null(bg) && length(bg) == 1 && is.numeric(bg) && bg >= 0 && bg <= 1) {\n alpha = bg\n bg = \"by\"\n }\n if (!is.null(bg) && length(bg) == 1 && bg == \"by\") {\n bg = by_col(\n ngrps = ngrps,\n col = NULL,\n palette = palette,\n gradient = by_continuous,\n ordered = by_ordered,\n alpha = alpha\n )\n } else if (length(bg) != ngrps) {\n bg = rep(bg, ngrps)\n }\n if (type == \"ribbon\" || (type == \"boxplot\" && !is.null(by))) {\n if (!is.null(bg)) {\n bg = adjustcolor(bg, ribbon.alpha)\n } else if (!is.null(col)) {\n bg = adjustcolor(col, ribbon.alpha)\n }\n }\n\n return(bg)\n}\n"], ["/tinyplot/R/type_spline.R", "#' Spline plot type\n#' \n#' @description Type function for plotting a cubic (or Hermite) spline interpolation.\n#' Arguments are passed to \\code{\\link[stats]{spline}}; see this latter function\n#' for default argument values.\n#' \n#' @inheritParams stats::spline\n#' @inherit stats::spline details\n#' @importFrom stats spline\n#' @examples\n#' # \"spline\" type convenience string\n#' tinyplot(dist ~ speed, data = cars, type = \"spline\")\n#' \n#' # Use `type_spline()` to pass extra arguments for customization\n#' tinyplot(dist ~ speed, data = cars, type = type_spline(method = \"natural\", n = 25),\n#' add = TRUE, lty = 2)\n#' @export\ntype_spline = function(\n n = NULL,\n method = \"fmm\",\n xmin = NULL,\n xmax = NULL,\n xout = NULL,\n ties = mean\n ) {\n out = list(\n draw = draw_lines(),\n data = data_spline(method = method, ties = ties, n = n, xmin = xmin, xmax = xmax, xout = xout),\n name = \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_spline = function(n, method, xmin, xmax, xout, ties, ...) {\n fun = function(datapoints, ...) {\n datapoints = split(datapoints, list(datapoints$facet, datapoints$by), drop = TRUE)\n datapoints = lapply(datapoints, function(dat) {\n if (is.null(n)) n = 3*length(dat$x)\n if (is.null(xmax)) xmax = max(dat$x)\n if (is.null(xmin)) xmin = min(dat$x)\n if (is.null(xout)) {\n fit = spline(x = dat$x, y = dat$y, n = n, method = method, xmin = xmin, xmax = xmax, ties = ties)\n } else {\n fit = spline(x = dat$x, y = dat$y, n = n, method = method, xmin = xmin, xmax = xmax, xout = xout, ties = ties)\n }\n fit = as.data.frame(fit)\n fit$facet = dat$facet[1]\n fit$by = dat$by[1]\n fit\n return(fit)\n })\n datapoints = do.call(rbind, datapoints)\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_segments.R", "#' Line segments plot type\n#'\n#' @description Type function for plotting line segments.\n#' \n#' @details Contrary to base \\code{\\link[graphics]{segments}}, line segments in\n#' [tinyplot] must be specified using the `xmin`, `ymin`,`xmax`, and `ymax`\n#' arguments. \n#' \n#' @examples\n#' # \"segments\" type convenience character string\n#' tinyplot(\n#' xmin = c(0,.1), ymin = c(.2,1), xmax = c(1,.9), ymax = c(.75,0),\n#' type = \"segments\"\n#' )\n#' \n#' # Same result with type_segments()\n#' tinyplot(\n#' xmin = c(0,.1), ymin = c(.2,1), xmax = c(1,.9), ymax = c(.75,0),\n#' type = type_segments()\n#' )\n#' \n#' @export\ntype_segments = function() {\n out = list(\n draw = draw_segments(),\n data = NULL,\n name = \"segments\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_segments = function() {\n fun = function(ixmin, iymin, ixmax, iymax, ilty, ilwd, icol, ...) {\n segments(\n x0 = ixmin, y0 = iymin, x1 = ixmax, y1 = iymax,\n lty = ilty,\n lwd = ilwd,\n col = icol\n )\n }\n return(fun)\n}\n"], ["/tinyplot/R/assertions.R", "check_dependency = function(library_name) {\n flag = requireNamespace(library_name, quietly = TRUE)\n if (isFALSE(flag)) {\n msg = sprintf(\"Please install the `%s` package.\", library_name)\n return(msg)\n } else {\n return(TRUE)\n }\n}\n\nassert_dependency = function(library_name) {\n flag = check_dependency(library_name)\n if (!isTRUE(flag)) stop(flag, call. = FALSE)\n return(invisible())\n}\n\nassert_choice = function(x, choice, null.ok = FALSE, name = as.character(substitute(x))) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(TRUE)\n }\n if (is.character(x) && length(x) == 1 && x %in% choice) {\n return(TRUE)\n }\n msg = sprintf(\n \"`%s` must be one of: %s\",\n name,\n paste(choice, collapse = \", \")\n )\n stop(msg, call. = FALSE)\n}\n\ncheck_true = function(x, null.ok = FALSE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(invisible(TRUE))\n }\n if (isTRUE(x)) {\n return(invisible(TRUE))\n }\n return(FALSE)\n}\n\nassert_true = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be true.\", name)\n if (!isTRUE(check_true(x, null.ok = null.ok))) {\n stop(msg, call. = FALSE)\n }\n}\n\ncheck_string = function(x, null.ok = FALSE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(invisible(TRUE))\n }\n if (is.character(x) && length(x) == 1) {\n return(invisible(TRUE))\n }\n return(FALSE)\n}\n\nassert_string = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be a string.\", name)\n if (!isTRUE(check_string(x, null.ok = null.ok))) {\n stop(msg, call. = FALSE)\n }\n}\n\ncheck_flag = function(x, null.ok = FALSE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(TRUE)\n }\n if (is.logical(x) && length(x) == 1) {\n return(TRUE)\n }\n return(FALSE)\n}\n\nassert_flag = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be a logical flag.\", name)\n if (!isTRUE(check_flag(x, null.ok = null.ok))) {\n stop(msg, call. = FALSE)\n }\n}\n\nassert_length = function(x, len = 1, null.ok = FALSE, name = as.character(substitute(x))) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(invisible(TRUE))\n }\n msg = sprintf(\"`%s` must be one of these lengths: %s\", name, paste(len, collapse = \", \"))\n if (!length(x) %in% len) {\n stop(msg, call. = FALSE)\n }\n}\n\nassert_logical = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(invisible(TRUE))\n }\n msg = sprintf(\"`%s` must be a logical vector\", name)\n if (!is.logical(x)) stop(msg, call. = FALSE)\n}\n\n\ncheck_integerish = function(x, len = NULL, lower = NULL, upper = NULL, null.ok = TRUE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(TRUE)\n }\n if (!is.numeric(x)) {\n return(FALSE)\n }\n x = stats::na.omit(x)\n if (!is.null(len) && length(x) != len) {\n return(FALSE)\n }\n if (!is.null(lower) && any(x < lower)) {\n return(FALSE)\n }\n if (!is.null(upper) && any(x > upper)) {\n return(FALSE)\n }\n if (isTRUE(any(abs(x - round(x)) > (.Machine$double.eps)^0.5))) {\n return(FALSE)\n }\n return(TRUE)\n}\n\nassert_integerish = function(x, len = NULL, lower = NULL, upper = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(invisible())\n }\n msg = sprintf(\"`%s` must be integer-ish\", name)\n if (is.null(x) && !isTRUE(null.ok)) stop(sprintf(\"%s should not be NULL.\", name), call. = FALSE)\n if (!isTRUE(check_integerish(x, len = len, lower = lower, upper = upper, null.ok = null.ok))) {\n if (!is.numeric(x)) msg = paste0(msg, \"; it is not numeric\")\n if (!is.null(len) && length(x) != len) msg = paste0(msg, sprintf(\"; its length must be %s\", len))\n if (!is.null(lower) && any(x < lower)) msg = paste0(msg, sprintf(\"; all values must be greater than or equal to %s\", lower))\n if (!is.null(upper) && any(x > upper)) msg = paste0(msg, sprintf(\"; all values must be less than or equal to %s\", upper))\n if (isTRUE(any(abs(x - round(x)) > (.Machine$double.eps)^0.5))) msg = paste0(msg, \"; all values must be close to integers\")\n stop(msg, call. = FALSE)\n }\n}\n\ncheck_numeric = function(x, len = NULL, lower = NULL, upper = NULL, null.ok = TRUE) {\n if (is.null(x) && isTRUE(null.ok)) {\n return(TRUE)\n }\n if (!is.numeric(x)) {\n return(FALSE)\n }\n if (!is.null(len) && length(x) != len) {\n return(FALSE)\n }\n if (!is.null(lower) && any(x < lower)) {\n return(FALSE)\n }\n if (!is.null(upper) && any(x > upper)) {\n return(FALSE)\n }\n return(TRUE)\n}\n\nassert_numeric = function(x, len = NULL, lower = NULL, upper = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be numeric\", name)\n if (!isTRUE(check_numeric(x, len = len, lower = lower, upper = upper, null.ok = null.ok))) {\n if (!is.null(len) && length(x) != len) msg = paste0(msg, sprintf(\"; its length must be %s\", len))\n if (!is.null(lower) && any(x < lower)) msg = paste0(msg, sprintf(\"; all values must be greater than or equal to %s\", lower))\n if (!is.null(upper) && any(x > upper)) msg = paste0(msg, sprintf(\"; all values must be less than or equal to %s\", upper))\n stop(msg, call. = FALSE)\n }\n}\n\nassert_data_frame = function(x, min_rows = 0, min_cols = 0, name = as.character(substitute(x))) {\n msg = sprintf(\"`%s` must be a data.frame.\", name)\n if (!is.data.frame(x)) stop(msg, call. = FALSE)\n msg = sprintf(\"Number of rows in `%s` must be at least `%s`\", name, min_rows)\n if (nrow(x) < min_rows) stop(msg, call. = FALSE)\n msg = sprintf(\"Number of columns in `%s` must be at least `%s`\", name, min_cols)\n if (ncol(x) < min_cols) stop(msg, call. = FALSE)\n}\n\n\ncheck_character = function(x, len = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(TRUE)\n } else if (!is.character(x)) {\n msg = sprintf(\"`%s` must be character.\", name)\n return(msg)\n } else if (!is.null(len) && length(x) != len) {\n msg = sprintf(\"`%s` must have length %s.\", name, len)\n return(msg)\n }\n return(TRUE)\n}\n\nassert_character = function(x, len = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n flag = check_character(x, len = len, null.ok = null.ok, name = name)\n if (!isTRUE(flag)) {\n stop(flag, call. = FALSE)\n } else {\n return(invisible(TRUE))\n }\n}\n\nassert_list = function(x, named = FALSE, len = NULL, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(invisible(TRUE))\n }\n if (!is.list(x)) stop(\"Input is not a list.\", call. = FALSE)\n if (isTRUE(named)) {\n if (is.null(names(x))) {\n stop(sprintf(\"`%s` should be named list.\", name), call. = FALSE)\n }\n }\n if (!is.null(len)) {\n if (length(x) != len) {\n stop(sprintf(\"`%s` must be of length %s.\", name, len), call. = FALSE)\n }\n }\n}\n\nassert_function = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(invisible(TRUE))\n }\n if (!is.function(x)) {\n msg = sprintf(\"`%s` must be a function.\", name)\n stop(msg, call. = FALSE)\n }\n}\n\ncheck_atomic_vector = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n if (isTRUE(null.ok) && is.null(x)) {\n return(invisible(TRUE))\n }\n # doesn't work on glue::glue() output\n # flag = is.atomic(x) && is.vector(x) && !is.list(x)\n flag = is.atomic(x) && is.null(dim(x)) && length(x) > 0 && !is.list(x)\n if (flag) {\n out = TRUE\n } else if (is.factor(x) && is.null(dim(x))) {\n out = TRUE\n } else {\n out = sprintf(\"`%s` must be an atomic vector.\", name)\n }\n return(out)\n}\n\nassert_atomic_vector = function(x, null.ok = FALSE, name = as.character(substitute(x))) {\n flag = check_atomic_vector(x, null.ok = null.ok, name = name)\n if (!isTRUE(flag)) {\n stop(flag, call. = FALSE)\n } else {\n return(invisible(TRUE))\n }\n}\n\nassert_class = function(x, classname) {\n if (!inherits(x, classname)) {\n msg = sprintf(\"`x` must be of class `%s`.\", classname)\n stop(msg, call. = FALSE)\n }\n}\n\n"], ["/tinyplot/R/type_jitter.R", "#' Jittered points plot type\n#'\n#' @description Type function for plotting jittered points.\n#' Arguments are passed to \\code{\\link[base]{jitter}}.\n#'\n#' @inheritParams base::jitter\n#' @inherit base::jitter details\n#' @examples\n#' # \"jitter\" type convenience string\n#' tinyplot(Sepal.Length ~ Species, data = iris, type = \"jitter\")\n#' \n#' # Use `type_jitter()` to pass extra arguments for customization\n#' tinyplot(Sepal.Length ~ Species, data = iris, type = type_jitter(factor = 0.5))\n#' @export\ntype_jitter = function(factor = 1, amount = NULL) {\n out = list(\n draw = draw_points(),\n data = data_jitter(factor = factor, amount = amount),\n name = \"p\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_jitter = function(factor, amount) {\n fun = function(datapoints, ...) {\n x = datapoints$x\n y = datapoints$y\n if (is.factor(x)) {\n xlvls = levels(x)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n x = as.integer(x)\n } else {\n xlabs = NULL\n }\n if (is.factor(y)) {\n ylvls = levels(y)\n ylabs = seq_along(ylvls)\n names(ylabs) = ylvls\n y = as.integer(y)\n } else {\n ylabs = NULL\n }\n x = jitter(x, factor = factor, amount = amount)\n y = jitter(y, factor = factor, amount = amount)\n\n datapoints$x = x\n datapoints$y = y\n\n out = list(\n datapoints = datapoints,\n x = x,\n y = y,\n xlabs = xlabs,\n ylabs = ylabs\n )\n return(out)\n }\n}\n\n"], ["/tinyplot/R/type_lines.R", "#' Lines plot type\n#'\n#' @description Type function for plotting lines.\n#' \n#' @inheritParams graphics::plot.default\n#' \n#' @examples\n#' # \"l\" type convenience character string\n#' tinyplot(circumference ~ age | Tree, data = Orange, type = \"l\")\n#' \n#' # Use `type_lines()` to pass extra arguments for customization\n#' tinyplot(circumference ~ age | Tree, data = Orange, type = type_lines(type = \"s\"))\n#' \n#' @export\ntype_lines = function(type = \"l\") {\n out = list(\n draw = draw_lines(type = type),\n data = NULL,\n name = type\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_lines = function(type = \"l\") {\n fun = function(ix, iy, icol, ipch, ibg, ilty, ilwd, cex = 1, ...) {\n lines(\n x = ix,\n y = iy,\n col = icol,\n type = type,\n pch = ipch,\n bg = ibg,\n lty = ilty,\n lwd = ilwd,\n cex = cex\n )\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_polypath.R", "#' Polypath polygon type\n#' \n#' @description Type function for plotting polygons.\n#' Arguments are passed to \\code{\\link[graphics]{polypath}}.\n#' \n#' @inheritParams graphics::polypath\n#' \n#' @examples\n#' # \"polypath\" type convenience character string\n#' tinyplot(\n#' c(.1, .1, .6, .6, NA, .4, .4, .9, .9),\n#' c(.1, .6, .6, .1, NA, .4, .9, .9, .4),\n#' type = \"polypath\", fill = \"grey\"\n#' )\n#' \n#' # Use `type_polypath()` to pass extra arguments for customization\n#' tinyplot(\n#' c(.1, .1, .6, .6, NA, .4, .4, .9, .9),\n#' c(.1, .6, .6, .1, NA, .4, .9, .9, .4),\n#' type = type_polypath(rule = \"evenodd\"), fill = \"grey\"\n#' )\n#' @export\ntype_polypath = function(rule = \"winding\") {\n draw_polypath = function() {\n fun = function(ix, iy, icol, ibg, ilty, ilwd, dots, ...) {\n polypath(\n x = ix,\n y = iy,\n border = icol,\n col = ibg,\n lty = ilty,\n lwd = ilwd,\n rule = rule\n )\n }\n return(fun)\n }\n\n out = list(\n draw = draw_polypath(),\n data = NULL,\n name = \"polypath\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n"], ["/tinyplot/R/type_rect.R", "#' Rectangle plot type\n#'\n#' @description Type function for plotting rectangles.\n#' \n#' @details Contrary to base \\code{\\link[graphics]{rect}}, rectangles in\n#' [tinyplot] must be specified using the `xmin`, `ymin`,`xmax`, and `ymax`\n#' arguments. \n#' \n#' @examples\n#' i = 4*(0:10)\n#' \n#' # \"rect\" type convenience character string\n#' tinyplot(\n#' xmin = 100+i, ymin = 300+i, xmax = 150+i, ymax = 380+i,\n#' by = i, fill = 0.2,\n#' type = \"rect\"\n#' )\n#' \n#' # Same result with type_rect()\n#' tinyplot(\n#' xmin = 100+i, ymin = 300+i, xmax = 150+i, ymax = 380+i,\n#' by = i, fill = 0.2,\n#' type = type_rect()\n#' )\n#' \n#' @export\ntype_rect = function() {\n out = list(\n draw = draw_rect(),\n data = NULL,\n name = \"rect\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_rect = function() {\n fun = function(ixmin, iymin, ixmax, iymax, ilty, ilwd, icol, ibg, ...) {\n rect(\n xleft = ixmin, ybottom = iymin, xright = ixmax, ytop = iymax,\n lty = ilty,\n lwd = ilwd,\n border = icol,\n col = ibg\n )\n }\n return(fun)\n}\n"], ["/tinyplot/R/type_lm.R", "#' Linear model plot type\n#'\n#' @description Type function for plotting a linear model fit.\n#' Arguments are passed to \\code{\\link[stats]{lm}}.\n#' \n#' @inheritParams type_glm\n#' @importFrom stats lm predict\n#' @examples\n#' # \"lm\" type convenience string\n#' tinyplot(Sepal.Width ~ Petal.Width, data = iris, type = \"lm\")\n#' \n#' # Grouped model fits (here: illustrating an example of Simpson's paradox)\n#' tinyplot(Sepal.Width ~ Petal.Width | Species, data = iris, type = \"lm\")\n#' tinyplot_add(type = \"p\")\n#' \n#' # Use `type_lm()` to pass extra arguments for customization\n#' tinyplot(Sepal.Width ~ Petal.Width, data = iris, type = type_lm(level = 0.8))\n#' @export\ntype_lm = function(se = TRUE, level = 0.95) {\n assert_flag(se)\n out = list(\n draw = draw_ribbon(),\n data = data_lm(se = se, level = level),\n name = if (isTRUE(se)) \"ribbon\" else \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_lm = function(se, level, ...) {\n fun = function(datapoints, ...) {\n dat = split(datapoints, list(datapoints$facet, datapoints$by))\n dat = lapply(dat, function(x) {\n if (nrow(x) == 0) return(x)\n if (nrow(x) < 3) {\n x$y = NA\n return(x)\n }\n fit = lm(y ~ x, data = x)\n nd = data.frame(x = seq(min(x$x, na.rm = TRUE), max(x$x, na.rm = TRUE), length.out = 100))\n nd$by = x$by[1]\n nd$facet = x$facet[1]\n if (se == TRUE) {\n p = predict(fit, newdata = nd, se.fit = TRUE)\n p = ci(p$fit, p$se.fit, conf.level = level, fit$df.residual)\n nd$y = p$estimate\n nd$ymax = p$conf.high\n nd$ymin = p$conf.low\n } else {\n nd$y = predict(fit, newdata = nd)\n }\n nd\n })\n datapoints = do.call(rbind, dat)\n datapoints = datapoints[order(datapoints$facet, datapoints$by, datapoints$x), ]\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_polygon.R", "#' Polygon plot type\n#'\n#' @description Type function for plotting polygons.\n#' Arguments are passed to \\code{\\link[graphics]{polygon}}.\n#' \n#' @inheritParams graphics::polygon\n#' \n#' @examples\n#' # \"polygon\" type convenience character string\n#' tinyplot(1:9, c(2,1,2,1,NA,2,1,2,1), type = \"polygon\")\n#' \n#' # Use `type_polygon()` to pass extra arguments for customization\n#' tinyplot(1:9, c(2,1,2,1,NA,2,1,2,1), type = type_polygon(density = c(10, 20)))\n#' \n#' @export\ntype_polygon = function(density = NULL, angle = 45) {\n out = list(\n draw = draw_polygon(density = density, angle = angle),\n data = NULL,\n name = \"polygon\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndraw_polygon = function(density = density, angle = 45) {\n fun = function(ix, iy, icol, ibg, ilty = par(\"lty\"), ilwd = par(\"lwd\"), ...) {\n polygon(\n x = ix,\n y = iy,\n border = icol,\n col = ibg,\n lty = ilty,\n lwd = ilwd,\n density = density,\n angle = angle\n )\n }\n return(fun)\n}\n"], ["/tinyplot/R/tinyplot_add.R", "#' Add new elements to the current `tinyplot`\n#'\n#' @description\n#' This convenience function grabs the preceding `tinyplot` call and updates it\n#' with any new arguments that have been explicitly provided by the user. It\n#' then injects `add=TRUE` and evaluates the updated call, thereby drawing a new\n#' layer on top of the existing plot. `plt_add()` is a shorthand alias for\n#' `tinyplot_add()`.\n#'\n#' @section Limitations:\n#' - `tinyplot_add()` works reliably only when adding to a plot originally\n#' created using the [`tinyplot.formula`] method with a valid `data` argument.\n#' We cannot guarantee correct behavior if the original plot was created with\n#' the atomic [`tinyplot.default`] method, due to potential environment\n#' mismatches. (An exception is when the original plot arguments---`x`, `y`,\n#' etc.---are located in the global environment.)\n#'\n#' - Automatic legends for the added elements will be turned off.\n#'\n#' @param ... All named arguments override arguments from the previous calls.\n#' Arguments not supplied to [tinyplot_add] remain unchanged from the previous\n#' call.\n#'\n#' @examples\n#' tinyplot(Sepal.Width ~ Sepal.Length | Species,\n#' facet = ~Species,\n#' data = iris)\n#'\n#' tinyplot_add(type = \"lm\") ## or : plt_add(type = \"lm\")\n#'\n#' ## Note: the previous function is equivalent to (but much more convenient\n#' ## than) re-writing the full call with the new type and `add=TRUE`:\n#'\n#' # tinyplot(Sepal.Width ~ Sepal.Length | Species,\n#' # facet = ~Species,\n#' # data = iris,\n#' # type = \"lm\",\n#' # add = TRUE)\n#'\n#' @returns No return value, called for side effect of producing a plot.\n#'\n#' @export\ntinyplot_add = function(...) {\n cal = getOption(\"tinyplot_last_call\", default = NULL)\n\n ## TODO: remove the global option above and move to this when density is refactored\n # cal = get(\".last_call\", envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n\n if (is.null(cal)) {\n stop(\"No previous tinyplot call found.\")\n }\n\n args = list(...)\n for (n in names(args)) {\n if (n != \"\") {\n cal[[n]] = args[[n]]\n }\n }\n\n # allow first argument in tinyplot_add() to be unnamed\n if (isTRUE(names(args)[1] == \"\")) {\n cal[[2]] = args[[1]]\n }\n\n cal[[\"add\"]] = TRUE\n eval(cal)\n}\n\n\n\n#' @export\n#' @name plt_add\n#' @rdname tinyplot_add\nplt_add = tinyplot_add\n"], ["/tinyplot/R/type_loess.R", "#' Local polynomial regression plot type\n#' \n#' @description Type function for plotting a LOESS (LOcal regrESSion) fit.\n#' Arguments are passed to \\code{\\link[stats]{loess}}.\n#' \n#' @inheritParams stats::loess\n#' @param se logical. If `TRUE` (the default), confidence intervals are drawn.\n#' @param level the confidence level required if `se = TRUE`. Default is 0.95.\n#' @importFrom stats loess loess.control predict\n#' @examples\n#' # \"loess\" type convenience string\n#' tinyplot(dist ~ speed, data = cars, type = \"loess\")\n#' \n#' # Use `type_loess()` to pass extra arguments for customization\n#' tinyplot(dist ~ speed, data = cars, type = type_loess(span = 0.5, degree = 1))\n#' @export\ntype_loess = function(\n span = 0.75,\n degree = 2,\n family = \"gaussian\",\n control = loess.control(),\n se = TRUE,\n level = 0.95\n ) {\n out = list(\n draw = draw_ribbon(),\n data = data_loess(span = span, degree = degree, family = family, control = control, se = se, level = level),\n name = if (isTRUE(se)) \"ribbon\" else \"l\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_loess = function(span, degree, family, control, se, level, ...) {\n fun = function(datapoints, ...) {\n datapoints = split(datapoints, list(datapoints$facet, datapoints$by))\n datapoints = Filter(function(k) nrow(k) > 0, datapoints)\n datapoints = lapply(datapoints, function(dat) {\n fit = loess(y ~ x, data = dat, span = span, degree = degree, family = family, control = control)\n if (se == TRUE) {\n p = predict(fit, newdata = dat, se = TRUE)\n p = ci(p$fit, p$se.fit, conf.level = level, p$df)\n dat$y = p$estimate\n dat$ymax = p$conf.high\n dat$ymin = p$conf.low\n } else {\n dat$y = predict(fit, dat)\n }\n dat\n })\n datapoints = do.call(rbind, datapoints)\n datapoints = datapoints[order(datapoints$facet, datapoints$by, datapoints$x), ]\n out = list(datapoints = datapoints)\n return(out)\n }\n return(fun)\n}\n\n"], ["/tinyplot/R/type_pointrange.R", "#' @rdname type_errorbar\n#' @export\ntype_pointrange = function() {\n out = list(\n draw = draw_pointrange(),\n data = data_pointrange(),\n name = \"p\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\n\ndraw_pointrange = function() {\n fun = function(ix, iy, ixmin, iymin, ixmax, iymax, icol, ibg, ipch, ilwd, cex, ...) {\n segments(\n x0 = ixmin,\n y0 = iymin,\n x1 = ixmax,\n y1 = iymax,\n col = icol,\n lwd = ilwd\n )\n draw_points()(ix = ix, iy = iy, icol = icol, ibg = ibg, ipch = ipch, ilwd = ilwd, cex = cex)\n }\n return(fun)\n}\n\n\ndata_pointrange = function() {\n fun = function(datapoints, xlabs, ...) {\n if (is.character(datapoints$x)) datapoints$x = as.factor(datapoints$x)\n if (is.factor(datapoints$x)) {\n ## original data (i.e., no new sorting by factor)\n xlvls = unique(datapoints$x)\n datapoints$x = factor(datapoints$x, levels = xlvls)\n xlabs = seq_along(xlvls)\n names(xlabs) = xlvls\n datapoints$x = as.integer(datapoints$x)\n }\n datapoints$xmin = datapoints$x\n datapoints$xmax = datapoints$x\n out = list(\n x = datapoints$x,\n xlabs = xlabs,\n datapoints = datapoints)\n\n return(out)\n }\n return(fun)\n}\n"], ["/tinyplot/R/sanitize.R", "sanitize_ribbon.alpha = function(ribbon.alpha) {\n assert_numeric(ribbon.alpha, len = 1, lower = 0, upper = 1, null.ok = TRUE)\n if (is.null(ribbon.alpha)) ribbon.alpha = .tpar[[\"ribbon.alpha\"]]\n return(ribbon.alpha)\n}\n\n\n\nsanitize_type = function(type, x, y, dots) {\n if (inherits(type, \"tinyplot_type\")) {\n return(type)\n }\n\n known_types = c(\n \"p\", \"l\", \"o\", \"b\", \"c\", \"h\", \"j\", \"s\", \"S\", \"n\", \n \"abline\",\n \"area\",\n \"bar\", \"barplot\",\n \"box\", \"boxplot\",\n \"density\",\n \"errorbar\",\n \"function\",\n \"glm\",\n \"hist\", \"histogram\",\n \"hline\",\n \"j\", \"jitter\",\n \"lines\",\n \"lm\",\n \"loess\",\n \"pointrange\",\n \"points\",\n \"polygon\", \"polypath\",\n \"qq\",\n \"rect\",\n \"ribbon\",\n \"ridge\",\n \"rug\",\n \"segments\",\n \"spine\", \"spineplot\",\n \"spline\",\n \"summary\",\n \"text\",\n \"violin\",\n \"vline\"\n )\n assert_choice(type, known_types, null.ok = TRUE)\n\n if (is.null(type)) {\n if (!is.null(x) && (is.factor(x) || is.character(x)) && !(is.factor(y) || is.character(y))) {\n # enforce boxplot type for y ~ factor(x)\n type = type_boxplot\n } else if (is.factor(y) || is.character(y)) {\n # enforce spineplot type for factor(y) ~ x\n type = type_spineplot\n } else {\n type = \"p\"\n }\n }\n\n if (is.character(type)) type = switch(type,\n \"abline\" = type_abline,\n \"area\" = type_area,\n \"bar\" = type_barplot,\n \"barplot\" = type_barplot,\n \"box\" = type_boxplot,\n \"boxplot\" = type_boxplot,\n \"density\" = type_density,\n \"errorbar\" = type_errorbar,\n \"function\" = type_function,\n \"glm\" = type_glm,\n \"hist\" = type_histogram,\n \"histogram\" = type_histogram,\n \"hline\" = type_hline,\n \"j\" = type_jitter,\n \"jitter\" = type_jitter,\n \"lines\" = type_lines,\n \"lm\" = type_lm,\n \"loess\" = type_loess,\n \"p\" = type_points,\n \"pointrange\" = type_pointrange,\n \"points\" = type_points,\n \"polygon\" = type_polygon,\n \"polypath\" = type_polypath,\n \"qq\" = type_qq,\n \"rect\" = type_rect,\n \"ribbon\" = type_ribbon,\n \"ridge\" = type_ridge,\n \"rug\" = type_rug,\n \"segments\" = type_segments,\n \"spine\" = type_spineplot,\n \"spineplot\" = type_spineplot,\n \"spline\" = type_spline,\n \"summary\" = type_summary,\n \"text\" = type_text,\n \"violin\" = type_violin,\n \"vline\" = type_vline,\n type # default case\n )\n \n if (is.function(type)) {\n args = intersect(names(formals(type)), names(dots))\n args = if (length(args) >= 1L) dots[args] else list()\n type = do.call(type, args)\n type$dots = dots[setdiff(names(dots), names(args))]\n }\n \n if (inherits(type, \"tinyplot_type\")) return(type)\n\n out = list(draw = NULL, data = NULL, name = type)\n return(out)\n}\n"], ["/tinyplot/R/tinyformula.R", "## auxiliary functions for formula/facet parsing\n\ntinyformula = function(formula, facet = NULL) {\n ## input\n ## - formula: y ~ x or y ~ x | z or ~ x or ~ x | z\n ## - facet: ~ a or ~ a + b or b ~ a\n ##\n ## output:\n ## - x: ~ x\n ## - y: NULL or ~ y\n ## - by: NULL or ~ z or ~ z1 + z2 + ... (use interaction of all)\n ## - xfacet: NULL or ~ a or ~ a + b etc.\n ## - yfacet: NULL or ~ b\n ## - full: e.g. ~ x + y + z + a + b\n\n ## preliminaries\n if (!inherits(formula, \"formula\")) formula = as.formula(formula)\n nf = length(formula)\n\n ## basic formula types\n x = ~ x\n y = if (nf == 2L) NULL else ~ y\n by = if (!inherits(formula[[nf]], \"call\") || formula[[nf]][[1L]] != as.name(\"|\")) NULL else ~ z\n if (is.null(facet) || !inherits(facet, \"formula\")) {\n xfacet = NULL\n yfacet = NULL\n } else {\n xfacet = ~ a\n yfacet = if (length(facet) == 2L) NULL else ~ b\n }\n\n ## fill with actual terms\n environment(x) = environment(formula)\n if (!is.null(y)) {\n environment(y) = environment(formula)\n y[[2L]] = formula[[2L]]\n }\n if (is.null(by)) {\n x[[2L]] = formula[[nf]]\n } else {\n environment(by) = environment(formula)\n by[[2L]] = formula[[nf]][[3L]]\n x[[2L]] = formula[[nf]][[2L]]\n }\n if (!is.null(xfacet)) {\n environment(xfacet) = environment(formula)\n xfacet[[2L]] = facet[[length(facet)]]\n }\n if (!is.null(yfacet)) {\n environment(yfacet) = environment(formula)\n yfacet[[2L]] = facet[[2L]]\n }\n\n ## combine everything\n full = x\n if (!is.null(y)) full[[2L]] = call(\"+\", full[[2L]], y[[2L]])\n if (!is.null(by)) full[[2L]] = call(\"+\", full[[2L]], by[[2L]])\n if (!is.null(xfacet)) full[[2L]] = call(\"+\", full[[2L]], xfacet[[2L]])\n if (!is.null(yfacet)) full[[2L]] = call(\"+\", full[[2L]], yfacet[[2L]])\n\n ## return list of all formulas\n return(list(\n x = x,\n y = y,\n by = by,\n xfacet = xfacet,\n yfacet = yfacet,\n full = full\n ))\n}\n\ntinyframe = function(formula, data, drop = FALSE) {\n ## input\n ## - formula: (sub-)formula\n ## - data: model.frame from full formula\n if (is.null(formula)) return(NULL)\n names = sapply(attr(terms(formula), \"variables\")[-1L], deparse, width.cutoff = 500L)\n data[, names, drop = drop]\n}\n"], ["/tinyplot/R/hooks.R", "# Copied from https://raw.githubusercontent.com/r-lib/evaluate/refs/heads/main/R/hooks.R\n# license: MIT + file LICENSE\n\n\n\n#' Set and remove hooks\n#'\n#' This interface wraps the base [setHook()] function to provide a return\n#' value that makes it easy to undo.\n#'\n#' @param hooks a named list of hooks - each hook can either be a function or\n#' a list of functions.\n#' @param action `\"replace\"`, `\"append\"` or `\"prepend\"`\n#' @keywords internal\nset_hooks <- function(hooks, action = \"append\") {\n old <- list()\n for (hook_name in names(hooks)) {\n old[[hook_name]] <- getHook(hook_name)\n setHook(hook_name, hooks[[hook_name]], action = action)\n }\n invisible(old)\n}\n\n#' @rdname set_hooks\n#' @keywords internal\nremove_hooks <- function(hooks) {\n for (hook_name in names(hooks)) {\n hook <- getHook(hook_name)\n if (length(hook) > 0) {\n for (fun in unlist(hooks[hook_name])) {\n hook[sapply(hook, identical, fun)] <- NULL\n }\n }\n setHook(hook_name, hook, \"replace\")\n }\n}\n"], ["/tinyplot/R/type_area.R", "#' @rdname type_ribbon\n#' @export\ntype_area = function(alpha = NULL) {\n out = list(\n draw = NULL,\n data = data_area(alpha = alpha),\n name = \"area\"\n )\n class(out) = \"tinyplot_type\"\n return(out)\n}\n\n\ndata_area = function(alpha = alpha) {\n ribbon.alpha = if (is.null(alpha)) .tpar[[\"ribbon.alpha\"]] else (alpha)\n fun = function(datapoints, ...) {\n datapoints$ymax = datapoints$y\n datapoints$ymin = rep.int(0, nrow(datapoints))\n out = list(\n datapoints = datapoints,\n ymax = datapoints$ymax,\n ymin = datapoints$ymin,\n type = \"ribbon\",\n ribbon.alpha = ribbon.alpha\n )\n return(out)\n }\n return(fun)\n}\n"], ["/tinyplot/R/utils.R", "rescale_num = function (x, from = NULL, to = NULL) {\n if (is.null(from)) from = range(x)\n if (is.null(to)) to = c(0, 1)\n (x - from[1])/diff(from) * diff(to) + to[1]\n}\n\n## Function for efficiently checking whether a vector has more than n unique\n## values (uses a hash set approach for large vectors to check sequentially)\nmore_than_n_unique = function(x, n, small_vec_len = 1e3L) {\n len_x = length(x)\n # For \"small\" vectors, just use direct length(unique(x)) approach\n if (len_x <= small_vec_len) {\n return(length(unique(x)) > n)\n } else {\n # For larger vectors, use the hash set approach\n env = new.env(hash = TRUE, size = n)\n count = 0\n for (val in x) {\n if (!exists(as.character(val), env)) {\n assign(as.character(val), TRUE, env)\n count = count + 1\n if (count > n) {\n return(TRUE)\n }\n }\n }\n return(FALSE)\n }\n}\n\n\n## Null coalescing operator\nif (getRversion() <= \"4.4.0\") {\n `%||%` = function(x, y) if (is.null(x)) y else x\n}\n\n\n## Function that computes an appropriate bandwidth kernel based on a string\n## input\nbw_fun = function(kernel, x) {\n kernel = tolower(kernel)\n switch(\n kernel,\n nrd0 = bw.nrd0(x),\n nrd = bw.nrd(x),\n ucv = bw.ucv(x),\n bcv = bw.bcv(x),\n sj = bw.SJ(x),\n stop(\"Invalid `bw` string. Choose from 'nrd0', 'nrd', 'ucv', 'bcv', or 'SJ'.\")\n )\n}\n"], ["/tinyplot/R/lim.R", "# calculate limits of each plot\n\nlim_args = function(\n datapoints,\n xlim, ylim,\n xaxb = NULL, yaxb = NULL,\n xlim_user = FALSE, ylim_user = FALSE,\n type\n) {\n \n if (is.null(xlim)) {\n xlim = range(c(datapoints[[\"x\"]], datapoints[[\"xmin\"]],\n datapoints[[\"xmax\"]]), finite = TRUE)\n }\n if (is.null(ylim)) {\n ylim = range(c(datapoints[[\"y\"]], datapoints[[\"ymin\"]],\n datapoints[[\"ymax\"]]), finite = TRUE)\n }\n\n if (identical(type, \"boxplot\")) {\n xlim = xlim + c(-0.5, 0.5)\n }\n \n if (!xlim_user && !is.null(xaxb) && type != \"spineplot\") xlim = range(c(xlim, xaxb))\n if (!ylim_user && !is.null(yaxb) && type != \"spineplot\") ylim = range(c(ylim, yaxb))\n\n out = list(xlim = xlim, ylim = ylim)\n return(out)\n}\n\n"], ["/tinyplot/R/zzz.R", "#' Operations on package load\n#' @importFrom utils globalVariables\n#' @param libname library name\n#' @param pkgname package name name\n#' @keywords internal\n#' @noRd\n.onLoad = function(libname, pkgname) {\n # https://stackoverflow.com/questions/12598242/global-variables-in-packages-in-r\n # https://stackoverflow.com/questions/49056642/r-how-to-make-variable-available-to-namespace-at-loading-time?noredirect=1&lq=1\n init_environment()\n init_tpar()\n set_environment_variable(\".saved_par_before\", NULL)\n set_environment_variable(\".saved_par_after\", NULL)\n set_environment_variable(\".saved_par_first\", NULL)\n set_environment_variable(\".last_call\", NULL)\n set_environment_variable(\".tpar_hooks\", NULL)\n\n globalVariables(c(\n \"add\",\n \"asp\",\n \"axes\",\n \"by_continuous\",\n \"by_ordered\",\n \"cex_fct_adj\",\n \"dots\",\n \"draw\",\n \"facet_bg\",\n \"facet_border\",\n \"facet_col\",\n \"facet_font\",\n \"facet_newlines\",\n \"facet_rect\",\n \"facet_text\",\n \"facet.args\",\n \"facet\",\n \"facets\",\n \"fill\",\n \"flip\",\n \"frame.plot\",\n \"has_legend\",\n \"iby\",\n \"ifacet\",\n \"nfacet_cols\",\n \"nfacet_rows\",\n \"nfacets\",\n \"ngrps\",\n \"oxaxis\",\n \"oyaxis\",\n \"ribbon.alpha\",\n \"split_data\",\n \"type\",\n \"x\",\n \"xaxl\",\n \"xaxs\",\n \"xaxt\",\n \"xlabs\",\n \"xlim\",\n \"xlim_user\",\n \"xlvls\",\n \"xmax\",\n \"xmin\",\n \"y\",\n \"yaxl\",\n \"yaxs\",\n \"yaxt\",\n \"ylabs\",\n \"ylim\",\n \"ylim_user\",\n \"ymax\",\n \"ymin\"\n ))\n}\n"], ["/tinyplot/R/setup_device.R", "setup_device = function(file, width, height) {\n # write to file\n if (!is.null(file)) {\n filepath = file\n filewidth = width\n fileheight = height\n if (is.null(filewidth)) filewidth = .tpar[[\"file.width\"]]\n if (is.null(fileheight)) fileheight = .tpar[[\"file.height\"]]\n fileres = .tpar[[\"file.res\"]]\n # catch to close interactive device if one isn't already open\n fkdev = is.null(dev.list())\n # grab existing device pars to pass on to next one\n dop = par(no.readonly = TRUE)\n # close interactive device if not already open\n if (isTRUE(fkdev)) dev.off()\n exttype = file_ext(filepath)\n if (exttype == \"pdf\" && .tpar[[\"cairo\"]]) {\n exttype = \"cairo\"\n } else if (exttype == \"jpg\") {\n exttype = \"jpeg\"\n }\n switch(exttype,\n png = png(filepath, width = filewidth, height = fileheight, units = \"in\", res = fileres),\n jpeg = jpeg(filepath, width = filewidth, height = fileheight, units = \"in\", res = fileres),\n pdf = pdf(filepath, width = filewidth, height = fileheight),\n cairo = cairo_pdf(filepath, width = filewidth, height = fileheight),\n svg = svg(filepath, width = filewidth, height = fileheight),\n stop(\"\\nUnsupported file extension. Only '.png', '.jpg', '.pdf', or '.svg' are allowed.\\n\")\n )\n dop$new = FALSE # catch for some interfaces\n par(dop)\n\n # interactive plot with user-specified width/height\n } else if (!is.null(width) || !is.null(height)) {\n devwidth = width\n devheight = height\n # if one of width or height is missing, set equal to the other\n if (is.null(devwidth)) devwidth = devheight\n if (is.null(devheight)) devheight = devwidth\n # catch to close interactive device if one isn't already open\n fkdev = is.null(dev.list())\n # grab existing device pars to pass on to next one\n dop = par(no.readonly = TRUE)\n # close interactive device if not already open\n if (isTRUE(fkdev)) dev.off()\n dev.new(width = devwidth, height = devheight)\n dop$new = FALSE # catch for some interfaces\n par(dop)\n }\n}\n"], ["/tinyplot/R/environment.R", "init_environment = function() {\n tnypltptns = parent.env(environment())\n assign(\".tinyplot_env\", new.env(), envir = tnypltptns)\n .tpar = new.env()\n assign(\".tpar\", .tpar, envir = tnypltptns)\n}\n\nget_environment_variable = function(name) {\n get(name, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n}\n\nset_environment_variable = function(name, value) {\n assign(name, value, envir = get(\".tinyplot_env\", envir = parent.env(environment())))\n}\n"], ["/tinyplot/R/tinyplot-package.R", "#' @keywords internal\n\"_PACKAGE\"\n\nNULL\n"]], "task_instance_info": {"created_time": "2025-08-21 01:20:29", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(adj = NULL, pos = NULL, offset = 0.5, vfont = NULL, font = NULL, xpd = NULL, srt = 0) {}", "code_description": "This code segment functions to: Configure graphical parameters for rendering text elements within a coordinate system and execute the display of formatted annotations with positional adjustments, rotation settings, and font specifications."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\ndraw_text = function(adj = NULL, pos = NULL, offset = 0.5, vfont = NULL, font = NULL, xpd = NULL, srt = 0) {\n function(elements, ...) {\n with(elements, {\n graphics::text(\n x = coords$x,\n y = coords$y,\n labels = data$datapoints$labels,\n adj = adj,\n pos = pos,\n offset = offset,\n vfont = vfont,\n font = font,\n xpd = xpd,\n srt = srt\n )\n })\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-21-00"}, "editdistance_info": {"edit_distance": 49.3151, "calculate_time": "2025-08-21 01:21:00", "true_code_clean": "function(adj = NULL, pos = NULL, offset = 0.5, vfont = NULL, font = NULL, xpd = NULL, srt = 0) {\n if (is.null(xpd)) xpd = par(\"xpd\")\n fun = function(ix, iy, ilabels, icol, cex, ...) {\n text(\n x = ix, y = iy, labels = ilabels, col = icol,\n adj = adj, pos = pos, offset = offset,\n vfont = vfont, font = font,\n xpd = xpd,\n srt = srt,\n cex = cex\n )\n }\n}", "predict_code_clean": "draw_text = function(adj = NULL, pos = NULL, offset = 0.5, vfont = NULL, font = NULL, xpd = NULL, srt = 0) {\n function(elements, ...) {\n with(elements, {\n graphics::text(\n x = coords$x,\n y = coords$y,\n labels = data$datapoints$labels,\n adj = adj,\n pos = pos,\n offset = offset,\n vfont = vfont,\n font = font,\n xpd = xpd,\n srt = srt\n )\n })\n }\n}"}}