-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathutilities-grid.R
83 lines (74 loc) · 2.08 KB
/
utilities-grid.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#' @export
grid::unit
#' @export
grid::arrow
# Name ggplot grid object
# Convenience function to name grid objects
#
# @keyword internal
ggname <- function(prefix, grob) {
grob$name <- grobName(grob, prefix)
grob
}
#' Interpreter for graphical parameters
#'
#' This is a wrapper for [`grid::gpar()`] that applies ggplot2's interpretation
#' of graphical parameters.
#'
#' @param ... Named arguments passed on to `gpar()`.
#' @param stroke Linewidth for points. Populates the `lwd` grid parameter.
#' @param pointsize Size for points. Populates the `fontsize` grid parameter.
#'
#' @return An object of class 'gpar'.
#' @keywords internal
#' @export
gg_par <- function(..., stroke = NULL, pointsize = NULL) {
args <- list2(...)
args <- args[lengths(args) > 0]
if (!is.null(args$lwd)) {
args$lwd <- args$lwd * .pt
}
if (!is.null(stroke)) {
args$lwd <- stroke * .stroke / 2
}
if (!is.null(pointsize)) {
# Stroke is added around the outside of the point
stroke <- stroke %||% 0
stroke[is.na(stroke)] <- 0
args$fontsize <- pointsize * .pt + stroke * .stroke / 2
}
if (!is.null(args$lty) && anyNA(args$lty)) {
args$lty[is.na(args$lty)] <- if (is.character(args$lty)) "blank" else 0
}
inject(gpar(!!!args))
}
#' The zero grob draws nothing and has zero size.
#'
#' @keywords internal
#' @export
zeroGrob <- function() .zeroGrob
.zeroGrob <- NULL
on_load(.zeroGrob <- add_class(nullGrob(), "zeroGrob"))
is.zero <- function(x) is.null(x) || inherits(x, "null")
width_cm <- function(x) {
if (is.grob(x)) {
convertWidth(grobWidth(x), "cm", TRUE)
} else if (is.unit(x)) {
convertWidth(x, "cm", TRUE)
} else if (is.list(x)) {
vapply(x, width_cm, numeric(1))
} else {
cli::cli_abort("Don't know how to get width of {.cls {class(x)}} object")
}
}
height_cm <- function(x) {
if (is.grob(x)) {
convertHeight(grobHeight(x), "cm", TRUE)
} else if (is.unit(x)) {
convertHeight(x, "cm", TRUE)
} else if (is.list(x)) {
vapply(x, height_cm, numeric(1))
} else {
cli::cli_abort("Don't know how to get height of {.cls {class(x)}} object")
}
}