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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
|
#' Specify a secondary axis
#'
#' This function is used in conjunction with a position scale to create a
#' secondary axis, positioned opposite of the primary axis. All secondary
#' axes must be based on a one-to-one transformation of the primary axes.
#'
#' @param trans A formula or function of transformation
#'
#' @param name The name of the secondary axis
#'
#' @param breaks One of:
#' - `NULL` for no breaks
#' - `waiver()` for the default breaks computed by the transformation object
#' - A numeric vector of positions
#' - A function that takes the limits as input and returns breaks as output
#'
#' @param labels One of:
#' - `NULL` for no labels
#' - `waiver()` for the default labels computed by the transformation object
#' - A character vector giving labels (must be same length as `breaks`)
#' - A function that takes the breaks as input and returns labels as output
#'
#' @param guide A position guide that will be used to render
#' the axis on the plot. Usually this is [guide_axis()].
#'
#' @details
#' `sec_axis()` is used to create the specifications for a secondary axis.
#' Except for the `trans` argument any of the arguments can be set to
#' `derive()` which would result in the secondary axis inheriting the
#' settings from the primary axis.
#'
#' `dup_axis()` is provide as a shorthand for creating a secondary axis that
#' is a duplication of the primary axis, effectively mirroring the primary axis.
#'
#' As of v3.1, date and datetime scales have limited secondary axis capabilities.
#' Unlike other continuous scales, secondary axis transformations for date and datetime scales
#' must respect their primary POSIX data structure.
#' This means they may only be transformed via addition or subtraction, e.g.
#' `~ . + hms::hms(days = 8)`, or
#' `~ . - 8*60*60`. Nonlinear transformations will return an error.
#' To produce a time-since-event secondary axis in this context, users
#' may consider adapting secondary axis labels.
#'
#' @examples
#' p <- ggplot(mtcars, aes(cyl, mpg)) +
#' geom_point()
#'
#' # Create a simple secondary axis
#' p + scale_y_continuous(sec.axis = sec_axis(~ . + 10))
#'
#' # Inherit the name from the primary axis
#' p + scale_y_continuous("Miles/gallon", sec.axis = sec_axis(~ . + 10, name = derive()))
#'
#' # Duplicate the primary axis
#' p + scale_y_continuous(sec.axis = dup_axis())
#'
#' # You can pass in a formula as a shorthand
#' p + scale_y_continuous(sec.axis = ~ .^2)
#'
#' # Secondary axes work for date and datetime scales too:
#' df <- data.frame(
#' dx = seq(
#' as.POSIXct("2012-02-29 12:00:00", tz = "UTC"),
#' length.out = 10,
#' by = "4 hour"
#' ),
#' price = seq(20, 200000, length.out = 10)
#' )
#'
#' # This may useful for labelling different time scales in the same plot
#' ggplot(df, aes(x = dx, y = price)) +
#' geom_line() +
#' scale_x_datetime(
#' "Date",
#' date_labels = "%b %d",
#' date_breaks = "6 hour",
#' sec.axis = dup_axis(
#' name = "Time of Day",
#' labels = scales::time_format("%I %p")
#' )
#' )
#'
#' # or to transform axes for different timezones
#' ggplot(df, aes(x = dx, y = price)) +
#' geom_line() +
#' scale_x_datetime("
#' GMT",
#' date_labels = "%b %d %I %p",
#' sec.axis = sec_axis(
#' ~ . + 8 * 3600,
#' name = "GMT+8",
#' labels = scales::time_format("%b %d %I %p")
#' )
#' )
#'
#' @export
sec_axis <- function(trans = NULL, name = waiver(), breaks = waiver(), labels = waiver(),
guide = waiver()) {
# sec_axis() historically accpeted two-sided formula, so be permissive.
if (length(trans) > 2) trans <- trans[c(1,3)]
trans <- as_function(trans)
ggproto(NULL, AxisSecondary,
trans = trans,
name = name,
breaks = breaks,
labels = labels,
guide = guide
)
}
#' @rdname sec_axis
#'
#' @export
dup_axis <- function(trans = ~., name = derive(), breaks = derive(), labels = derive(), guide = derive()) {
sec_axis(trans, name, breaks, labels, guide)
}
is.sec_axis <- function(x) {
inherits(x, "AxisSecondary")
}
set_sec_axis <- function(sec.axis, scale) {
if (!is.waive(sec.axis)) {
if (is.formula(sec.axis)) sec.axis <- sec_axis(sec.axis)
if (!is.sec_axis(sec.axis)) {
cli::cli_abort("Secondary axes must be specified using {.fn sec_axis}")
}
scale$secondary.axis <- sec.axis
}
return(scale)
}
#' @rdname sec_axis
#'
#' @export
derive <- function() {
structure(list(), class = "derived")
}
is.derived <- function(x) {
inherits(x, "derived")
}
#' @rdname ggplot2-ggproto
#' @format NULL
#' @usage NULL
#' @export
AxisSecondary <- ggproto("AxisSecondary", NULL,
trans = NULL,
axis = NULL,
name = waiver(),
breaks = waiver(),
labels = waiver(),
# This determines the quality of the remapping from the secondary axis and
# back to the primary axis i.e. the exactness of the placement of the
# breakpoints of the secondary axis.
detail = 1000,
empty = function(self) {
is.null(self$trans)
},
# Inherit settings from the primary axis/scale
init = function(self, scale) {
if (self$empty()) {
return()
}
if (!is.function(self$trans)) {
cli::cli_abort("Transformation for secondary axes must be a function")
}
if (is.derived(self$name) && !is.waive(scale$name)) self$name <- scale$name
if (is.derived(self$breaks)) self$breaks <- scale$breaks
if (is.waive(self$breaks)) self$breaks <- scale$trans$breaks
if (is.derived(self$labels)) self$labels <- scale$labels
if (is.derived(self$guide)) self$guide <- scale$guide
},
transform_range = function(self, range) {
self$trans(range)
},
mono_test = function(self, scale){
range <- scale$range$range
# Check if plot is empty
if (is.null(range)) {
return()
}
along_range <- seq(range[1], range[2], length.out = self$detail)
old_range <- scale$trans$inverse(along_range)
# Create mapping between primary and secondary range
full_range <- self$transform_range(old_range)
# Test for monotonicity
if (length(unique0(sign(diff(full_range)))) != 1)
cli::cli_abort("Transformation for secondary axes must be monotonic")
},
break_info = function(self, range, scale) {
if (self$empty()) return()
# Test for monotonicity on unexpanded range
self$mono_test(scale)
# Get scale's original range before transformation
along_range <- seq(range[1], range[2], length.out = self$detail)
old_range <- scale$trans$inverse(along_range)
# Create mapping between primary and secondary range
full_range <- self$transform_range(old_range)
# Remove duplicates in the expanded area of the range that can arise if
# the transformation is non-monotonic in the expansion. The split ensures
# the middle duplicated are kept
duplicates <- c(
!duplicated(full_range[seq_len(self$detail/2)], fromLast = TRUE),
!duplicated(full_range[-seq_len(self$detail/2)])
)
old_range <- old_range[duplicates]
full_range <- full_range[duplicates]
# Get break info for the secondary axis
new_range <- range(full_range, na.rm = TRUE)
# patch for date and datetime scales just to maintain functionality
# works only for linear secondary transforms that respect the time or date transform
if (scale$trans$name %in% c("date", "time")) {
temp_scale <- self$create_scale(new_range, trans = scale$trans)
range_info <- temp_scale$break_info()
old_val_trans <- rescale(range_info$major, from = c(0, 1), to = range)
old_val_minor_trans <- rescale(range_info$minor, from = c(0, 1), to = range)
} else {
temp_scale <- self$create_scale(new_range)
range_info <- temp_scale$break_info()
# Map the break values back to their correct position on the primary scale
if (!is.null(range_info$major_source)) {
old_val <- approx(full_range, old_range, range_info$major_source)$y
old_val_trans <- scale$trans$transform(old_val)
# rescale values from 0 to 1
range_info$major[] <- round(
rescale(
scale$map(old_val_trans, range(old_val_trans)),
from = range
),
digits = 3
)
} else {
old_val_trans <- NULL
}
if (!is.null(range_info$minor_source)) {
old_val_minor <- approx(full_range, old_range, range_info$minor_source)$y
old_val_minor_trans <- scale$trans$transform(old_val_minor)
range_info$minor[] <- round(
rescale(
scale$map(old_val_minor_trans, range(old_val_minor_trans)),
from = range
),
digits = 3
)
} else {
old_val_minor_trans <- NULL
}
}
# The _source values should be in (primary) scale_transformed space,
# so that the coord doesn't have to know about the secondary scale transformation
# when drawing the axis. The values in user space are useful for testing.
range_info$major_source_user <- range_info$major_source
range_info$minor_source_user <- range_info$minor_source
range_info$major_source[] <- old_val_trans
range_info$minor_source[] <- old_val_minor_trans
names(range_info) <- paste0("sec.", names(range_info))
range_info
},
# Temporary scale for the purpose of calling break_info()
create_scale = function(self, range, trans = identity_trans()) {
scale <- ggproto(NULL, ScaleContinuousPosition,
name = self$name,
breaks = self$breaks,
labels = self$labels,
limits = range,
expand = c(0, 0),
trans = trans
)
scale$train(range)
scale
},
make_title = function(title) {
title
}
)
|