diff --git a/R/aes.R b/R/aes.R index d739289b0e..2a96caa943 100644 --- a/R/aes.R +++ b/R/aes.R @@ -146,24 +146,24 @@ print.uneval <- function(x, ...) { } #' @export -"[.uneval" <- function(x, i, ...) { +`[.uneval` <- function(x, i, ...) { new_aes(NextMethod()) } # If necessary coerce replacements to quosures for compatibility #' @export -"[[<-.uneval" <- function(x, i, value) { +`[[<-.uneval` <- function(x, i, value) { new_aes(NextMethod()) } #' @export -"$<-.uneval" <- function(x, i, value) { +`$<-.uneval` <- function(x, i, value) { # Can't use NextMethod() because of a bug in R 3.1 x <- unclass(x) x[[i]] <- value new_aes(x) } #' @export -"[<-.uneval" <- function(x, i, value) { +`[<-.uneval` <- function(x, i, value) { new_aes(NextMethod()) } @@ -419,7 +419,7 @@ warn_for_aes_extract_usage_expr <- function(x, data, env = emptyenv()) { good_usage <- alternative_aes_extract_usage(x) cli::cli_warn(c( "Use of {.code {format(x)}} is discouraged.", - "i" = "Use {.code {good_usage}} instead." + i = "Use {.code {good_usage}} instead." )) } } else if (is.call(x)) { diff --git a/R/annotation-custom.R b/R/annotation-custom.R index 4261526b89..7ea973987f 100644 --- a/R/annotation-custom.R +++ b/R/annotation-custom.R @@ -85,7 +85,7 @@ GeomCustomAnn <- ggproto("GeomCustomAnn", Geom, vp <- viewport(x = mean(x_rng), y = mean(y_rng), width = diff(x_rng), height = diff(y_rng), - just = c("center","center")) + just = c("center", "center")) editGrob(grob, vp = vp, name = paste(grob$name, annotation_id())) }, diff --git a/R/annotation-logticks.R b/R/annotation-logticks.R index aa03d472cf..6ffab9fa78 100644 --- a/R/annotation-logticks.R +++ b/R/annotation-logticks.R @@ -85,11 +85,12 @@ #' mid = unit(3,"mm"), #' long = unit(4,"mm") #' ) -annotation_logticks <- function(base = 10, sides = "bl", outside = FALSE, scaled = TRUE, +annotation_logticks <- function( + base = 10, sides = "bl", outside = FALSE, scaled = TRUE, short = unit(0.1, "cm"), mid = unit(0.2, "cm"), long = unit(0.3, "cm"), colour = "black", linewidth = 0.5, linetype = 1, alpha = 1, color = NULL, ..., - size = deprecated()) -{ + size = deprecated()) { + if (!is.null(color)) colour <- color @@ -135,8 +136,8 @@ GeomLogticks <- ggproto("GeomLogticks", Geom, draw_panel = function(data, panel_params, coord, base = 10, sides = "bl", outside = FALSE, scaled = TRUE, short = unit(0.1, "cm"), - mid = unit(0.2, "cm"), long = unit(0.3, "cm")) - { + mid = unit(0.2, "cm"), long = unit(0.3, "cm")) { + ticks <- list() flipped <- inherits(coord, "CoordFlip") x_name <- if (flipped) "y" else "x" @@ -165,20 +166,20 @@ GeomLogticks <- ggproto("GeomLogticks", Geom, names(xticks)[names(xticks) == "value"] <- x_name # Rename to 'x' for coordinates$transform xticks <- coord$transform(xticks, panel_params) - xticks <- xticks[xticks$x <= 1 & xticks$x >= 0,] + xticks <- xticks[xticks$x <= 1 & xticks$x >= 0, ] if (outside) - xticks$end = -xticks$end + xticks$end <- -xticks$end # Make the grobs - if (grepl("b", sides) && nrow(xticks) > 0) { + if (grepl("b", sides, fixed = TRUE) && nrow(xticks) > 0) { ticks$x_b <- with(data, segmentsGrob( x0 = unit(xticks$x, "native"), x1 = unit(xticks$x, "native"), y0 = unit(xticks$start, "cm"), y1 = unit(xticks$end, "cm"), gp = gg_par(col = alpha(colour, alpha), lty = linetype, lwd = linewidth) )) } - if (grepl("t", sides) && nrow(xticks) > 0) { + if (grepl("t", sides, fixed = TRUE) && nrow(xticks) > 0) { ticks$x_t <- with(data, segmentsGrob( x0 = unit(xticks$x, "native"), x1 = unit(xticks$x, "native"), y0 = unit(1, "npc") - unit(xticks$start, "cm"), y1 = unit(1, "npc") - unit(xticks$end, "cm"), @@ -203,20 +204,20 @@ GeomLogticks <- ggproto("GeomLogticks", Geom, names(yticks)[names(yticks) == "value"] <- y_name # Rename to 'y' for coordinates$transform yticks <- coord$transform(yticks, panel_params) - yticks <- yticks[yticks$y <= 1 & yticks$y >= 0,] + yticks <- yticks[yticks$y <= 1 & yticks$y >= 0, ] if (outside) - yticks$end = -yticks$end + yticks$end <- -yticks$end # Make the grobs - if (grepl("l", sides) && nrow(yticks) > 0) { + if (grepl("l", sides, fixed = TRUE) && nrow(yticks) > 0) { ticks$y_l <- with(data, segmentsGrob( y0 = unit(yticks$y, "native"), y1 = unit(yticks$y, "native"), x0 = unit(yticks$start, "cm"), x1 = unit(yticks$end, "cm"), gp = gg_par(col = alpha(colour, alpha), lty = linetype, lwd = linewidth) )) } - if (grepl("r", sides) && nrow(yticks) > 0) { + if (grepl("r", sides, fixed = TRUE) && nrow(yticks) > 0) { ticks$y_r <- with(data, segmentsGrob( y0 = unit(yticks$y, "native"), y1 = unit(yticks$y, "native"), x0 = unit(1, "npc") - unit(yticks$start, "cm"), x1 = unit(1, "npc") - unit(yticks$end, "cm"), @@ -242,8 +243,10 @@ GeomLogticks <- ggproto("GeomLogticks", Geom, # - value: the position of the log tick on the data axis, for example 1, 2, ..., 9, 10, 20, ... # - start: on the other axis, start position of the line (usually 0) # - end: on the other axis, end position of the line (for example, .1, .2, or .3) -calc_logticks <- function(base = 10, ticks_per_base = base - 1, - minpow = 0, maxpow = minpow + 1, start = 0, shortend = 0.1, midend = 0.2, longend = 0.3) { +calc_logticks <- function( + base = 10, ticks_per_base = base - 1, + minpow = 0, maxpow = minpow + 1, start = 0, + shortend = 0.1, midend = 0.2, longend = 0.3) { # Number of blocks of tick marks reps <- maxpow - minpow @@ -268,8 +271,8 @@ calc_logticks <- function(base = 10, ticks_per_base = base - 1, # Where to place the longer tick marks that are between each base # For base 10, this will be at each 5 - longtick_after_base <- floor(ticks_per_base/2) - tickend[ cycleIdx == longtick_after_base ] <- midend + longtick_after_base <- floor(ticks_per_base / 2) + tickend[cycleIdx == longtick_after_base] <- midend tickdf <- data_frame0( value = ticks, diff --git a/R/annotation-map.R b/R/annotation-map.R index c6888f2add..33bc327ca2 100644 --- a/R/annotation-map.R +++ b/R/annotation-map.R @@ -97,9 +97,10 @@ GeomAnnotationMap <- ggproto("GeomAnnotationMap", GeomMap, id = grob_id, gp = gg_par( col = data$colour, fill = alpha(data$fill, data$alpha), - lwd = data$linewidth) + lwd = data$linewidth ) + ) }, - required_aes = c() + required_aes = NULL ) diff --git a/R/annotation-raster.R b/R/annotation-raster.R index 8eb8685883..d42efb76b6 100644 --- a/R/annotation-raster.R +++ b/R/annotation-raster.R @@ -39,7 +39,7 @@ NULL #' geom_point() annotation_raster <- function(raster, xmin, xmax, ymin, ymax, interpolate = FALSE) { - if (!inherits(raster, 'nativeRaster')) + if (!inherits(raster, "nativeRaster")) raster <- grDevices::as.raster(raster) layer( @@ -86,8 +86,10 @@ GeomRasterAnn <- ggproto("GeomRasterAnn", Geom, x_rng <- range(data$x, na.rm = TRUE) y_rng <- range(data$y, na.rm = TRUE) - rasterGrob(raster, x_rng[1], y_rng[1], + rasterGrob( + raster, x_rng[1], y_rng[1], diff(x_rng), diff(y_rng), default.units = "native", - just = c("left","bottom"), interpolate = interpolate) + just = c("left", "bottom"), interpolate = interpolate + ) } ) diff --git a/R/annotation.R b/R/annotation.R index f56494c43c..8f8d19425a 100644 --- a/R/annotation.R +++ b/R/annotation.R @@ -47,7 +47,7 @@ annotate <- function(geom, x = NULL, y = NULL, xmin = NULL, xmax = NULL, if (is_string(geom, c("abline", "hline", "vline"))) { cli::cli_warn(c( "{.arg geom} must not be {.val {geom}}.", - "i" = "Please use {.fn {paste0('geom_', geom)}} directly instead." + i = "Please use {.fn {paste0('geom_', geom)}} directly instead." )) } @@ -95,4 +95,3 @@ annotate <- function(geom, x = NULL, y = NULL, xmin = NULL, xmax = NULL, show.legend = FALSE ) } - diff --git a/R/autoplot.R b/R/autoplot.R index cfcdc662b2..2c0c0c9219 100644 --- a/R/autoplot.R +++ b/R/autoplot.R @@ -129,7 +129,6 @@ autoplot <- function(object, ...) { autoplot.default <- function(object, ...) { cli::cli_abort(c( "Objects of class {.cls {class(object)[[1]]}} are not supported by autoplot.", - "i" = "Have you loaded the required package?" + i = "Have you loaded the required package?" )) } - diff --git a/R/axis-secondary.R b/R/axis-secondary.R index 2999bd79b5..62b8963fdf 100644 --- a/R/axis-secondary.R +++ b/R/axis-secondary.R @@ -105,7 +105,7 @@ sec_axis <- function(transform = NULL, } # sec_axis() historically accepted two-sided formula, so be permissive. - if (length(transform) > 2) transform <- transform[c(1,3)] + if (length(transform) > 2) transform <- transform[c(1, 3)] transform <- as_function(transform) ggproto(NULL, AxisSecondary, @@ -130,12 +130,12 @@ is.sec_axis <- function(x) { set_sec_axis <- function(sec.axis, scale) { if (!is.waive(sec.axis)) { - if (scale$is_discrete()) { - if (!identical(.subset2(sec.axis, "trans"), identity)) { - cli::cli_abort("Discrete secondary axes must have the {.fn identity} transformation.") - } + if (scale$is_discrete() && !identical(.subset2(sec.axis, "trans"), identity)) { + cli::cli_abort("Discrete secondary axes must have the {.fn identity} transformation.") + } + if (is.formula(sec.axis)) { + sec.axis <- sec_axis(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}.") } @@ -205,7 +205,7 @@ AxisSecondary <- ggproto("AxisSecondary", NULL, self$trans(range) }, - mono_test = function(self, scale){ + mono_test = function(self, scale) { range <- scale$range$range # Check if plot is empty @@ -231,11 +231,11 @@ AxisSecondary <- ggproto("AxisSecondary", NULL, if (self$empty()) return() # Test for monotonicity on unexpanded range - if (!scale$is_discrete()) { + if (scale$is_discrete()) { + breaks <- scale$map(self$breaks) + } else { self$mono_test(scale) breaks <- self$breaks - } else { - breaks <- scale$map(self$breaks) } # Get scale's original range before transformation @@ -250,8 +250,8 @@ AxisSecondary <- ggproto("AxisSecondary", NULL, # 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)]) + !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] @@ -318,13 +318,14 @@ AxisSecondary <- ggproto("AxisSecondary", NULL, # Temporary scale for the purpose of calling break_info() create_scale = function(self, range, transformation = transform_identity(), breaks = self$breaks) { - scale <- ggproto(NULL, ScaleContinuousPosition, - name = self$name, - breaks = breaks, - labels = self$labels, - limits = range, - expand = c(0, 0), - trans = transformation + scale <- ggproto( + NULL, ScaleContinuousPosition, + name = self$name, + breaks = breaks, + labels = self$labels, + limits = range, + expand = c(0, 0), + trans = transformation ) scale$train(range) scale diff --git a/R/bin.R b/R/bin.R index a7784d02e5..a709617f91 100644 --- a/R/bin.R +++ b/R/bin.R @@ -90,7 +90,7 @@ bin_breaks_width <- function(x_range, width = NULL, center = NULL, if (isTRUE((max_x - origin) / width > 1e6)) { cli::cli_abort(c( "The number of histogram bins must be less than 1,000,000.", - "i" = "Did you make {.arg binwidth} too small?" + i = "Did you make {.arg binwidth} too small?" )) } breaks <- seq(origin, max_x, width) @@ -125,8 +125,9 @@ bin_breaks_bins <- function(x_range, bins = 30, center = NULL, } } - bin_breaks_width(x_range, width, boundary = boundary, center = center, - closed = closed) + bin_breaks_width( + x_range, width, boundary = boundary, center = center, closed = closed + ) } @@ -145,8 +146,7 @@ bin_vector <- function(x, bins, weight = NULL, pad = FALSE) { weight[is.na(weight)] <- 0 } - bin_idx <- cut(x, bins$fuzzy, right = bins$right_closed, - include.lowest = TRUE) + bin_idx <- cut(x, bins$fuzzy, right = bins$right_closed, include.lowest = TRUE) bin_count <- as.numeric(tapply(weight, bin_idx, sum, na.rm = TRUE)) bin_count[is.na(bin_count)] <- 0 @@ -175,7 +175,8 @@ bin_vector <- function(x, bins, weight = NULL, pad = FALSE) { } bin_out <- function(count = integer(0), x = numeric(0), width = numeric(0), - xmin = x - width / 2, xmax = x + width / 2) { + xmin = x - width / 2, xmax = x + width / 2) { + density <- count / width / sum(abs(count)) data_frame0( diff --git a/R/compat-plyr.R b/R/compat-plyr.R index bb3ea73cb9..959f227af3 100644 --- a/R/compat-plyr.R +++ b/R/compat-plyr.R @@ -109,16 +109,14 @@ id <- function(.variables, drop = FALSE) { if (n > 2^31) { char_id <- inject(paste(!!!ids, sep = "\r")) res <- match(char_id, unique0(char_id)) - } - else { + } else { combs <- c(1, cumprod(ndistinct[-p])) mat <- inject(cbind(!!!ids)) res <- c((mat - 1L) %*% combs + 1L) } if (drop) { id_var(res, drop = TRUE) - } - else { + } else { res <- as.integer(res) attr(res, "n") <- n res @@ -170,7 +168,7 @@ join_keys <- function(x, y, by) { # round a number to a given precision round_any <- function(x, accuracy, f = round) { check_numeric(x) - f(x/accuracy) * accuracy + f(x / accuracy) * accuracy } #' Apply function to unique subsets of a data.frame diff --git a/R/coord-.R b/R/coord-.R index 6764cf62a3..b0c4ed7470 100644 --- a/R/coord-.R +++ b/R/coord-.R @@ -120,8 +120,8 @@ Coord <- ggproto("Coord", scale = scale_position[!is_sec] ) opposite <- c( - "top" = "bottom", "bottom" = "top", - "left" = "right", "right" = "left" + top = "bottom", bottom = "top", + left = "right", right = "left" ) guide_position[is_sec] <- Map( function(sec, prim) sec %|W|% unname(opposite[prim]), @@ -275,9 +275,9 @@ parse_coord_expand <- function(expand) { } # Utility function to check coord limits -check_coord_limits <- function( - limits, arg = caller_arg(limits), call = caller_env() -) { +check_coord_limits <- function(limits, arg = caller_arg(limits), + call = caller_env()) { + if (is.null(limits)) { return(invisible(NULL)) } diff --git a/R/coord-cartesian-.R b/R/coord-cartesian-.R index 1b13d9c6c0..b3aee6ea60 100644 --- a/R/coord-cartesian-.R +++ b/R/coord-cartesian-.R @@ -137,7 +137,7 @@ CoordCartesian <- ggproto("CoordCartesian", Coord, left = panel_guides_grob( panel_params$guides, position = "left", theme = theme, labels = panel_params$draw_labels$left - ), + ), right = panel_guides_grob( panel_params$guides, position = "right", theme = theme, labels = panel_params$draw_labels$right diff --git a/R/coord-map.R b/R/coord-map.R index 3ba9260206..a792a8b954 100644 --- a/R/coord-map.R +++ b/R/coord-map.R @@ -130,7 +130,7 @@ #' worldmap + coord_map("ortho", orientation = c(41, -74, 0)) #' } #' } -coord_map <- function(projection="mercator", ..., parameters = NULL, orientation = NULL, xlim = NULL, ylim = NULL, clip = "on") { +coord_map <- function(projection = "mercator", ..., parameters = NULL, orientation = NULL, xlim = NULL, ylim = NULL, clip = "on") { if (is.null(parameters)) { params <- list(...) } else { diff --git a/R/coord-munch.R b/R/coord-munch.R index 9c314ffc59..1b7e8781b1 100644 --- a/R/coord-munch.R +++ b/R/coord-munch.R @@ -65,8 +65,8 @@ munch_data <- function(data, dist = NULL, segment_length = 0.01) { extra[is.na(extra)] <- 1 # Generate extra pieces for x and y values # The final point must be manually inserted at the end - x <- c(unlist(mapply(interp, data$x[-n], data$x[-1], extra, SIMPLIFY = FALSE)), data$x[n]) - y <- c(unlist(mapply(interp, data$y[-n], data$y[-1], extra, SIMPLIFY = FALSE)), data$y[n]) + x <- c(unlist(Map(interp, data$x[-n], data$x[-1], extra)), data$x[n]) + y <- c(unlist(Map(interp, data$y[-n], data$y[-1], extra)), data$y[n]) # Replicate other aesthetics: defined by start point but also # must include final point @@ -126,7 +126,7 @@ dist_polar <- function(r, theta) { # Note that 'slope' actually means the spiral slope, 'a' in the spiral # formula r = a * theta lf <- rename(lf, c(x1 = "t1", x2 = "t2", y1 = "r1", y2 = "r2", - yintercept = "r_int", xintercept = "t_int")) + yintercept = "r_int", xintercept = "t_int")) # Re-normalize the theta values so that intercept for each is 0 # This is necessary for calculating spiral arc length. @@ -212,7 +212,8 @@ spiral_arc_length <- function(a, theta1, theta2) { # http://mathworld.wolfram.com/ArchimedesSpiral.html 0.5 * a * ( (theta1 * sqrt(1 + theta1 * theta1) + asinh(theta1)) - - (theta2 * sqrt(1 + theta2 * theta2) + asinh(theta2))) + (theta2 * sqrt(1 + theta2 * theta2) + asinh(theta2)) + ) } # Closes a polygon type data structure by repeating the first-in-group after diff --git a/R/coord-polar.R b/R/coord-polar.R index f1c8108ddf..628801a413 100644 --- a/R/coord-polar.R +++ b/R/coord-polar.R @@ -149,12 +149,12 @@ CoordPolar <- ggproto("CoordPolar", Coord, ) if (self$theta == "y") { - names(details) <- gsub("x\\.", "r.", names(details)) - names(details) <- gsub("y\\.", "theta.", names(details)) + names(details) <- gsub("x.", "r.", names(details), fixed = TRUE) + names(details) <- gsub("y.", "theta.", names(details), fixed = TRUE) details$r.arrange <- scale_x$axis_order() } else { - names(details) <- gsub("x\\.", "theta.", names(details)) - names(details) <- gsub("y\\.", "r.", names(details)) + names(details) <- gsub("x.", "theta.", names(details), fixed = TRUE) + names(details) <- gsub("y.", "r.", names(details), fixed = TRUE) details$r.arrange <- scale_y$axis_order() } @@ -232,9 +232,9 @@ CoordPolar <- ggproto("CoordPolar", Coord, # This gets the proper theme element for theta and r grid lines: # panel.grid.major.x or .y - majortheta <- paste("panel.grid.major.", self$theta, sep = "") - minortheta <- paste("panel.grid.minor.", self$theta, sep = "") - majorr <- paste("panel.grid.major.", self$r, sep = "") + majortheta <- paste0("panel.grid.major.", self$theta) + minortheta <- paste0("panel.grid.minor.", self$theta) + majorr <- paste0("panel.grid.major.", self$r) ggname("grill", grobTree( element_render(theme, "panel.background"), @@ -275,12 +275,14 @@ CoordPolar <- ggproto("CoordPolar", Coord, # Combine the two ends of the scale if they are close theta <- theta[!is.na(theta)] - ends_apart <- (theta[length(theta)] - theta[1]) %% (2*pi) + ends_apart <- (theta[length(theta)] - theta[1]) %% (2 * pi) if (length(theta) > 0 && ends_apart < 0.05 && !is.null(labels)) { n <- length(labels) if (is.expression(labels)) { - combined <- substitute(paste(a, "/", b), - list(a = labels[[1]], b = labels[[n]])) + combined <- substitute( + paste(a, "/", b), + list(a = labels[[1]], b = labels[[n]]) + ) } else { combined <- paste(labels[1], labels[n], sep = "/") } @@ -321,9 +323,9 @@ CoordPolar <- ggproto("CoordPolar", Coord, rename_data <- function(coord, data) { if (coord$theta == "y") { - rename(data, c("y" = "theta", "x" = "r")) + rename(data, c(y = "theta", x = "r")) } else { - rename(data, c("y" = "r", "x" = "theta")) + rename(data, c(y = "r", x = "theta")) } } diff --git a/R/coord-radial.R b/R/coord-radial.R index 3a5ccf1ee2..f866377ec9 100644 --- a/R/coord-radial.R +++ b/R/coord-radial.R @@ -196,7 +196,14 @@ CoordRadial <- ggproto("CoordRadial", Coord, opposite_r <- isTRUE(scales$r$position %in% c("bottom", "left")) } - if (!isFALSE(self$r_axis_inside)) { + if (isFALSE(self$r_axis_inside)) { + + r_position <- c(params$r_axis, opposite_position(params$r_axis)) + if (opposite_r) { + r_position <- rev(r_position) + } + + } else { r_position <- c("left", "right") # If both opposite direction and opposite position, don't flip @@ -210,12 +217,8 @@ CoordRadial <- ggproto("CoordRadial", Coord, # Set guide text angles guide_params[["r"]]$angle <- guide_params[["r"]]$angle %|W|% arc[1] guide_params[["r.sec"]]$angle <- guide_params[["r.sec"]]$angle %|W|% arc[2] - } else { - r_position <- c(params$r_axis, opposite_position(params$r_axis)) - if (opposite_r) { - r_position <- rev(r_position) - } } + guide_params[["r"]]$position <- r_position[1] guide_params[["r.sec"]]$position <- r_position[2] @@ -245,15 +248,15 @@ CoordRadial <- ggproto("CoordRadial", Coord, gdefs[[t]] <- guides[[t]]$get_layer_key(gdefs[[t]], layers) } - if (!isFALSE(self$r_axis_inside)) { + if (isFALSE(self$r_axis_inside)) { + # When drawing radial axis outside, we need to pretend that arcs starts + # at horizontal or vertical position to have the transform work right. + mod <- list(arc = params$fake_arc) + } else { # For radial axis, we need to pretend that rotation starts at 0 and # the bounding box is for circles, otherwise tick positions will be # spaced too closely. mod <- list(bbox = list(x = c(0, 1), y = c(0, 1)), arc = c(0, 2 * pi)) - } else { - # When drawing radial axis outside, we need to pretend that arcs starts - # at horizontal or vertical position to have the transform work right. - mod <- list(arc = params$fake_arc) } temp <- modify_list(panel_params, mod) @@ -327,22 +330,25 @@ CoordRadial <- ggproto("CoordRadial", Coord, } theta_fine <- theta_rescale(seq(0, 1, length.out = 100), c(0, 1), arc, dir) - r_fine <- r_rescale(panel_params$r.major, panel_params$r.range, - panel_params$inner_radius) + r_fine <- r_rescale( + panel_params$r.major, panel_params$r.range, panel_params$inner_radius + ) # This gets the proper theme element for theta and r grid lines: # panel.grid.major.x or .y - grid_elems <- paste( + grid_elems <- paste0( c("panel.grid.major.", "panel.grid.minor.", "panel.grid.major."), - c(self$theta, self$theta, self$r), sep = "" + c(self$theta, self$theta, self$r) ) grid_elems <- lapply(grid_elems, calc_element, theme = theme) - majortheta <- paste("panel.grid.major.", self$theta, sep = "") - minortheta <- paste("panel.grid.minor.", self$theta, sep = "") - majorr <- paste("panel.grid.major.", self$r, sep = "") + majortheta <- paste0("panel.grid.major.", self$theta) + minortheta <- paste0("panel.grid.minor.", self$theta) + majorr <- paste0("panel.grid.major.", self$r) bg_element <- calc_element("panel.background", theme) - if (!inherits(bg_element, "element_blank")) { + if (inherits(bg_element, "element_blank")) { + background <- zeroGrob() + } else { background <- data_frame0( x = c(Inf, Inf, -Inf, -Inf), y = c(Inf, -Inf, -Inf, Inf) @@ -357,8 +363,6 @@ CoordRadial <- ggproto("CoordRadial", Coord, x = background$x, y = background$y, gp = bg_gp ) - } else { - background <- zeroGrob() } ggname("grill", grobTree( @@ -439,18 +443,18 @@ CoordRadial <- ggproto("CoordRadial", Coord, if (self$theta == "y") { # Need to use single brackets for labels to avoid deleting an element by # assigning NULL - labels$y['primary'] <- list(titles[[1]] %|W|% labels$y$primary) - labels$x['primary'] <- list(titles[[2]] %|W|% labels$x$primary) - labels$x['secondary'] <- list(titles[[3]] %|W|% labels$x$secondary) + labels$y["primary"] <- list(titles[[1]] %|W|% labels$y$primary) + labels$x["primary"] <- list(titles[[2]] %|W|% labels$x$primary) + labels$x["secondary"] <- list(titles[[3]] %|W|% labels$x$secondary) if (any(in_arc(c(0, 1) * pi, panel_params$arc))) { labels <- list(x = labels$y, y = labels$x) } else { labels <- list(x = rev(labels$x), y = rev(labels$y)) } } else { - labels$x['primary'] <- list(titles[[1]] %|W|% labels$x$primary) - labels$y['primary'] <- list(titles[[2]] %|W|% labels$y$primary) - labels$y['secondary'] <- list(titles[[3]] %|W|% labels$y$secondary) + labels$x["primary"] <- list(titles[[1]] %|W|% labels$x$primary) + labels$y["primary"] <- list(titles[[2]] %|W|% labels$y$primary) + labels$y["secondary"] <- list(titles[[3]] %|W|% labels$y$secondary) if (!any(in_arc(c(0, 1) * pi, panel_params$arc))) { labels <- list(x = rev(labels$y), y = rev(labels$x)) diff --git a/R/coord-sf.R b/R/coord-sf.R index c31af6d393..b2b59caa2a 100644 --- a/R/coord-sf.R +++ b/R/coord-sf.R @@ -37,12 +37,14 @@ CoordSf <- ggproto("CoordSf", CoordCartesian, for (layer_data in data) { if (is_sf(layer_data)) { geometry <- sf::st_geometry(layer_data) - } else + } else { next + } crs <- sf::st_crs(geometry) - if (is.na(crs)) + if (is.na(crs)) { next + } return(crs) } @@ -82,8 +84,8 @@ CoordSf <- ggproto("CoordSf", CoordCartesian, target_crs <- panel_params$crs # normalize geometry data, it should already be in the correct crs here - data[[ geom_column(data) ]] <- sf_rescale01( - data[[ geom_column(data) ]], + data[[geom_column(data)]] <- sf_rescale01( + data[[geom_column(data)]], panel_params$x_range, panel_params$y_range ) @@ -200,8 +202,8 @@ CoordSf <- ggproto("CoordSf", CoordCartesian, } else if (any(!is.finite(scales_bbox$x) | !is.finite(scales_bbox$y))) { if (self$lims_method != "geometry_bbox") { cli::cli_warn(c( - "Projection of {.field x} or {.field y} limits failed in {.fn coord_sf}.", - "i" = "Consider setting {.code lims_method = {.val geometry_bbox}} or {.code default_crs = NULL}." + "Projection of {.field x} or {.field y} limits failed in {.fn coord_sf}.", + i = "Consider setting {.code lims_method = {.val geometry_bbox}} or {.code default_crs = NULL}." )) } coord_bbox <- self$params$bbox @@ -416,8 +418,8 @@ sf_rescale01 <- function(x, x_range, y_range) { calc_limits_bbox <- function(method, xlim, ylim, crs, default_crs) { if (!all(is.finite(c(xlim, ylim))) && method != "geometry_bbox") { cli::cli_abort(c( - "Scale limits cannot be mapped onto spatial coordinates in {.fn coord_sf}.", - "i" = "Consider setting {.code lims_method = \"geometry_bbox\"} or {.code default_crs = NULL}." + "Scale limits cannot be mapped onto spatial coordinates in {.fn coord_sf}.", + i = "Consider setting {.code lims_method = \"geometry_bbox\"} or {.code default_crs = NULL}." )) } @@ -451,7 +453,7 @@ calc_limits_bbox <- function(method, xlim, ylim, crs, default_crs) { # rotated in projected space # # Method "cross" is also the default - cross =, + cross = , list( x = c(rep(mean(xlim), 20), seq(xlim[1], xlim[2], length.out = 20)), y = c(seq(ylim[1], ylim[2], length.out = 20), rep(mean(ylim), 20)) @@ -548,7 +550,7 @@ coord_sf <- function(xlim = NULL, ylim = NULL, expand = TRUE, label_axes <- parse_axes_labeling(label_axes) if (is.character(label_graticule)) { - label_graticule <- unlist(strsplit(label_graticule, "")) + label_graticule <- unlist(strsplit(label_graticule, "", fixed = TRUE)) } else { cli::cli_abort("Graticule labeling format not recognized.") } @@ -580,7 +582,7 @@ coord_sf <- function(xlim = NULL, ylim = NULL, expand = TRUE, parse_axes_labeling <- function(x, call = caller_env()) { if (is.character(x)) { - x <- unlist(strsplit(x, "")) + x <- unlist(strsplit(x, "", fixed = TRUE)) x <- list(top = x[1], right = x[2], bottom = x[3], left = x[4]) } else if (!is.list(x)) { cli::cli_abort("Panel labeling format not recognized.", call = call) @@ -663,10 +665,10 @@ view_scales_from_graticule <- function(graticule, scale, aesthetic, # left/right doesn't necessarily mean to label the parallels. position <- switch( arg_match0(aesthetic, c("x", "x.sec", "y", "y.sec")), - "x" = "bottom", - "x.sec" = "top", - "y" = "left", - "y.sec" = "right" + x = "bottom", + x.sec = "top", + y = "left", + y.sec = "right" ) axis <- gsub("\\.sec$", "", aesthetic) if (axis == "x") { diff --git a/R/facet-.R b/R/facet-.R index 8faafc1428..351e89f35b 100644 --- a/R/facet-.R +++ b/R/facet-.R @@ -168,25 +168,33 @@ Facet <- ggproto("Facet", NULL, xlab_height_top <- grobHeight(labels$x[[1]]) panels <- gtable_add_rows(panels, xlab_height_top, pos = 0) - panels <- gtable_add_grob(panels, labels$x[[1]], name = "xlab-t", - l = panel_dim$l, r = panel_dim$r, t = 1, clip = "off") + panels <- gtable_add_grob( + panels, labels$x[[1]], name = "xlab-t", + l = panel_dim$l, r = panel_dim$r, t = 1, clip = "off" + ) xlab_height_bottom <- grobHeight(labels$x[[2]]) panels <- gtable_add_rows(panels, xlab_height_bottom, pos = -1) - panels <- gtable_add_grob(panels, labels$x[[2]], name = "xlab-b", - l = panel_dim$l, r = panel_dim$r, t = -1, clip = "off") + panels <- gtable_add_grob( + panels, labels$x[[2]], name = "xlab-b", + l = panel_dim$l, r = panel_dim$r, t = -1, clip = "off" + ) panel_dim <- find_panel(panels) ylab_width_left <- grobWidth(labels$y[[1]]) panels <- gtable_add_cols(panels, ylab_width_left, pos = 0) - panels <- gtable_add_grob(panels, labels$y[[1]], name = "ylab-l", - l = 1, b = panel_dim$b, t = panel_dim$t, clip = "off") + panels <- gtable_add_grob( + panels, labels$y[[1]], name = "ylab-l", + l = 1, b = panel_dim$b, t = panel_dim$t, clip = "off" + ) ylab_width_right <- grobWidth(labels$y[[2]]) panels <- gtable_add_cols(panels, ylab_width_right, pos = -1) - panels <- gtable_add_grob(panels, labels$y[[2]], name = "ylab-r", - l = -1, b = panel_dim$b, t = panel_dim$t, clip = "off") + panels <- gtable_add_grob( + panels, labels$y[[2]], name = "ylab-r", + l = -1, b = panel_dim$b, t = panel_dim$t, clip = "off" + ) panels }, @@ -365,8 +373,11 @@ unique_combs <- function(df) { if (length(df) == 0) return() unique_values <- lapply(df, ulevels) - rev(expand.grid(rev(unique_values), stringsAsFactors = FALSE, - KEEP.OUT.ATTRS = TRUE)) + rev(expand.grid( + rev(unique_values), + stringsAsFactors = FALSE, + KEEP.OUT.ATTRS = TRUE + )) } df.grid <- function(a, b) { @@ -449,7 +460,7 @@ validate_facets <- function(x) { if (inherits(x, "gg")) { cli::cli_abort(c( "Please use {.fn vars} to supply facet variables.", - "i" = "Did you use {.code %>%} or {.code |>} instead of {.code +}?" + i = "Did you use {.code %>%} or {.code |>} instead of {.code +}?" )) } x @@ -493,7 +504,9 @@ simplify <- function(x) { if (length(x) < 3) { return(list(x)) } - op <- x[[1]]; a <- x[[2]]; b <- x[[3]] + op <- x[[1]] + a <- x[[2]] + b <- x[[3]] if (is_symbol(op, c("+", "*", "~"))) { c(simplify(a), simplify(b)) @@ -606,7 +619,7 @@ check_facet_vars <- function(..., name) { if (length(problems) != 0) { cli::cli_abort(c( "{.val {problems}} {?is/are} not {?an/} allowed name{?/s} for faceting variables.", - "i" = "Change the name of your data columns to not be {.or {.str {reserved_names}}}." + i = "Change the name of your data columns to not be {.or {.str {reserved_names}}}." ), call = call2(name)) } } @@ -664,13 +677,13 @@ find_panel <- function(table) { #' @export panel_cols <- function(table) { panels <- table$layout[grepl("^panel", table$layout$name), , drop = FALSE] - unique0(panels[, c('l', 'r')]) + unique0(panels[, c("l", "r")]) } #' @rdname find_panel #' @export panel_rows <- function(table) { panels <- table$layout[grepl("^panel", table$layout$name), , drop = FALSE] - unique0(panels[, c('t', 'b')]) + unique0(panels[, c("t", "b")]) } #' Take input data and define a mapping between faceting variables and ROW, #' COL and PANEL keys @@ -716,7 +729,9 @@ combine_vars <- function(data, env = emptyenv(), vars = NULL, drop = TRUE) { # Systematically add on missing combinations for (value in values[!has_all]) { - if (empty(value)) next; + if (empty(value)) { + next + } old <- base[setdiff(names(base), names(value))] new <- unique0(value[intersect(names(base), names(value))]) diff --git a/R/facet-grid-.R b/R/facet-grid-.R index 784e394885..e4c68e61f3 100644 --- a/R/facet-grid-.R +++ b/R/facet-grid-.R @@ -181,10 +181,12 @@ facet_grid <- function(rows = NULL, cols = NULL, scales = "fixed", ggproto(NULL, FacetGrid, shrink = shrink, - params = list(rows = facets_list$rows, cols = facets_list$cols, margins = margins, + params = list( + rows = facets_list$rows, cols = facets_list$cols, margins = margins, free = free, space_free = space_free, labeller = labeller, as.table = as.table, switch = switch, drop = drop, - draw_axes = draw_axes, axis_labels = axis_labels) + draw_axes = draw_axes, axis_labels = axis_labels + ) ) } @@ -199,7 +201,7 @@ grid_as_facets_list <- function(rows, cols) { if (inherits(rows, "gg")) { msg <- c( msg, - "i" = "Did you use {.code %>%} or {.code |>} instead of {.code +}?" + i = "Did you use {.code %>%} or {.code |>} instead of {.code +}?" ) } cli::cli_abort(msg) @@ -240,8 +242,8 @@ FacetGrid <- ggproto("FacetGrid", Facet, dups <- intersect(names(rows), names(cols)) if (length(dups) > 0) { cli::cli_abort(c( - "Faceting variables can only appear in {.arg rows} or {.arg cols}, not both.", - "i" = "Duplicated variables: {.val {dups}}" + "Faceting variables can only appear in {.arg rows} or {.arg cols}, not both.", + i = "Duplicated variables: {.val {dups}}" ), call = call2(snake_class(self))) } @@ -271,8 +273,8 @@ FacetGrid <- ggproto("FacetGrid", Facet, panel <- id(base, drop = TRUE) panel <- factor(panel, levels = seq_len(attr(panel, "n"))) - rows <- if (!length(names(rows))) rep(1L, length(panel)) else id(base[names(rows)], drop = TRUE) - cols <- if (!length(names(cols))) rep(1L, length(panel)) else id(base[names(cols)], drop = TRUE) + rows <- if (length(names(rows))) id(base[names(rows)], drop = TRUE) else rep(1L, length(panel)) + cols <- if (length(names(cols))) id(base[names(cols)], drop = TRUE) else rep(1L, length(panel)) panels <- data_frame0(PANEL = panel, ROW = rows, COL = cols, base) panels <- panels[order(panels$PANEL), , drop = FALSE] @@ -325,8 +327,8 @@ FacetGrid <- ggproto("FacetGrid", Facet, data <- unrowname(data[data_rep, , drop = FALSE]) facet_vals <- unrowname(vec_cbind( unrowname(facet_vals[data_rep, , drop = FALSE]), - unrowname(to_add[facet_rep, , drop = FALSE])) - ) + unrowname(to_add[facet_rep, , drop = FALSE]) + )) } # Add PANEL variable @@ -352,19 +354,19 @@ FacetGrid <- ggproto("FacetGrid", Facet, axis_labels <- params$axis_labels %||% list(x = TRUE, y = TRUE) dim <- c(max(layout$ROW), max(layout$COL)) - if (!axis_labels$x) { - cols <- seq_len(nrow(layout)) - x_order <- as.integer(layout$PANEL[order(layout$ROW, layout$COL)]) - } else { + if (axis_labels$x) { cols <- which(layout$ROW == 1) x_order <- layout$COL - } - if (!axis_labels$y) { - rows <- seq_len(nrow(layout)) - y_order <- as.integer(layout$PANEL[order(layout$ROW, layout$COL)]) } else { + cols <- seq_len(nrow(layout)) + x_order <- as.integer(layout$PANEL[order(layout$ROW, layout$COL)]) + } + if (axis_labels$y) { rows <- which(layout$COL == 1) y_order <- layout$ROW + } else { + rows <- seq_len(nrow(layout)) + y_order <- as.integer(layout$PANEL[order(layout$ROW, layout$COL)]) } # Render individual axes diff --git a/R/facet-wrap.R b/R/facet-wrap.R index 4650d12dd8..e873fc60ff 100644 --- a/R/facet-wrap.R +++ b/R/facet-wrap.R @@ -117,7 +117,7 @@ NULL facet_wrap <- function(facets, nrow = NULL, ncol = NULL, scales = "fixed", space = "fixed", shrink = TRUE, labeller = "label_value", as.table = TRUE, switch = deprecated(), drop = TRUE, - dir = "h", strip.position = 'top', axes = "margins", + dir = "h", strip.position = "top", axes = "margins", axis.labels = "all") { scales <- arg_match0(scales %||% "fixed", c("fixed", "free_x", "free_y", "free")) dir <- arg_match0(dir, c("h", "v", "lt", "tl", "lb", "bl", "rt", "tr", "rb", "br")) diff --git a/R/fortify-map.R b/R/fortify-map.R index d0dc76b716..bf29a63f77 100644 --- a/R/fortify-map.R +++ b/R/fortify-map.R @@ -133,6 +133,8 @@ map_data <- function(map, region = ".", exact = FALSE, ...) { borders <- function(database = "world", regions = ".", fill = NA, colour = "grey50", xlim = NULL, ylim = NULL, ...) { df <- map_data(database, regions, xlim = xlim, ylim = ylim) - geom_polygon(aes_(~long, ~lat, group = ~group), data = df, - fill = fill, colour = colour, ..., inherit.aes = FALSE) + geom_polygon( + aes_(~long, ~lat, group = ~group), data = df, + fill = fill, colour = colour, ..., inherit.aes = FALSE + ) } diff --git a/R/fortify-multcomp.R b/R/fortify-multcomp.R index 79714b2a68..f699ba424f 100644 --- a/R/fortify-multcomp.R +++ b/R/fortify-multcomp.R @@ -63,7 +63,8 @@ fortify.confint.glht <- function(model, data, ...) { #' @export fortify.summary.glht <- function(model, data, ...) { coef <- as.data.frame( - model$test[c("coefficients", "sigma", "tstat", "pvalues")]) + model$test[c("coefficients", "sigma", "tstat", "pvalues")] + ) names(coef) <- c("estimate", "se", "t", "p") base::data.frame( diff --git a/R/fortify-spatial.R b/R/fortify-spatial.R index 0e9f37d046..0339569659 100644 --- a/R/fortify-spatial.R +++ b/R/fortify-spatial.R @@ -25,7 +25,7 @@ fortify.SpatialPolygonsDataFrame <- function(model, data, region = NULL, ...) { if (is.null(region)) { # Suppress duplicated warnings withr::with_options(list(lifecycle_verbosity = "quiet"), { - coords <- lapply(model@polygons,fortify) + coords <- lapply(model@polygons, fortify) }) coords <- vec_rbind0(!!!coords) cli::cli_inform("Regions defined for each Polygons") diff --git a/R/fortify.R b/R/fortify.R index da4bcf7892..ab938a3205 100644 --- a/R/fortify.R +++ b/R/fortify.R @@ -46,7 +46,7 @@ fortify.grouped_df <- function(model, data, ...) { # paranoid mode. .prevalidate_data_frame_like_object <- function(data) { orig_dims <- dim(data) - if (!vec_is(orig_dims, integer(), size=2)) + if (!vec_is(orig_dims, integer(), size = 2)) cli::cli_abort(paste0("{.code dim(data)} must return ", "an {.cls integer} of length 2.")) if (anyNA(orig_dims) || any(orig_dims < 0)) # extra-paranoid mode @@ -85,7 +85,7 @@ fortify.default <- function(model, data, ...) { if (is.mapping(model)) { msg <- c( paste0(msg, ", not ", obj_type_friendly(model), "."), - "i" = "Did you accidentally pass {.fn aes} to the {.arg data} argument?" + i = "Did you accidentally pass {.fn aes} to the {.arg data} argument?" ) cli::cli_abort(msg) } diff --git a/R/geom-.R b/R/geom-.R index c5a1ab275d..0d97ed6ac0 100644 --- a/R/geom-.R +++ b/R/geom-.R @@ -96,10 +96,10 @@ Geom <- ggproto("Geom", draw_panel = function(self, data, panel_params, coord, ...) { groups <- split(data, factor(data$group)) - grobs <- lapply(groups, function(group) { - self$draw_group(group, panel_params, coord, ...) - }) - + grobs <- lapply( + groups, self$draw_group, + panel_params = panel_params, coord = coord, ... + ) ggname(snake_class(self), gTree( children = inject(gList(!!!grobs)) )) @@ -171,9 +171,9 @@ Geom <- ggproto("Geom", names(issues) <- rep("x", length(issues)) cli::cli_abort(c( "Aesthetic modifiers returned invalid values", - "x" = "The following mappings are invalid", + x = "The following mappings are invalid", issues, - "i" = "Did you map the modifier in the wrong layer?" + i = "Did you map the modifier in the wrong layer?" )) } @@ -205,7 +205,7 @@ Geom <- ggproto("Geom", # for setup_data() or handle_na(). These can not be imputed automatically, # so the slightly hacky "extra_params" field is used instead. By # default it contains `na.rm` - extra_params = c("na.rm"), + extra_params = "na.rm", parameters = function(self, extra = FALSE) { # Look first in draw_panel. If it contains ... then look in draw groups @@ -226,7 +226,7 @@ Geom <- ggproto("Geom", if (is.null(self$required_aes)) { required_aes <- NULL } else { - required_aes <- unlist(strsplit(self$required_aes, '|', fixed = TRUE)) + required_aes <- unlist(strsplit(self$required_aes, "|", fixed = TRUE)) } c(union(required_aes, names(self$default_aes)), self$optional_aes, "group") }, @@ -276,7 +276,7 @@ check_aesthetics <- function(x, n) { cli::cli_abort(c( "Aesthetics must be either length 1 or the same as the data ({n}).", - "x" = "Fix the following mappings: {.col {names(which(!good))}}." + x = "Fix the following mappings: {.col {names(which(!good))}}." )) } diff --git a/R/geom-bin2d.R b/R/geom-bin2d.R index 2fe756dc96..d3acb447f1 100644 --- a/R/geom-bin2d.R +++ b/R/geom-bin2d.R @@ -27,11 +27,11 @@ #' # Or by specifying the width of the bins #' d + geom_bin_2d(binwidth = c(0.1, 0.1)) geom_bin_2d <- function(mapping = NULL, data = NULL, - stat = "bin2d", position = "identity", - ..., - na.rm = FALSE, - show.legend = NA, - inherit.aes = TRUE) { + stat = "bin2d", position = "identity", + ..., + na.rm = FALSE, + show.legend = NA, + inherit.aes = TRUE) { layer( data = data, @@ -52,4 +52,3 @@ geom_bin_2d <- function(mapping = NULL, data = NULL, #' @rdname geom_bin_2d #' @usage NULL geom_bin2d <- geom_bin_2d - diff --git a/R/geom-boxplot.R b/R/geom-boxplot.R index 1ac23ba80f..afa0d81a03 100644 --- a/R/geom-boxplot.R +++ b/R/geom-boxplot.R @@ -132,9 +132,9 @@ geom_boxplot <- function(mapping = NULL, data = NULL, # varwidth = TRUE is not compatible with preserve = "total" if (is.character(position)) { - if (varwidth == TRUE) position <- position_dodge2(preserve = "single") + if (isTRUE(varwidth)) position <- position_dodge2(preserve = "single") } else { - if (identical(position$preserve, "total") & varwidth == TRUE) { + if (identical(position$preserve, "total") && isTRUE(varwidth)) { cli::cli_warn("Can't preserve total widths when {.code varwidth = TRUE}.") position$preserve <- "single" } @@ -233,7 +233,7 @@ GeomBoxplot <- ggproto("GeomBoxplot", Geom, if (nrow(data) != 1) { cli::cli_abort(c( "Can only draw one boxplot per group.", - "i"= "Did you forget {.code aes(group = ...)}?" + i = "Did you forget {.code aes(group = ...)}?" )) } @@ -279,7 +279,6 @@ GeomBoxplot <- ggproto("GeomBoxplot", Geom, shape = outlier.shape %||% data$shape[1], size = outlier.size %||% data$size[1], stroke = outlier.stroke %||% data$stroke[1], - fill = NA, alpha = outlier.alpha %||% data$alpha[1], .size = length(data$outliers[[1]]) ) diff --git a/R/geom-contour.R b/R/geom-contour.R index a73bc3a135..97d870e3c7 100644 --- a/R/geom-contour.R +++ b/R/geom-contour.R @@ -139,4 +139,3 @@ GeomContour <- ggproto("GeomContour", GeomPath, #' @export #' @include geom-polygon.R GeomContourFilled <- ggproto("GeomContourFilled", GeomPolygon) - diff --git a/R/geom-curve.R b/R/geom-curve.R index e1c38d1cd4..831e31657c 100644 --- a/R/geom-curve.R +++ b/R/geom-curve.R @@ -74,7 +74,8 @@ GeomCurve <- ggproto("GeomCurve", GeomSegment, fill = alpha(arrow.fill, trans$alpha), lwd = trans$linewidth, lty = trans$linetype, - lineend = lineend), + lineend = lineend + ), arrow = arrow ) } diff --git a/R/geom-density2d.R b/R/geom-density2d.R index 832546b563..b6709dccb8 100644 --- a/R/geom-density2d.R +++ b/R/geom-density2d.R @@ -151,4 +151,3 @@ geom_density2d_filled <- geom_density_2d_filled #' @export #' @include geom-polygon.R GeomDensity2dFilled <- ggproto("GeomDensity2dFilled", GeomPolygon) - diff --git a/R/geom-dotplot.R b/R/geom-dotplot.R index 54b7ce1f57..f257ccc136 100644 --- a/R/geom-dotplot.R +++ b/R/geom-dotplot.R @@ -145,11 +145,13 @@ geom_dotplot <- function(mapping = NULL, data = NULL, (identical(position, "stack") || (inherits(position, "PositionStack")))) cli::cli_inform("{.code position = \"stack\"} doesn't work properly with {.fn geom_dotplot}. Use {.code stackgroups = TRUE} instead.") - if (stackgroups && method == "dotdensity" && binpositions == "bygroup") + if (stackgroups && method == "dotdensity" && binpositions == "bygroup") { cli::cli_inform(c( - '{.fn geom_dotplot} called with {.code stackgroups = TRUE} and {.code method = "dotdensity"}.", - i = "Do you want {.code binpositions = "all"} instead?' + "{.fn geom_dotplot} called with {.code stackgroups = TRUE} and {.code method = \"dotdensity\"}.", + i = "Do you want {.code binpositions = \"all\"} instead?" )) + } + stackdir <- arg_match0(stackdir, c("up", "down", "center", "centerwhole"), "stackdir") layer( @@ -261,9 +263,11 @@ GeomDotplot <- ggproto("GeomDotplot", Geom, # works. They're just set to the standard x +- width/2 so that dot clusters # can be dodged like other geoms. # After position code is rewritten, each dot should have its own bounding box. - data <- dapply(data, c("group", "PANEL"), transform, - ymin = min(y) - binwidth[1] / 2, - ymax = max(y) + binwidth[1] / 2) + data <- dapply( + data, c("group", "PANEL"), transform, + ymin = min(y) - binwidth[1] / 2, + ymax = max(y) + binwidth[1] / 2 + ) data$xmin <- data$x + data$width * stackaxismin data$xmax <- data$x + data$width * stackaxismax @@ -296,13 +300,17 @@ GeomDotplot <- ggproto("GeomDotplot", Geom, } ggname("geom_dotplot", - dotstackGrob(stackaxis = stackaxis, x = tdata$x, y = tdata$y, dotdia = dotdianpc, - stackposition = tdata$stackpos, stackdir = stackdir, stackratio = stackratio, - default.units = "npc", - gp = gg_par(col = alpha(tdata$colour, tdata$alpha), - fill = fill_alpha(tdata$fill, tdata$alpha), - lwd = tdata$stroke / .pt, lty = tdata$linetype, - lineend = lineend)) + dotstackGrob( + stackaxis = stackaxis, x = tdata$x, y = tdata$y, dotdia = dotdianpc, + stackposition = tdata$stackpos, stackdir = stackdir, stackratio = stackratio, + default.units = "npc", + gp = gg_par( + col = alpha(tdata$colour, tdata$alpha), + fill = fill_alpha(tdata$fill, tdata$alpha), + lwd = tdata$stroke / .pt, lty = tdata$linetype, + lineend = lineend + ) + ) ) }, diff --git a/R/geom-errorbarh.R b/R/geom-errorbarh.R index c38b9b7cd6..6e46e16dd8 100644 --- a/R/geom-errorbarh.R +++ b/R/geom-errorbarh.R @@ -82,7 +82,7 @@ GeomErrorbarh <- ggproto("GeomErrorbarh", Geom, alpha = rep(data$alpha, each = 8), linewidth = rep(data$linewidth, each = 8), linetype = rep(data$linetype, each = 8), - group = rep(1:(nrow(data)), each = 8), + group = rep(vec_seq_along(data), each = 8), .size = nrow(data) * 8 ), panel_params, coord, lineend = lineend) }, diff --git a/R/geom-function.R b/R/geom-function.R index c566731996..6c949f97ec 100644 --- a/R/geom-function.R +++ b/R/geom-function.R @@ -97,7 +97,7 @@ GeomFunction <- ggproto("GeomFunction", GeomPath, if (length(groups) > 1) { cli::cli_warn(c( "Multiple drawing groups in {.fn {snake_class(self)}}", - "i" = "Did you use the correct {.field group}, {.field colour}, or {.field fill} aesthetics?" + i = "Did you use the correct {.field group}, {.field colour}, or {.field fill} aesthetics?" )) } diff --git a/R/geom-jitter.R b/R/geom-jitter.R index 52f017dccd..6b283986f7 100644 --- a/R/geom-jitter.R +++ b/R/geom-jitter.R @@ -45,7 +45,7 @@ geom_jitter <- function(mapping = NULL, data = NULL, if (!missing(position)) { cli::cli_abort(c( "Both {.arg position} and {.arg width}/{.arg height} were supplied.", - "i" = "Choose a single approach to alter the position." + i = "Choose a single approach to alter the position." )) } diff --git a/R/geom-label.R b/R/geom-label.R index 6f21478da0..20014c8350 100644 --- a/R/geom-label.R +++ b/R/geom-label.R @@ -20,7 +20,7 @@ geom_label <- function(mapping = NULL, data = NULL, if (!missing(position)) { cli::cli_abort(c( "Both {.arg position} and {.arg nudge_x}/{.arg nudge_y} are supplied.", - "i" = "Choose one approach to alter the position." + i = "Choose one approach to alter the position." )) } @@ -129,7 +129,7 @@ labelGrob <- function(label, x = unit(0.5, "npc"), y = unit(0.5, "npc"), if (!is.unit(y)) y <- unit(y, default.units) - if (!is.null(angle) & is.null(vp)) { + if (!is.null(angle) && is.null(vp)) { vp <- viewport( angle = angle, x = x, y = y, width = unit(0, "cm"), height = unit(0, "cm"), diff --git a/R/geom-map.R b/R/geom-map.R index 7f4b860378..4dd4c7ca45 100644 --- a/R/geom-map.R +++ b/R/geom-map.R @@ -155,5 +155,5 @@ GeomMap <- ggproto("GeomMap", GeomPolygon, ) }, - required_aes = c("map_id") + required_aes = "map_id" ) diff --git a/R/geom-path.R b/R/geom-path.R index 72c4f7154e..09d2bfe43b 100644 --- a/R/geom-path.R +++ b/R/geom-path.R @@ -205,33 +205,32 @@ GeomPath <- ggproto("GeomPath", Geom, munched$fill <- arrow.fill %||% munched$colour - if (!constant) { - - arrow <- repair_segment_arrow(arrow, munched$group) - - segmentsGrob( - munched$x[!end], munched$y[!end], munched$x[!start], munched$y[!start], + if (constant) { + id <- match(munched$group, unique0(munched$group)) + polylineGrob( + munched$x, munched$y, id = id, default.units = "native", arrow = arrow, gp = gg_par( - col = alpha(munched$colour, munched$alpha)[!end], - fill = alpha(munched$fill, munched$alpha)[!end], - lwd = munched$linewidth[!end], - lty = munched$linetype[!end], + col = alpha(munched$colour, munched$alpha)[start], + fill = alpha(munched$fill, munched$alpha)[start], + lwd = munched$linewidth[start], + lty = munched$linetype[start], lineend = lineend, linejoin = linejoin, linemitre = linemitre ) ) } else { - id <- match(munched$group, unique0(munched$group)) - polylineGrob( - munched$x, munched$y, id = id, + arrow <- repair_segment_arrow(arrow, munched$group) + + segmentsGrob( + munched$x[!end], munched$y[!end], munched$x[!start], munched$y[!start], default.units = "native", arrow = arrow, gp = gg_par( - col = alpha(munched$colour, munched$alpha)[start], - fill = alpha(munched$fill, munched$alpha)[start], - lwd = munched$linewidth[start], - lty = munched$linetype[start], + col = alpha(munched$colour, munched$alpha)[!end], + fill = alpha(munched$fill, munched$alpha)[!end], + lwd = munched$linewidth[!end], + lty = munched$linetype[!end], lineend = lineend, linejoin = linejoin, linemitre = linemitre @@ -374,22 +373,22 @@ stairstep <- function(data, direction = "hv") { } if (direction == "vh") { - xs <- rep(1:n, each = 2)[-2*n] + xs <- rep(1:n, each = 2)[-2 * n] ys <- c(1, rep(2:n, each = 2)) } else if (direction == "hv") { - ys <- rep(1:n, each = 2)[-2*n] + ys <- rep(1:n, each = 2)[-2 * n] xs <- c(1, rep(2:n, each = 2)) } else if (direction == "mid") { - xs <- rep(1:(n-1), each = 2) + xs <- rep(1:(n - 1), each = 2) ys <- rep(1:n, each = 2) } if (direction == "mid") { gaps <- data$x[-1] - data$x[-n] - mid_x <- data$x[-n] + gaps/2 # map the mid-point between adjacent x-values + mid_x <- data$x[-n] + gaps / 2 # map the mid-point between adjacent x-values x <- c(data$x[1], mid_x[xs], data$x[n]) y <- c(data$y[ys]) - data_attr <- data[c(1,xs,n), setdiff(names(data), c("x", "y"))] + data_attr <- data[c(1, xs, n), setdiff(names(data), c("x", "y"))] } else { x <- data$x[xs] y <- data$y[ys] diff --git a/R/geom-raster.R b/R/geom-raster.R index 94b1775373..c3d79b6fac 100644 --- a/R/geom-raster.R +++ b/R/geom-raster.R @@ -16,8 +16,8 @@ geom_raster <- function(mapping = NULL, data = NULL, interpolate = FALSE, na.rm = FALSE, show.legend = NA, - inherit.aes = TRUE) -{ + inherit.aes = TRUE) { + check_number_decimal(hjust) check_number_decimal(vjust) @@ -59,7 +59,7 @@ GeomRaster <- ggproto("GeomRaster", Geom, } else if (any(abs(diff(x_diff)) > precision)) { cli::cli_warn(c( "Raster pixels are placed at uneven horizontal intervals and will be shifted", - "i" = "Consider using {.fn geom_tile} instead." + i = "Consider using {.fn geom_tile} instead." )) w <- min(x_diff) } else { @@ -71,7 +71,7 @@ GeomRaster <- ggproto("GeomRaster", Geom, } else if (any(abs(diff(y_diff)) > precision)) { cli::cli_warn(c( "Raster pixels are placed at uneven horizontal intervals and will be shifted", - "i" = "Consider using {.fn geom_tile} instead." + i = "Consider using {.fn geom_tile} instead." )) h <- min(y_diff) } else { diff --git a/R/geom-rect.R b/R/geom-rect.R index 8473474525..38de6345f3 100644 --- a/R/geom-rect.R +++ b/R/geom-rect.R @@ -70,21 +70,7 @@ GeomRect <- ggproto("GeomRect", Geom, draw_panel = function(self, data, panel_params, coord, lineend = "butt", linejoin = "mitre") { data <- check_linewidth(data, snake_class(self)) - if (!coord$is_linear()) { - aesthetics <- setdiff( - names(data), c("x", "y", "xmin", "xmax", "ymin", "ymax") - ) - index <- rep(seq_len(nrow(data)), each = 4) - - new <- data[index, aesthetics, drop = FALSE] - new$x <- vec_interleave(data$xmin, data$xmax, data$xmax, data$xmin) - new$y <- vec_interleave(data$ymax, data$ymax, data$ymin, data$ymin) - new$group <- index - - ggname("geom_rect", GeomPolygon$draw_panel( - new, panel_params, coord, lineend = lineend, linejoin = linejoin - )) - } else { + if (coord$is_linear()) { coords <- coord$transform(data, panel_params) ggname("geom_rect", rectGrob( coords$xmin, coords$ymax, @@ -101,6 +87,20 @@ GeomRect <- ggproto("GeomRect", Geom, lineend = lineend ) )) + } else { + aesthetics <- setdiff( + names(data), c("x", "y", "xmin", "xmax", "ymin", "ymax") + ) + index <- rep(seq_len(nrow(data)), each = 4) + + new <- data[index, aesthetics, drop = FALSE] + new$x <- vec_interleave(data$xmin, data$xmax, data$xmax, data$xmin) + new$y <- vec_interleave(data$ymax, data$ymax, data$ymin, data$ymin) + new$group <- index + + ggname("geom_rect", GeomPolygon$draw_panel( + new, panel_params, coord, lineend = lineend, linejoin = linejoin + )) } }, diff --git a/R/geom-ribbon.R b/R/geom-ribbon.R index a8f6b1be42..6f5f02a689 100644 --- a/R/geom-ribbon.R +++ b/R/geom-ribbon.R @@ -101,7 +101,8 @@ GeomRibbon <- ggproto("GeomRibbon", Geom, fill = from_theme(col_mix(ink, paper, 0.2)), linewidth = from_theme(borderwidth), linetype = from_theme(bordertype), - alpha = NA), + alpha = NA + ), required_aes = c("x|y", "ymin|xmin", "ymax|xmax"), diff --git a/R/geom-rug.R b/R/geom-rug.R index d675474f43..9f144e55ce 100644 --- a/R/geom-rug.R +++ b/R/geom-rug.R @@ -97,15 +97,15 @@ GeomRug <- ggproto("GeomRug", Geom, # For coord_flip, coord$transform does not flip the sides where to # draw the rugs. We have to flip them. - if (inherits(coord, 'CoordFlip')) { - sides <- chartr('tblr', 'rlbt', sides) + if (inherits(coord, "CoordFlip")) { + sides <- chartr("tblr", "rlbt", sides) } # move the rug to outside the main plot space - rug_length <- if (!outside) { - list(min = length, max = unit(1, "npc") - length) - } else { + rug_length <- if (outside) { list(min = -1 * length, max = unit(1, "npc") + length) + } else { + list(min = length, max = unit(1, "npc") - length) } gp <- gg_par( @@ -115,7 +115,7 @@ GeomRug <- ggproto("GeomRug", Geom, lineend = lineend ) if (!is.null(data$x)) { - if (grepl("b", sides)) { + if (grepl("b", sides, fixed = TRUE)) { rugs$x_b <- segmentsGrob( x0 = unit(data$x, "native"), x1 = unit(data$x, "native"), y0 = unit(0, "npc"), y1 = rug_length$min, @@ -123,7 +123,7 @@ GeomRug <- ggproto("GeomRug", Geom, ) } - if (grepl("t", sides)) { + if (grepl("t", sides, fixed = TRUE)) { rugs$x_t <- segmentsGrob( x0 = unit(data$x, "native"), x1 = unit(data$x, "native"), y0 = unit(1, "npc"), y1 = rug_length$max, @@ -133,7 +133,7 @@ GeomRug <- ggproto("GeomRug", Geom, } if (!is.null(data$y)) { - if (grepl("l", sides)) { + if (grepl("l", sides, fixed = TRUE)) { rugs$y_l <- segmentsGrob( y0 = unit(data$y, "native"), y1 = unit(data$y, "native"), x0 = unit(0, "npc"), x1 = rug_length$min, @@ -141,7 +141,7 @@ GeomRug <- ggproto("GeomRug", Geom, ) } - if (grepl("r", sides)) { + if (grepl("r", sides, fixed = TRUE)) { rugs$y_r <- segmentsGrob( y0 = unit(data$y, "native"), y1 = unit(data$y, "native"), x0 = unit(1, "npc"), x1 = rug_length$max, @@ -193,9 +193,9 @@ GeomRug <- ggproto("GeomRug", Geom, ) data <- switch( paste0(sides_aes, collapse = ""), - "x" = , - "y" = df_list[[1]], - "xy" = vctrs::vec_set_union(df_list[[1]], df_list[[2]]) + x = , + y = df_list[[1]], + xy = vctrs::vec_set_union(df_list[[1]], df_list[[2]]) ) } else { data <- remove_missing( diff --git a/R/geom-segment.R b/R/geom-segment.R index 00d9eff87a..f2b5cbbb72 100644 --- a/R/geom-segment.R +++ b/R/geom-segment.R @@ -143,13 +143,14 @@ GeomSegment <- ggproto("GeomSegment", Geom, data$group <- seq_len(nrow(data)) starts <- subset(data, select = c(-xend, -yend)) - ends <- rename(subset(data, select = c(-x, -y)), c("xend" = "x", "yend" = "y")) + ends <- rename(subset(data, select = c(-x, -y)), c(xend = "x", yend = "y")) pieces <- vec_rbind0(starts, ends) - pieces <- pieces[order(pieces$group),] + pieces <- pieces[order(pieces$group), ] - GeomPath$draw_panel(pieces, panel_params, coord, arrow = arrow, - lineend = lineend) + GeomPath$draw_panel( + pieces, panel_params, coord, arrow = arrow, lineend = lineend + ) }, draw_key = draw_key_path, diff --git a/R/geom-sf.R b/R/geom-sf.R index 2e9aee78b8..a0a2a4b264 100644 --- a/R/geom-sf.R +++ b/R/geom-sf.R @@ -330,7 +330,7 @@ geom_sf_label <- function(mapping = aes(), data = NULL, if (!missing(position)) { cli::cli_abort(c( "Both {.arg position} and {.arg nudge_x}/{.arg nudge_y} are supplied.", - "i" = "Only use one approach to alter the position." + i = "Only use one approach to alter the position." )) } @@ -377,7 +377,7 @@ geom_sf_text <- function(mapping = aes(), data = NULL, if (!missing(position)) { cli::cli_abort(c( "Both {.arg position} and {.arg nudge_x}/{.arg nudge_y} are supplied.", - "i" = "Only use one approach to alter the position." + i = "Only use one approach to alter the position." )) } diff --git a/R/geom-text.R b/R/geom-text.R index ed378734ba..18336a73c9 100644 --- a/R/geom-text.R +++ b/R/geom-text.R @@ -175,13 +175,13 @@ geom_text <- function(mapping = NULL, data = NULL, size.unit = "mm", na.rm = FALSE, show.legend = NA, - inherit.aes = TRUE) -{ + inherit.aes = TRUE) { + if (!missing(nudge_x) || !missing(nudge_y)) { if (!missing(position)) { cli::cli_abort(c( "Both {.arg position} and {.arg nudge_x}/{.arg nudge_y} are supplied.", - "i" = "Only use one approach to alter the position." + i = "Only use one approach to alter the position." )) } @@ -286,8 +286,9 @@ compute_just <- function(just, a = 0.5, b = a, angle = 0) { } - unname(c(left = 0, center = 0.5, right = 1, - bottom = 0, middle = 0.5, top = 1)[just]) + unname( + c(left = 0, center = 0.5, right = 1, bottom = 0, middle = 0.5, top = 1)[just] + ) } just_dir <- function(x, tol = 0.001) { diff --git a/R/geom-tile.R b/R/geom-tile.R index e7bb6bc9e3..6832c09e8c 100644 --- a/R/geom-tile.R +++ b/R/geom-tile.R @@ -107,7 +107,7 @@ geom_tile <- function(mapping = NULL, data = NULL, #' @export #' @include geom-rect.R GeomTile <- ggproto("GeomTile", GeomRect, - extra_params = c("na.rm"), + extra_params = "na.rm", setup_data = function(data, params) { diff --git a/R/geom-violin.R b/R/geom-violin.R index 9976e5b8a4..02585b2d73 100644 --- a/R/geom-violin.R +++ b/R/geom-violin.R @@ -160,7 +160,7 @@ GeomViolin <- ggproto("GeomViolin", Geom, # Close the polygon: set first and last point the same # Needed for coord_polar and such - newdata <- vec_rbind0(newdata, newdata[1,]) + newdata <- vec_rbind0(newdata, newdata[1, ]) newdata <- flip_data(newdata, flipped_aes) # Draw quantiles if requested, so long as there is non-zero y range @@ -188,8 +188,8 @@ GeomViolin <- ggproto("GeomViolin", Geom, ggname("geom_violin", grobTree( GeomPolygon$draw_panel(newdata, ...), - quantile_grob) - ) + quantile_grob + )) } else { ggname("geom_violin", GeomPolygon$draw_panel(newdata, ...)) } @@ -228,4 +228,3 @@ create_quantile_segment_frame <- function(data, draw_quantiles) { group = rep(ys, each = 2) ) } - diff --git a/R/ggplot-global.R b/R/ggplot-global.R index 495dc65ae0..27a6e1f359 100644 --- a/R/ggplot-global.R +++ b/R/ggplot-global.R @@ -29,26 +29,30 @@ ggplot_global$all_aesthetics <- .all_aesthetics # (In the future, .base_to_ggplot should be removed in favor # of direct assignment to ggplot_global$base_to_ggplot, see below.) .base_to_ggplot <- c( - "col" = "colour", - "color" = "colour", - "pch" = "shape", - "cex" = "size", - "lty" = "linetype", - "lwd" = "linewidth", - "srt" = "angle", - "adj" = "hjust", - "bg" = "fill", - "fg" = "colour", - "min" = "ymin", - "max" = "ymax" + col = "colour", + color = "colour", + pch = "shape", + cex = "size", + lty = "linetype", + lwd = "linewidth", + srt = "angle", + adj = "hjust", + bg = "fill", + fg = "colour", + min = "ymin", + max = "ymax" ) ggplot_global$base_to_ggplot <- .base_to_ggplot # These two vectors must match in length and position of symmetrical aesthetics # xintercept2 is a filler to match to the intercept aesthetic in geom_abline -ggplot_global$x_aes <- c("x", "xmin", "xmax", "xend", "xintercept", - "xmin_final", "xmax_final", "xlower", "xmiddle", "xupper", "x0") +ggplot_global$x_aes <- c( + "x", "xmin", "xmax", "xend", "xintercept", + "xmin_final", "xmax_final", "xlower", "xmiddle", "xupper", "x0" +) -ggplot_global$y_aes <- c("y", "ymin", "ymax", "yend", "yintercept", - "ymin_final", "ymax_final", "lower", "middle", "upper", "y0") +ggplot_global$y_aes <- c( + "y", "ymin", "ymax", "yend", "yintercept", + "ymin_final", "ymax_final", "lower", "middle", "upper", "y0" +) diff --git a/R/ggproto.R b/R/ggproto.R index 6165a9707d..5e6c272ca7 100644 --- a/R/ggproto.R +++ b/R/ggproto.R @@ -127,7 +127,7 @@ fetch_ggproto <- function(x, name) { } else { cli::cli_abort(c( "{class(x)[[1]]} was built with an incompatible version of ggproto.", - "i" = "Please reinstall the package that provides this extension." + i = "Please reinstall the package that provides this extension." )) } } @@ -207,10 +207,8 @@ make_proto_method <- function(self, f, name) { as.list.ggproto <- function(x, inherit = TRUE, ...) { res <- list() - if (inherit) { - if (is.function(x$super)) { - res <- as.list(x$super()) - } + if (inherit && is.function(x$super)) { + res <- as.list(x$super()) } current <- as.list.environment(x, ...) @@ -259,7 +257,7 @@ format.ggproto <- function(x, ..., flat = TRUE) { classes <- setdiff(class(obj), "ggproto") if (length(classes) == 0) return("") - paste0(": Class ", paste(classes, collapse = ', ')) + paste0(": Class ", paste(classes, collapse = ", ")) } # Get a flat list if requested @@ -310,14 +308,14 @@ object_summaries <- function(x, exclude = NULL, flat = TRUE) { else paste(class(obj), collapse = ", ") }, FUN.VALUE = character(1)) - paste0(obj_names, ": ", values, sep = "", collapse = "\n") + paste0(obj_names, ": ", values, collapse = "\n") } # Given a string, indent every line by some number of spaces. # The exception is to not add spaces after a trailing \n. indent <- function(str, indent = 0) { gsub("(\\n|^)(?!$)", - paste0("\\1", paste(rep(" ", indent), collapse = "")), + paste0("\\1", strrep(" ", indent)), str, perl = TRUE ) @@ -391,4 +389,3 @@ ggproto_debug <- function(method, debug = c("once", "always", "never"), ...) { never = undebug(method, ...) ) } - diff --git a/R/grob-absolute.R b/R/grob-absolute.R index cce138712a..ae9c86a942 100644 --- a/R/grob-absolute.R +++ b/R/grob-absolute.R @@ -6,7 +6,7 @@ #' #' @keywords internal absoluteGrob <- function(grob, width = NULL, height = NULL, - xmin = NULL, ymin = NULL, vp = NULL) { + xmin = NULL, ymin = NULL, vp = NULL) { gTree( children = grob, diff --git a/R/grob-dotstack.R b/R/grob-dotstack.R index d3463c18bd..425c710dd4 100644 --- a/R/grob-dotstack.R +++ b/R/grob-dotstack.R @@ -6,20 +6,20 @@ dotstackGrob <- function( stackposition = 0, # Position of each dot in the stack, relative to origin stackdir = "up", # Stacking direction ("up", "down", "center", or "centerwhole") stackratio = 1, # Stacking height of dots (.75 means 25% dot overlap) - default.units = "npc", name = NULL, gp = gpar(), vp = NULL) -{ - if (!is.unit(x)) - x <- unit(x, default.units) - if (!is.unit(y)) - y <- unit(y, default.units) - if (!is.unit(dotdia)) - dotdia <- unit(dotdia, default.units) - if (!unitType(dotdia) == "npc") - cli::cli_warn("Unit type of dotdia should be {.val npc}") + default.units = "npc", name = NULL, gp = gpar(), vp = NULL) { - grob(x = x, y = y, stackaxis = stackaxis, dotdia = dotdia, - stackposition = stackposition, stackdir = stackdir, stackratio = stackratio, - name = name, gp = gp, vp = vp, cl = "dotstackGrob") + if (!is.unit(x)) + x <- unit(x, default.units) + if (!is.unit(y)) + y <- unit(y, default.units) + if (!is.unit(dotdia)) + dotdia <- unit(dotdia, default.units) + if (!unitType(dotdia) == "npc") + cli::cli_warn("Unit type of dotdia should be {.val npc}") + + grob(x = x, y = y, stackaxis = stackaxis, dotdia = dotdia, + stackposition = stackposition, stackdir = stackdir, stackratio = stackratio, + name = name, gp = gp, vp = vp, cl = "dotstackGrob") } #' @export diff --git a/R/guide-.R b/R/guide-.R index dd63949cd2..53c05664e6 100644 --- a/R/guide-.R +++ b/R/guide-.R @@ -263,7 +263,7 @@ Guide <- ggproto( transform = function(self, params, coord, ...) { cli::cli_abort(c( "{.fn {snake_class(self)}} does not implement a {.fn transform} method.", - "i" = "Did you mean to use {.fn guide_axis}?" + i = "Did you mean to use {.fn guide_axis}?" )) }, @@ -388,11 +388,7 @@ Guide <- ggproto( return(zeroGrob()) } - if (!is.list(key)) { - breaks <- key - } else { - breaks <- key[[params$aes]] - } + breaks <- if (is.list(key)) key[[params$aes]] else key n_breaks <- length(breaks) # Early exit if there are no breaks @@ -504,14 +500,14 @@ flip_element_grob <- function(..., flip = FALSE) { # The flippable arguments for `flip_element_grob()`. flip_names <- c( - "x" = "y", - "y" = "x", - "width" = "height", - "height" = "width", - "hjust" = "vjust", - "vjust" = "hjust", - "margin_x" = "margin_y", - "margin_y" = "margin_x" + x = "y", + y = "x", + width = "height", + height = "width", + hjust = "vjust", + vjust = "hjust", + margin_x = "margin_y", + margin_y = "margin_x" ) # Shortcut for position argument matching diff --git a/R/guide-axis-logticks.R b/R/guide-axis-logticks.R index 37273cba06..06b7fb7e6a 100644 --- a/R/guide-axis-logticks.R +++ b/R/guide-axis-logticks.R @@ -188,13 +188,13 @@ GuideAxisLogticks <- ggproto( limits <- transformation$inverse(scale$get_limits()) has_negatives <- any(limits <= 0) - if (!has_negatives) { - start <- floor(log10(min(limits))) - 1L - end <- ceiling(log10(max(limits))) + 1L - } else { + if (has_negatives) { params$negative_small <- params$negative_small %||% 0.1 start <- floor(log10(abs(params$negative_small))) end <- ceiling(log10(max(abs(limits)))) + 1L + } else { + start <- floor(log10(min(limits))) - 1L + end <- ceiling(log10(max(limits))) + 1L } # Calculate tick marks diff --git a/R/guide-axis-stack.R b/R/guide-axis-stack.R index 74fe2b2b3a..22f3dc786c 100644 --- a/R/guide-axis-stack.R +++ b/R/guide-axis-stack.R @@ -252,4 +252,3 @@ GuideAxisStack <- ggproto( ) } ) - diff --git a/R/guide-axis-theta.R b/R/guide-axis-theta.R index 2e4f7a6cef..505cb8b212 100644 --- a/R/guide-axis-theta.R +++ b/R/guide-axis-theta.R @@ -91,18 +91,8 @@ GuideAxisTheta <- ggproto( return(params) } - if (!("theta" %in% names(key))) { - # We likely have a linear coord, so we match the text angles to - # standard axes to be visually similar. - key$theta <- switch( - params$position, - top = 0, - bottom = 1 * pi, - left = 1.5 * pi, - right = 0.5 * pi - ) - } else { - if (params$position == 'theta.sec') { + if ("theta" %in% names(key)) { + if (params$position == "theta.sec") { key$theta <- key$theta + pi } @@ -121,6 +111,16 @@ GuideAxisTheta <- ggproto( key$.label[[n]] <- combined key <- vec_slice(key, -1) } + } else { + # We likely have a linear coord, so we match the text angles to + # standard axes to be visually similar. + key$theta <- switch( + params$position, + top = 0, + bottom = 1 * pi, + left = 1.5 * pi, + right = 0.5 * pi + ) } params$key <- key diff --git a/R/guide-axis.R b/R/guide-axis.R index bc2a2e1596..98d38f9391 100644 --- a/R/guide-axis.R +++ b/R/guide-axis.R @@ -224,7 +224,7 @@ GuideAxis <- ggproto( if (length(unique(key[[position_aes]][breaks_are_unique])) == 1) { cli::cli_warn(c( "Position guide is perpendicular to the intended axis.", - "i" = "Did you mean to specify a different guide {.arg position}?" + i = "Did you mean to specify a different guide {.arg position}?" )) } @@ -235,7 +235,7 @@ GuideAxis <- ggproto( if (!inherits(new_guide, "GuideNone")) { cli::cli_warn(c( "{.fn {snake_class(self)}}: Discarding guide on merge.", - "i" = "Do you have more than one guide with the same {.arg position}?" + i = "Do you have more than one guide with the same {.arg position}?" )) } return(list(guide = self, params = params)) @@ -246,9 +246,8 @@ GuideAxis <- ggproto( suffix <- params$theme_suffix %||% paste(params$aes, params$position, sep = ".") elements[is_char] <- vapply( - elements[is_char], - function(x) paste(x, suffix, sep = "."), - character(1) + elements[is_char], paste, suffix, sep = ".", + FUN.VALUE = character(1) ) Guide$setup_elements(params, elements, theme) }, diff --git a/R/guide-bins.R b/R/guide-bins.R index 0124ea6052..d7cfead4e5 100644 --- a/R/guide-bins.R +++ b/R/guide-bins.R @@ -99,7 +99,7 @@ guide_bins <- function( show.limits = show.limits, # parameter - available_aes = c("any"), + available_aes = "any", ..., name = "bins", super = GuideBins @@ -122,7 +122,6 @@ GuideBins <- ggproto( default_ticks = element_line(inherit.blank = TRUE), angle = NULL, - direction = NULL, override.aes = list(), reverse = FALSE, order = 0, @@ -166,15 +165,15 @@ GuideBins <- ggproto( } else { limit_lab <- scale$get_labels(limits) } - if (!breaks[1] %in% limits) { - labels <- c(limit_lab[1], labels) - } else { + if (breaks[1] %in% limits) { key$.show[1] <- TRUE - } - if (!breaks[length(breaks)] %in% limits) { - labels <- c(labels, limit_lab[2]) } else { + labels <- c(limit_lab[1], labels) + } + if (breaks[length(breaks)] %in% limits) { key$.show[nrow(key)] <- TRUE + } else { + labels <- c(labels, limit_lab[2]) } key$.label <- labels @@ -193,7 +192,7 @@ GuideBins <- ggproto( cli::cli_warn(c(paste0( "{.arg show.limits} is ignored when {.arg labels} are given as a ", "character vector." - ), "i" = paste0( + ), i = paste0( "Either add the limits to {.arg breaks} or provide a function for ", "{.arg labels}." ))) @@ -226,8 +225,8 @@ GuideBins <- ggproto( setup_elements = function(params, elements, theme) { valid_position <- switch( params$direction, - "horizontal" = c("bottom", "top"), - "vertical" = c("right", "left") + horizontal = c("bottom", "top"), + vertical = c("right", "left") ) # Set defaults @@ -314,10 +313,10 @@ GuideBins <- ggproto( axis <- switch( elements$text_position, - "top" = list(x = c(0, 1), y = c(1, 1)), - "bottom" = list(x = c(0, 1), y = c(0, 0)), - "left" = list(x = c(0, 0), y = c(0, 1)), - "right" = list(x = c(1, 1), y = c(0, 1)) + top = list(x = c(0, 1), y = c(1, 1)), + bottom = list(x = c(0, 1), y = c(0, 0)), + left = list(x = c(0, 0), y = c(0, 1)), + right = list(x = c(1, 1), y = c(0, 1)) ) axis <- element_grob(elements$axis_line, x = axis$x, y = axis$y) @@ -358,7 +357,7 @@ parse_binned_breaks <- function(scale, breaks = scale$get_breaks()) { if (anyNA(nums)) { cli::cli_abort(c( "Breaks are not formatted correctly for a bin legend.", - "i" = "Use {.code (, ]} format to indicate bins." + i = "Use {.code (, ]} format to indicate bins." )) } all_breaks <- nums[c(1, seq_along(breaks) * 2)] diff --git a/R/guide-colorbar.R b/R/guide-colorbar.R index c7c424c2ac..680551dcf1 100644 --- a/R/guide-colorbar.R +++ b/R/guide-colorbar.R @@ -252,7 +252,7 @@ GuideColourbar <- ggproto( .size = length(bar) ) if (reverse) { - bar <- bar[nrow(bar):1, , drop = FALSE] + bar <- vec_slice(bar, rev(vec_seq_along(bar))) } return(bar) }, @@ -344,8 +344,8 @@ GuideColourbar <- ggproto( if (!params$draw_lim[2]) pos <- pos[-length(pos)] position <- switch( params$direction, - "horizontal" = c("bottom", "top"), - "vertical" = c("right", "left") + horizontal = c("bottom", "top"), + vertical = c("right", "left") ) ticks_length <- rep(elements$ticks_length, length.out = 2) @@ -359,8 +359,8 @@ GuideColourbar <- ggproto( if (params$display == "raster") { image <- switch( params$direction, - "horizontal" = t(decor$colour), - "vertical" = rev(decor$colour) + horizontal = t(decor$colour), + vertical = rev(decor$colour) ) grob <- rasterGrob( image = image, diff --git a/R/guide-colorsteps.R b/R/guide-colorsteps.R index 54cd89a948..41ac92ddde 100644 --- a/R/guide-colorsteps.R +++ b/R/guide-colorsteps.R @@ -134,7 +134,7 @@ GuideColoursteps <- ggproto( extract_decor = function(scale, aesthetic, key, reverse = FALSE, even.steps = TRUE, - nbin = 100, alpha = NA,...) { + nbin = 100, alpha = NA, ...) { parsed <- attr(key, "parsed") breaks <- parsed$breaks %||% scale$get_breaks() @@ -165,7 +165,7 @@ GuideColoursteps <- ggproto( cli::cli_warn(c(paste0( "{.arg show.limits} is ignored when {.arg labels} are given as a ", "character vector." - ), "i" = paste0( + ), i = paste0( "Either add the limits to {.arg breaks} or provide a function for ", "{.arg labels}." ))) diff --git a/R/guide-legend.R b/R/guide-legend.R index 37aad2e3f0..e242575243 100644 --- a/R/guide-legend.R +++ b/R/guide-legend.R @@ -187,7 +187,7 @@ GuideLegend <- ggproto( title = waiver(), ...) { params$title <- scale$make_title(params$title %|W|% scale$name %|W|% title) if (isTRUE(params$reverse %||% FALSE)) { - params$key <- params$key[nrow(params$key):1, , drop = FALSE] + params$key <- vec_slice(params$key, rev(vec_seq_along(params$key))) } params }, @@ -457,8 +457,8 @@ GuideLegend <- ggproto( hgap <- elements$spacing_x %||% 0 widths <- switch( elements$text_position, - "left" = list(label_widths, widths, hgap), - "right" = list(widths, label_widths, hgap), + left = list(label_widths, widths, hgap), + right = list(widths, label_widths, hgap), list(pmax(label_widths, widths), hgap) ) widths <- head(vec_interleave(!!!widths), -1) @@ -466,8 +466,8 @@ GuideLegend <- ggproto( vgap <- elements$spacing_y %||% 0 heights <- switch( elements$text_position, - "top" = list(label_heights, heights, vgap), - "bottom" = list(heights, label_heights, vgap), + top = list(label_heights, heights, vgap), + bottom = list(heights, label_heights, vgap), list(pmax(label_heights, heights), vgap) ) heights <- head(vec_interleave(!!!heights), -1) @@ -559,7 +559,7 @@ GuideLegend <- ggproto( gt <- gtable_add_grob( gt, elements$background, name = "background", clip = "off", - t = 1, r = -1, b = -1, l =1, z = -Inf + t = 1, r = -1, b = -1, l = 1, z = -Inf ) } gt @@ -599,7 +599,7 @@ get_key_size <- function(keys, which = "width", n) { } set_key_size <- function(key, linewidth = NULL, size = NULL, default = NULL) { - if (!is.null(attr(key, "width")) && !is.null(attr(key, 'height'))) { + if (!is.null(attr(key, "width")) && !is.null(attr(key, "height"))) { return(key) } if (!is.null(size) || !is.null(linewidth)) { @@ -678,20 +678,21 @@ position_margin <- function(position, margin = NULL, gap = unit(0, "pt")) { # Function implementing backward compatibility with the old way of specifying # guide styling deprecated_guide_args <- function( - theme = NULL, - title.position = NULL, - title.theme = NULL, title.hjust = NULL, title.vjust = NULL, - label = NULL, - label.position = NULL, - label.theme = NULL, label.hjust = NULL, label.vjust = NULL, - keywidth = NULL, keyheight = NULL, barwidth = NULL, barheight = NULL, - byrow = NULL, - frame.colour = NULL, frame.linewidth = NULL, frame.linetype = NULL, - ticks = NULL, ticks.colour = NULL, ticks.linewidth = NULL, - axis = NULL, axis.colour = NULL, axis.linewidth = NULL, axis.arrow = NULL, - default.unit = "line", - ..., - .call = caller_call()) { + theme = NULL, + title.position = NULL, + title.theme = NULL, title.hjust = NULL, title.vjust = NULL, + label = NULL, + label.position = NULL, + label.theme = NULL, label.hjust = NULL, label.vjust = NULL, + keywidth = NULL, keyheight = NULL, barwidth = NULL, barheight = NULL, + byrow = NULL, + frame.colour = NULL, frame.linewidth = NULL, frame.linetype = NULL, + ticks = NULL, ticks.colour = NULL, ticks.linewidth = NULL, + axis = NULL, axis.colour = NULL, axis.linewidth = NULL, axis.arrow = NULL, + default.unit = "line", + ..., + .call = caller_call()) { + warn_dots_used(call = .call) args <- names(formals(deprecated_guide_args)) diff --git a/R/guide-old.R b/R/guide-old.R index de870965fd..9526713e91 100644 --- a/R/guide-old.R +++ b/R/guide-old.R @@ -117,4 +117,3 @@ GuideOld <- ggproto( guide_gengrob(params, theme) } ) - diff --git a/R/labeller.R b/R/labeller.R index 4ca220c2b4..858595fd1c 100644 --- a/R/labeller.R +++ b/R/labeller.R @@ -92,7 +92,7 @@ NULL collapse_labels_lines <- function(labels) { is_exp <- vapply(labels, function(l) length(l) > 0 && is.expression(l[[1]]), logical(1)) - out <- inject(mapply(paste, !!!labels, sep = ", ", SIMPLIFY = FALSE)) + out <- inject(Map(paste, !!!labels, sep = ", ")) label <- list(unname(unlist(out))) if (all(is_exp)) { label <- lapply(label, function(l) list(parse(text = paste0("list(", l, ")")))) @@ -208,7 +208,7 @@ label_bquote <- function(rows = NULL, cols = NULL, params <- as_environment(params, call_env) eval(substitute(bquote(expr, params), list(expr = quoted))) } - list(inject(mapply(evaluate, !!!labels, SIMPLIFY = FALSE))) + list(inject(Map(evaluate, !!!labels))) } structure(fun, class = "labeller") @@ -590,7 +590,7 @@ check_labeller <- function(labeller) { # TODO Update to lifecycle after next lifecycle release cli::cli_warn(c( "The {.arg labeller} API has been updated. Labellers taking {.arg variable} and {.arg value} arguments are now deprecated.", - "i" = "See labellers documentation." + i = "See labellers documentation." )) } diff --git a/R/labels.R b/R/labels.R index 50e3776555..d5c6ba0888 100644 --- a/R/labels.R +++ b/R/labels.R @@ -148,9 +148,11 @@ setup_plot_labels <- function(plot, layers, data) { labs <- function(..., title = waiver(), subtitle = waiver(), caption = waiver(), tag = waiver(), alt = waiver(), alt_insight = waiver()) { # .ignore_empty = "all" is needed to allow trailing commas, which is NOT a trailing comma for dots_list() as it's in ... - args <- dots_list(..., title = title, subtitle = subtitle, caption = caption, + args <- dots_list( + ..., title = title, subtitle = subtitle, caption = caption, tag = tag, alt = allow_lambda(alt), alt_insight = alt_insight, - .ignore_empty = "all") + .ignore_empty = "all" + ) is_waive <- vapply(args, is.waive, logical(1)) args <- args[!is_waive] @@ -332,7 +334,7 @@ generate_alt_text <- function(p) { # Get layer types layers <- vapply(p$layers, function(l) snake_class(l$geom), character(1)) - layers <- sub("_", " ", sub("^geom_", "", unique0(layers))) + layers <- sub("_", " ", sub("^geom_", "", unique0(layers)), fixed = TRUE) if (length(layers) == 1) { layers <- paste0(" using a ", layers, " layer") } else { diff --git a/R/layer-sf.R b/R/layer-sf.R index 3a282e734f..cccc973db3 100644 --- a/R/layer-sf.R +++ b/R/layer-sf.R @@ -44,14 +44,12 @@ LayerSf <- ggproto("LayerSf", Layer, # automatically determine the name of the geometry column # and add the mapping if it doesn't exist - if ((isTRUE(self$inherit.aes) && is.null(self$computed_mapping$geometry) && - is.null(plot$computed_mapping$geometry)) || - (!isTRUE(self$inherit.aes) && is.null(self$computed_mapping$geometry))) { - if (is_sf(data)) { - geometry_col <- attr(data, "sf_column") - self$computed_mapping$geometry <- sym(geometry_col) - } + if (is.null(self$computed_mapping$geometry) && is_sf(data) && + (!isTRUE(self$inherit.aes) || is.null(plot$computed_mapping$geometry))) { + geometry_col <- attr(data, "sf_column") + self$computed_mapping$geometry <- sym(geometry_col) } + data }, compute_geom_1 = function(self, data) { diff --git a/R/layer.R b/R/layer.R index 3fd89cf3f7..9154cd00c8 100644 --- a/R/layer.R +++ b/R/layer.R @@ -212,7 +212,7 @@ validate_mapping <- function(mapping, call = caller_env()) { # Native pipe have higher precedence than + so any type of gg object can be # expected here, not just ggplot if (inherits(mapping, "gg")) { - msg <- c(msg, "i" = "Did you use {.code %>%} or {.code |>} instead of {.code +}?") + msg <- c(msg, i = "Did you use {.code %>%} or {.code |>} instead of {.code +}?") } cli::cli_abort(msg, call = call) @@ -245,10 +245,8 @@ Layer <- ggproto("Layer", NULL, if (!is.null(self$mapping)) { cat("mapping:", clist(self$mapping), "\n") } - cat(snakeize(class(self$geom)[[1]]), ": ", clist(self$geom_params), "\n", - sep = "") - cat(snakeize(class(self$stat)[[1]]), ": ", clist(self$stat_params), "\n", - sep = "") + cat(snakeize(class(self$geom)[[1]]), ": ", clist(self$geom_params), "\n", sep = "") + cat(snakeize(class(self$stat)[[1]]), ": ", clist(self$stat_params), "\n", sep = "") cat(snakeize(class(self$position)[[1]]), "\n") }, @@ -323,9 +321,9 @@ Layer <- ggproto("Layer", NULL, names(issues) <- rep("x", length(issues)) cli::cli_abort(c( "Aesthetics are not valid data columns.", - "x" = "The following aesthetics are invalid:", + x = "The following aesthetics are invalid:", issues, - "i" = "Did you mistype the name of a data column or forget to add {.fn after_stat}?" + i = "Did you mistype the name of a data column or forget to add {.fn after_stat}?" )) } @@ -405,9 +403,9 @@ Layer <- ggproto("Layer", NULL, names(issues) <- rep("x", length(issues)) cli::cli_abort(c( "Aesthetics must be valid computed stats.", - "x" = "The following aesthetics are invalid:", + x = "The following aesthetics are invalid:", issues, - "i" = "Did you map your stat in the wrong layer?" + i = "Did you map your stat in the wrong layer?" )) } diff --git a/R/layout.R b/R/layout.R index 1b578111b2..ec13fe83c6 100644 --- a/R/layout.R +++ b/R/layout.R @@ -122,12 +122,14 @@ Layout <- ggproto("Layout", NULL, # Initialise scales if needed, and possible. layout <- self$layout if (is.null(self$panel_scales_x)) { - self$panel_scales_x <- self$facet$init_scales(layout, x_scale = x_scale, - params = self$facet_params)$x + self$panel_scales_x <- self$facet$init_scales( + layout, x_scale = x_scale, params = self$facet_params + )$x } if (is.null(self$panel_scales_y)) { - self$panel_scales_y <- self$facet$init_scales(layout, y_scale = y_scale, - params = self$facet_params)$y + self$panel_scales_y <- self$facet$init_scales( + layout, y_scale = y_scale, params = self$facet_params + )$y } self$facet$train_scales( @@ -250,7 +252,8 @@ Layout <- ggproto("Layout", NULL, waiver() } else { scale$sec_name() - } %|W|% labels[[paste0("sec.", aes)]] + } + secondary <- secondary %|W|% labels[[paste0("sec.", aes)]] if (is.derived(secondary)) secondary <- primary order <- scale$axis_order() diff --git a/R/legend-draw.R b/R/legend-draw.R index ccfb035872..f1ad7716ce 100644 --- a/R/legend-draw.R +++ b/R/legend-draw.R @@ -83,7 +83,8 @@ draw_key_polygon <- function(data, params, size) { lwd = lwd, linejoin = params$linejoin %||% "mitre", lineend = params$lineend %||% "butt" - )) + ) + ) # Magic number is 5 because we convert mm to cm (divide by 10) but we # draw two lines in each direction (times 2) diff --git a/R/limits.R b/R/limits.R index 2e31220ec8..ccaea33df8 100644 --- a/R/limits.R +++ b/R/limits.R @@ -126,7 +126,7 @@ limits.numeric <- function(lims, var, call = caller_env()) { } make_scale <- function(type, var, ..., call = NULL) { - name <- paste("scale_", var, "_", type, sep = "") + name <- paste0("scale_", var, "_", type) scale <- match.fun(name) sc <- scale(...) sc$call <- call %||% parse_expr(paste0(name, "()")) diff --git a/R/margins.R b/R/margins.R index 7104a7d330..e945069ef6 100644 --- a/R/margins.R +++ b/R/margins.R @@ -223,7 +223,7 @@ font_descent <- function(family = "", face = "plain", size = 12, cex = 1) { } else { cache <- TRUE } - key <- paste0(cur_dev, ':', family, ':', face, ":", size, ":", cex) + key <- paste0(cur_dev, ":", family, ":", face, ":", size, ":", cex) # we only look up the first result; this function is not vectorized key <- key[1] @@ -238,7 +238,7 @@ font_descent <- function(family = "", face = "plain", size = 12, cex = 1) { fontfamily = family, fontface = face ) - )), 'inches') + )), "inches") if (cache) { descent_cache[[key]] <- descent diff --git a/R/performance.R b/R/performance.R index 7676ed31d6..c471560ca2 100644 --- a/R/performance.R +++ b/R/performance.R @@ -18,6 +18,6 @@ modify_list <- function(old, new) { modifyList <- function(...) { cli::cli_abort(c( "Please use {.fn modify_list} instead of {.fn modifyList} for better performance.", - "i" = "See the vignette {.emph ggplot2 internal programming guidelines} for details." + i = "See the vignette {.emph ggplot2 internal programming guidelines} for details." )) } diff --git a/R/plot-build.R b/R/plot-build.R index c7e641c8e6..64a2822e1a 100644 --- a/R/plot-build.R +++ b/R/plot-build.R @@ -27,7 +27,7 @@ ggplot_build <- function(plot) { # Attaching the plot env to be fetched by deprecations etc. attach_plot_env(plot$plot_env) - UseMethod('ggplot_build') + UseMethod("ggplot_build") } #' @export @@ -197,7 +197,7 @@ ggplot_gtable <- function(data) { # Attaching the plot env to be fetched by deprecations etc. attach_plot_env(data$plot$plot_env) - UseMethod('ggplot_gtable') + UseMethod("ggplot_gtable") } #' @export @@ -271,16 +271,22 @@ ggplot_gtable.ggplot_built <- function(data) { } plot_table <- gtable_add_rows(plot_table, subtitle_height, pos = 0) - plot_table <- gtable_add_grob(plot_table, subtitle, name = "subtitle", - t = 1, b = 1, l = title_l, r = title_r, clip = "off") + plot_table <- gtable_add_grob( + plot_table, subtitle, name = "subtitle", + t = 1, b = 1, l = title_l, r = title_r, clip = "off" + ) plot_table <- gtable_add_rows(plot_table, title_height, pos = 0) - plot_table <- gtable_add_grob(plot_table, title, name = "title", - t = 1, b = 1, l = title_l, r = title_r, clip = "off") + plot_table <- gtable_add_grob( + plot_table, title, name = "title", + t = 1, b = 1, l = title_l, r = title_r, clip = "off" + ) plot_table <- gtable_add_rows(plot_table, caption_height, pos = -1) - plot_table <- gtable_add_grob(plot_table, caption, name = "caption", - t = -1, b = -1, l = caption_l, r = caption_r, clip = "off") + plot_table <- gtable_add_grob( + plot_table, caption, name = "caption", + t = -1, b = -1, l = caption_l, r = caption_r, clip = "off" + ) plot_table <- table_add_tag(plot_table, plot$labels$tag, theme) @@ -292,7 +298,7 @@ ggplot_gtable.ggplot_built <- function(data) { plot_table <- gtable_add_grob(plot_table, element_render(theme, "plot.background"), t = 1, l = 1, b = -1, r = -1, name = "background", z = -Inf) - plot_table$layout <- plot_table$layout[c(nrow(plot_table$layout), 1:(nrow(plot_table$layout) - 1)),] + plot_table$layout <- plot_table$layout[c(nrow(plot_table$layout), 1:(nrow(plot_table$layout) - 1)), ] plot_table$grobs <- plot_table$grobs[c(nrow(plot_table$layout), 1:(nrow(plot_table$layout) - 1))] } @@ -322,10 +328,8 @@ by_layer <- function(f, layers, data, step = NULL) { error = function(cnd) { cli::cli_abort(c( "Problem while {step}.", - "i" = "Error occurred in the {ordinal(i)} layer."), - call = layers[[i]]$constructor, - parent = cnd - ) + i = "Error occurred in the {ordinal(i)} layer." + ), call = layers[[i]]$constructor, parent = cnd) } ) out @@ -387,7 +391,10 @@ table_add_tag <- function(table, label, theme) { width <- grobWidth(tag) if (location %in% c("plot", "panel")) { - if (!is.numeric(position)) { + if (is.numeric(position)) { + x <- unit(position[1], "npc") + y <- unit(position[2], "npc") + } else { if (right || left) { x <- (1 - element$hjust) * width if (right) { @@ -404,9 +411,6 @@ table_add_tag <- function(table, label, theme) { } else { y <- unit(element$vjust, "npc") } - } else { - x <- unit(position[1], "npc") - y <- unit(position[2], "npc") } # Re-render with manual positions tag <- element_grob( @@ -472,7 +476,7 @@ table_add_legends <- function(table, legends, theme) { location <- switch( theme$legend.location %||% "panel", - "plot" = plot_extent, + plot = plot_extent, find_panel ) diff --git a/R/plot-construction.R b/R/plot-construction.R index b021b630e9..b9af88264d 100644 --- a/R/plot-construction.R +++ b/R/plot-construction.R @@ -39,11 +39,11 @@ #' # Alternatively, you can add multiple components with a list. #' # This can be useful to return from a function. #' base + list(subset(mpg, fl == "p"), geom_smooth()) -"+.gg" <- function(e1, e2) { +`+.gg` <- function(e1, e2) { if (missing(e2)) { cli::cli_abort(c( - "Cannot use {.code +} with a single argument.", - "i" = "Did you accidentally put {.code +} on a new line?" + "Cannot use {.code +} with a single argument.", + i = "Did you accidentally put {.code +} on a new line?" )) } @@ -56,7 +56,7 @@ else if (is.ggproto(e1)) { cli::cli_abort(c( "Cannot add {.cls ggproto} objects together.", - "i" = "Did you forget to add this object to a {.cls ggplot} object?" + i = "Did you forget to add this object to a {.cls ggplot} object?" )) } } @@ -64,7 +64,7 @@ #' @rdname gg-add #' @export -"%+%" <- `+.gg` +`%+%` <- `+.gg` add_ggplot <- function(p, object, objectname) { if (is.null(object)) return(p) @@ -129,8 +129,8 @@ ggplot_add.data.frame <- function(object, plot, object_name) { #' @export ggplot_add.function <- function(object, plot, object_name) { cli::cli_abort(c( - "Can't add {.var {object_name}} to a {.cls ggplot} object", - "i" = "Did you forget to add parentheses, as in {.fn {object_name}}?" + "Can't add {.var {object_name}} to a {.cls ggplot} object", + i = "Did you forget to add parentheses, as in {.fn {object_name}}?" )) } #' @export diff --git a/R/plot.R b/R/plot.R index f6a6aaeb49..d151f74166 100644 --- a/R/plot.R +++ b/R/plot.R @@ -114,7 +114,7 @@ ggplot.default <- function(data = NULL, mapping = aes(), ..., if (!missing(mapping) && !is.mapping(mapping)) { cli::cli_abort(c( "{.arg mapping} must be created with {.fn aes}.", - "x" = "You've supplied {.obj_type_friendly {mapping}}." + x = "You've supplied {.obj_type_friendly {mapping}}." )) } @@ -144,7 +144,7 @@ ggplot.function <- function(data = NULL, mapping = aes(), ..., # Added to avoid functions end in ggplot.default cli::cli_abort(c( "{.arg data} cannot be a function.", - "i" = "Have you misspelled the {.arg data} argument in {.fn ggplot}" + i = "Have you misspelled the {.arg data} argument in {.fn ggplot}" )) } diff --git a/R/position-collide.R b/R/position-collide.R index 402f6ad7eb..88cb1fff01 100644 --- a/R/position-collide.R +++ b/R/position-collide.R @@ -48,7 +48,7 @@ collide <- function(data, width = NULL, name, strategy, intervals <- as.numeric(t(unique0(data[c("xmin", "xmax")]))) intervals <- intervals[!is.na(intervals)] - if (vec_unique_count(intervals) > 1 & any(diff(scale(intervals)) < -1e-6)) { + if (vec_unique_count(intervals) > 1 && any(diff(scale(intervals)) < -1e-6)) { cli::cli_warn("{.fn {name}} requires non-overlapping {.field x} intervals.") # This is where the algorithm from [L. Wilkinson. Dot plots. # The American Statistician, 1999.] should be used diff --git a/R/position-dodge.R b/R/position-dodge.R index 78d4a9a45f..c0f90e74bf 100644 --- a/R/position-dodge.R +++ b/R/position-dodge.R @@ -115,7 +115,7 @@ PositionDodge <- ggproto("PositionDodge", Position, if (is.null(data$xmin) && is.null(data$xmax) && is.null(self$width)) { cli::cli_warn(c( "Width not defined", - "i" = "Set with {.code position_dodge(width = ...)}" + i = "Set with {.code position_dodge(width = ...)}" )) } diff --git a/R/position-stack.R b/R/position-stack.R index de23456625..2b3c96915a 100644 --- a/R/position-stack.R +++ b/R/position-stack.R @@ -213,7 +213,7 @@ PositionStack <- ggproto("PositionStack", Position, ) } - data <- vec_rbind0(neg, pos)[match(seq_len(nrow(data)), c(which(negative), which(!negative))),] + data <- vec_rbind0(neg, pos)[match(seq_len(nrow(data)), c(which(negative), which(!negative))), ] flip_data(data, params$flipped_aes) } ) @@ -226,7 +226,7 @@ pos_stack <- function(df, width, vjust = 1, fill = FALSE) { if (fill) { heights <- heights / abs(heights[length(heights)]) } -# We need to preserve ymin/ymax order. If ymax is lower than ymin in input, it should remain that way + # We need to preserve ymin/ymax order. If ymax is lower than ymin in input, it should remain that way if (!is.null(df$ymin) && !is.null(df$ymax)) { max_is_lower <- df$ymax < df$ymin } else { @@ -260,7 +260,7 @@ stack_var <- function(data) { } else { cli::cli_warn(c( "Stacking requires either the {.field ymin} {.emph and} {.field ymax} or the {.field y} aesthetics", - "i" = "Maybe you want {.code position = \"identity\"}?" + i = "Maybe you want {.code position = \"identity\"}?" )) NULL } diff --git a/R/quick-plot.R b/R/quick-plot.R index 38cfd895fc..b464c0767a 100644 --- a/R/quick-plot.R +++ b/R/quick-plot.R @@ -154,7 +154,7 @@ qplot <- function(x, y, ..., data, facets = NULL, margins = FALSE, p <- p + do.call(paste0("geom_", g), params) } - logv <- function(var) var %in% strsplit(log, "")[[1]] + logv <- function(var) var %in% strsplit(log, "", fixed = TRUE)[[1]] if (logv("x")) p <- p + scale_x_log10() if (logv("y")) p <- p + scale_y_log10() diff --git a/R/reshape-add-margins.R b/R/reshape-add-margins.R index 4603268214..a4708f7877 100644 --- a/R/reshape-add-margins.R +++ b/R/reshape-add-margins.R @@ -37,17 +37,17 @@ reshape_margins <- function(vars, margins = NULL) { dims <- lapply(vars, intersect, margins) # Next, ensure high-level margins include lower-levels - dims <- mapply(function(vars, margin) { + dims <- Map(function(vars, margin) { lapply(margin, downto, vars) - }, vars, dims, SIMPLIFY = FALSE, USE.NAMES = FALSE) + }, vars, dims, USE.NAMES = FALSE) # Finally, find intersections across all dimensions seq_0 <- function(x) c(0, seq_along(x)) indices <- expand.grid(lapply(dims, seq_0), KEEP.OUT.ATTRS = FALSE) # indices <- indices[rowSums(indices) > 0, ] - lapply(seq_len(nrow(indices)), function(i){ - unlist(mapply("[", dims, indices[i, ], SIMPLIFY = FALSE)) + lapply(seq_len(nrow(indices)), function(i) { + unlist(Map("[", dims, indices[i, ])) }) } diff --git a/R/save.R b/R/save.R index ffe6945410..3997614240 100644 --- a/R/save.R +++ b/R/save.R @@ -99,8 +99,10 @@ ggsave <- function(filename, plot = get_last_plot(), dpi <- parse_dpi(dpi) dev <- plot_dev(device, filename, dpi = dpi) - dim <- plot_dim(c(width, height), scale = scale, units = units, - limitsize = limitsize, dpi = dpi) + dim <- plot_dim( + c(width, height), scale = scale, units = units, + limitsize = limitsize, dpi = dpi + ) if (is_null(bg)) { bg <- calc_element("plot.background", plot_theme(plot))$fill %||% "transparent" @@ -146,7 +148,7 @@ check_path <- function(path, filename, create.dir, if (interactive() && !create.dir) { cli::cli_bullets(c( "Cannot find directory {.path {path}}.", - "i" = "Would you like to create a new directory?" + i = "Would you like to create a new directory?" )) create.dir <- utils::menu(c("Yes", "No")) == 1 } @@ -228,8 +230,8 @@ plot_dim <- function(dim = c(NA, NA), scale = 1, units = "in", } cli::cli_abort(c( msg, - "i" = "If you're sure you want a plot that big, use {.code limitsize = FALSE}. - "), call = call) + i = "If you're sure you want a plot that big, use {.code limitsize = FALSE}." + ), call = call) } dim @@ -250,7 +252,7 @@ plot_dev <- function(device, filename = NULL, dpi = 300, call = caller_env()) { call_args$res <- dpi } if ("units" %in% names(args)) { - call_args$units <- 'in' + call_args$units <- "in" } dev <- function(...) { args <- modify_list(list(...), call_args) @@ -260,10 +262,12 @@ plot_dev <- function(device, filename = NULL, dpi = 300, call = caller_env()) { } eps <- function(filename, ...) { - grDevices::postscript(file = filename, ..., onefile = FALSE, horizontal = FALSE, - paper = "special") + grDevices::postscript( + file = filename, ..., onefile = FALSE, horizontal = FALSE, + paper = "special" + ) } - if (requireNamespace('ragg', quietly = TRUE)) { + if (requireNamespace("ragg", quietly = TRUE)) { png_dev <- absorb_grdevice_args(ragg::agg_png) jpeg_dev <- absorb_grdevice_args(ragg::agg_jpeg) tiff_dev <- absorb_grdevice_args(ragg::agg_tiff) @@ -294,8 +298,8 @@ plot_dev <- function(device, filename = NULL, dpi = 300, call = caller_env()) { if (identical(device, "")) { cli::cli_abort(c( "Can't save to {filename}.", - i = "Either supply {.arg filename} with a file extension or supply {.arg device}."), - call = call) + i = "Either supply {.arg filename} with a file extension or supply {.arg device}." + ), call = call) } } diff --git a/R/scale-.R b/R/scale-.R index 878cc602b9..958c84220e 100644 --- a/R/scale-.R +++ b/R/scale-.R @@ -224,7 +224,7 @@ discrete_scale <- function(aesthetics, scale_name = deprecated(), palette, name if (!is.function(limits) && (length(limits) > 0) && !is.discrete(limits)) { cli::cli_warn(c( "Continuous limits supplied to discrete scale.", - "i" = "Did you mean {.code limits = factor(...)} or {.fn scale_*_continuous}?" + i = "Did you mean {.code limits = factor(...)} or {.fn scale_*_continuous}?" ), call = call) } @@ -663,16 +663,15 @@ ScaleContinuous <- ggproto("ScaleContinuous", Scale, return() } # Intercept error here to give examples and mention scale in call - if (is.factor(x) || !typeof(x) %in% c("integer", "double")) { + if ((is.factor(x) || !typeof(x) %in% c("integer", "double")) && + inherits(self$range, "ContinuousRange")) { # These assumptions only hold for standard ContinuousRange class, so # we skip the error if another range class is used - if (inherits(self$range, "ContinuousRange")) { - cli::cli_abort( - c("Discrete values supplied to continuous scale.", - i = "Example values: {.and {.val {head(x, 5)}}}"), - call = self$call - ) - } + cli::cli_abort( + c("Discrete values supplied to continuous scale.", + i = "Example values: {.and {.val {head(x, 5)}}}"), + call = self$call + ) } self$range$train(x) }, @@ -941,16 +940,14 @@ ScaleDiscrete <- ggproto("ScaleDiscrete", Scale, return() } # Intercept error here to give examples and mention scale in call - if (!is.discrete(x)) { + if (!is.discrete(x) && inherits(self$range, "DiscreteRange")) { # These assumptions only hold for standard DiscreteRange class, so # we skip the error if another range class is used - if (inherits(self$range, "DiscreteRange")) { - cli::cli_abort( - c("Continuous values supplied to discrete scale.", - i = "Example values: {.and {.val {head(x, 5)}}}"), - call = self$call - ) - } + cli::cli_abort( + c("Continuous values supplied to discrete scale.", + i = "Example values: {.and {.val {head(x, 5)}}}"), + call = self$call + ) } self$range$train(x, drop = self$drop, na.rm = !self$na.translate) }, diff --git a/R/scale-alpha.R b/R/scale-alpha.R index 53344f23be..f7b4c3e2ed 100644 --- a/R/scale-alpha.R +++ b/R/scale-alpha.R @@ -78,7 +78,7 @@ scale_alpha_datetime <- function(name = waiver(), ..., range = c(0.1, 1)) { #' @rdname scale_alpha #' @export #' @usage NULL -scale_alpha_date <- function(name = waiver(), ..., range = c(0.1, 1)){ +scale_alpha_date <- function(name = waiver(), ..., range = c(0.1, 1)) { datetime_scale( aesthetics = "alpha", transform = "date", name = name, palette = pal_rescale(range), diff --git a/R/scale-brewer.R b/R/scale-brewer.R index af115ea13f..3473ea025d 100644 --- a/R/scale-brewer.R +++ b/R/scale-brewer.R @@ -116,7 +116,7 @@ scale_colour_distiller <- function(name = waiver(), ..., type = "seq", if (type == "qual") { cli::cli_warn(c( "Using a discrete colour palette in a continuous scale", - "i" = "Consider using {.code type = \"seq\"} or {.code type = \"div\"} instead" + i = "Consider using {.code type = \"seq\"} or {.code type = \"div\"} instead" )) } continuous_scale( @@ -138,7 +138,7 @@ scale_fill_distiller <- function(name = waiver(), ..., type = "seq", if (type == "qual") { cli::cli_warn(c( "Using a discrete colour palette in a continuous scale", - "i" = "Consider using {.code type = \"seq\"} or {.code type = \"div\"} instead" + i = "Consider using {.code type = \"seq\"} or {.code type = \"div\"} instead" )) } continuous_scale( @@ -159,7 +159,7 @@ scale_colour_fermenter <- function(name = waiver(), ..., type = "seq", if (type == "qual") { cli::cli_warn(c( "Using a discrete colour palette in a binned scale", - "i" = "Consider using {.code type = \"seq\"} or {.code type = \"div\"} instead" + i = "Consider using {.code type = \"seq\"} or {.code type = \"div\"} instead" )) } binned_scale( @@ -179,7 +179,7 @@ scale_fill_fermenter <- function(name = waiver(), ..., type = "seq", palette = 1 if (type == "qual") { cli::cli_warn(c( "Using a discrete colour palette in a binned scale", - "i" = "Consider using {.code type = \"seq\"} or {.code type = \"div\"} instead" + i = "Consider using {.code type = \"seq\"} or {.code type = \"div\"} instead" )) } binned_scale( diff --git a/R/scale-colour.R b/R/scale-colour.R index 19cdda1396..9ac2970b2f 100644 --- a/R/scale-colour.R +++ b/R/scale-colour.R @@ -95,7 +95,7 @@ scale_colour_continuous <- function(..., } else { cli::cli_abort(c( "Unknown scale type: {.val {type}}", - "i" = "Use either {.val gradient} or {.val viridis}." + i = "Use either {.val gradient} or {.val viridis}." )) } } @@ -120,7 +120,7 @@ scale_fill_continuous <- function(..., } else { cli::cli_abort(c( "Unknown scale type: {.val {type}}", - "i" = "Use either {.val gradient} or {.val viridis}." + i = "Use either {.val gradient} or {.val viridis}." )) } } @@ -153,7 +153,7 @@ scale_colour_binned <- function(..., } else { cli::cli_abort(c( "Unknown scale type: {.val {type}}", - "i" = "Use either {.val gradient} or {.val viridis}." + i = "Use either {.val gradient} or {.val viridis}." )) } } @@ -187,7 +187,7 @@ scale_fill_binned <- function(..., } else { cli::cli_abort(c( "Unknown scale type: {.val {type}}", - "i" = "Use either {.val gradient} or {.val viridis}." + i = "Use either {.val gradient} or {.val viridis}." )) } } @@ -200,13 +200,13 @@ check_scale_type <- function(scale, name, aesthetic, scale_is_discrete = FALSE, if (!is.ggproto(scale) || !is.scale(scale)) { cli::cli_abort(c( "The {.arg type} argument must return a continuous scale for the {.field {aesthetic}} aesthetic.", - "x" = "The provided object is not a scale function." + x = "The provided object is not a scale function." ), call = call) } if (!isTRUE(aesthetic %in% scale$aesthetics)) { cli::cli_abort(c( "The {.arg type} argument must return a continuous scale for the {.field {aesthetic}} aesthetic.", - "x" = "The provided scale works with the following aesthetics: {.field {scale$aesthetics}}." + x = "The provided scale works with the following aesthetics: {.field {scale$aesthetics}}." ), call = call) } if (isTRUE(scale$is_discrete()) != scale_is_discrete) { @@ -216,7 +216,7 @@ check_scale_type <- function(scale, name, aesthetic, scale_is_discrete = FALSE, } cli::cli_abort(c( "The {.arg type} argument must return a {scale_types[1]} scale for the {.field {aesthetic}} aesthetic.", - "x" = "The provided scale is {scale_types[2]}." + x = "The provided scale is {scale_types[2]}." ), call = call) } diff --git a/R/scale-continuous.R b/R/scale-continuous.R index 9d6eee9ca9..7c8fc632a7 100644 --- a/R/scale-continuous.R +++ b/R/scale-continuous.R @@ -160,10 +160,10 @@ ScaleContinuousPosition <- ggproto("ScaleContinuousPosition", ScaleContinuous, } }, make_sec_title = function(self, title) { - if (!is.waive(self$secondary.axis)) { - self$secondary.axis$make_title(title) - } else { + if (is.waive(self$secondary.axis)) { ggproto_parent(ScaleContinuous, self)$make_sec_title(title) + } else { + self$secondary.axis$make_title(title) } } ) @@ -209,4 +209,3 @@ scale_override_call <- function(call = NULL) { } !any(startsWith(as.character(call[[1]]), "scale_")) } - diff --git a/R/scale-date.R b/R/scale-date.R index 36f8b37d83..00a02c5bc0 100644 --- a/R/scale-date.R +++ b/R/scale-date.R @@ -390,13 +390,12 @@ ScaleContinuousDatetime <- ggproto("ScaleContinuousDatetime", ScaleContinuous, } }, make_sec_title = function(self, title) { - if (!is.waive(self$secondary.axis)) { - self$secondary.axis$make_title(title) - } else { + if (is.waive(self$secondary.axis)) { ggproto_parent(ScaleContinuous, self)$make_sec_title(title) + } else { + self$secondary.axis$make_title(title) } } - ) #' @rdname ggplot2-ggproto @@ -441,10 +440,10 @@ ScaleContinuousDate <- ggproto("ScaleContinuousDate", ScaleContinuous, } }, make_sec_title = function(self, title) { - if (!is.waive(self$secondary.axis)) { - self$secondary.axis$make_title(title) - } else { + if (is.waive(self$secondary.axis)) { ggproto_parent(ScaleContinuous, self)$make_sec_title(title) + } else { + self$secondary.axis$make_title(title) } } ) diff --git a/R/scale-discrete-.R b/R/scale-discrete-.R index 8fea10caf2..b370549ac3 100644 --- a/R/scale-discrete-.R +++ b/R/scale-discrete-.R @@ -121,7 +121,7 @@ ScaleDiscretePosition <- ggproto("ScaleDiscretePosition", ScaleDiscrete, } # if self$limits is not NULL and is a function, apply it to range - if (is.function(self$limits)){ + if (is.function(self$limits)) { return(self$limits(self$range$range)) } @@ -214,7 +214,7 @@ c.mapped_discrete <- function(..., recursive = FALSE) { mapped_discrete(NextMethod()) } #' @export -as.data.frame.mapped_discrete <- function (x, ...) { +as.data.frame.mapped_discrete <- function(x, ...) { as.data.frame.vector(x = unclass(x), ...) } @@ -254,4 +254,3 @@ vec_cast.mapped_discrete.factor <- function(x, to, ...) mapped_discrete(as.vecto vec_cast.factor.mapped_discrete <- function(x, to, ...) factor(as.vector(x), ...) #' @export vec_cast.mapped_discrete.logical <- function(x, to, ...) mapped_discrete(x) - diff --git a/R/scale-expansion.R b/R/scale-expansion.R index 0edb01f1b8..f56a71e0b0 100644 --- a/R/scale-expansion.R +++ b/R/scale-expansion.R @@ -65,7 +65,7 @@ expand_scale <- function(mult = 0, add = 0) { #' @noRd #' expand_range4 <- function(limits, expand) { - if (!(is.numeric(expand) && length(expand) %in% c(2,4))) { + if (!(is.numeric(expand) && length(expand) %in% c(2, 4))) { cli::cli_abort("{.arg expand} must be a numeric vector with 2 or 4 elements.") } diff --git a/R/scale-linetype.R b/R/scale-linetype.R index d4ea6df26d..da6c537cf3 100644 --- a/R/scale-linetype.R +++ b/R/scale-linetype.R @@ -60,7 +60,7 @@ scale_linetype_binned <- function(name = waiver(), ..., na.value = NA) { scale_linetype_continuous <- function(...) { cli::cli_abort(c( "A continuous variable cannot be mapped to the {.field linetype} aesthetic.", - "i" = "Choose a different aesthetic or use {.fn scale_linetype_binned}." + i = "Choose a different aesthetic or use {.fn scale_linetype_binned}." )) } #' @rdname scale_linetype diff --git a/R/scale-linewidth.R b/R/scale-linewidth.R index 801df22b3a..925b9e5b1e 100644 --- a/R/scale-linewidth.R +++ b/R/scale-linewidth.R @@ -45,10 +45,12 @@ scale_linewidth <- scale_linewidth_continuous #' @rdname scale_linewidth #' @export -scale_linewidth_binned <- function(name = waiver(), breaks = waiver(), labels = waiver(), - limits = NULL, range = c(1, 6), n.breaks = NULL, - nice.breaks = TRUE, transform = "identity", - trans = deprecated(), guide = "bins") { +scale_linewidth_binned <- function( + name = waiver(), breaks = waiver(), labels = waiver(), + limits = NULL, range = c(1, 6), n.breaks = NULL, + nice.breaks = TRUE, transform = "identity", + trans = deprecated(), guide = "bins") { + binned_scale("linewidth", palette = pal_rescale(range), name = name, breaks = breaks, labels = labels, limits = limits, transform = transform, trans = trans, n.breaks = n.breaks, diff --git a/R/scale-shape.R b/R/scale-shape.R index ecb8a2a2a1..870eb029f1 100644 --- a/R/scale-shape.R +++ b/R/scale-shape.R @@ -73,6 +73,6 @@ scale_shape_ordinal <- function(...) { scale_shape_continuous <- function(...) { cli::cli_abort(c( "A continuous variable cannot be mapped to the {.field shape} aesthetic.", - "i" = "Choose a different aesthetic or use {.fn scale_shape_binned}." + i = "Choose a different aesthetic or use {.fn scale_shape_binned}." )) } diff --git a/R/scale-size.R b/R/scale-size.R index 33f14d4834..ae4751bcd2 100644 --- a/R/scale-size.R +++ b/R/scale-size.R @@ -56,9 +56,11 @@ scale_size_continuous <- function(name = waiver(), breaks = waiver(), labels = w transform = "identity", trans = deprecated(), guide = "legend") { - continuous_scale("size", palette = pal_area(range), name = name, + continuous_scale( + "size", palette = pal_area(range), name = name, breaks = breaks, labels = labels, limits = limits, - transform = transform, trans = trans, guide = guide) + transform = transform, trans = trans, guide = guide + ) } #' @rdname scale_size @@ -71,9 +73,11 @@ scale_radius <- function(name = waiver(), breaks = waiver(), labels = waiver(), limits = NULL, range = c(1, 6), transform = "identity", trans = deprecated(), guide = "legend") { - continuous_scale("size", palette = pal_rescale(range), name = name, + continuous_scale( + "size", palette = pal_rescale(range), name = name, breaks = breaks, labels = labels, limits = limits, transform = transform, - trans = trans, guide = guide) + trans = trans, guide = guide + ) } #' @rdname scale_size diff --git a/R/scale-view.R b/R/scale-view.R index 3cf18147ec..36772a1e9e 100644 --- a/R/scale-view.R +++ b/R/scale-view.R @@ -18,11 +18,11 @@ view_scale_primary <- function(scale, limits = scale$get_limits(), # continuous_range can be specified in arbitrary order, but # scales expect the one in ascending order. continuous_scale_sorted <- sort(continuous_range) - if(!scale$is_discrete()) { + if (scale$is_discrete()) { + breaks <- scale$get_breaks(limits) + } else { breaks <- scale$get_breaks(continuous_scale_sorted) breaks <- censor(breaks, continuous_scale_sorted, only.finite = FALSE) - } else { - breaks <- scale$get_breaks(limits) } minor_breaks <- scale$get_breaks_minor(b = breaks, limits = continuous_scale_sorted) minor_breaks <- censor(minor_breaks, continuous_range, only.finite = FALSE) @@ -55,7 +55,7 @@ view_scale_secondary <- function(scale, limits = scale$get_limits(), } else { scale$secondary.axis$init(scale) break_info <- scale$secondary.axis$break_info(continuous_range, scale) - names(break_info) <- gsub("sec\\.", "", names(break_info)) + names(break_info) <- gsub("sec.", "", names(break_info), fixed = TRUE) # flip position from the original scale by default # this can (should) be overridden in the guide diff --git a/R/scales-.R b/R/scales-.R index e62eb0e8cb..572d85b34d 100644 --- a/R/scales-.R +++ b/R/scales-.R @@ -170,4 +170,3 @@ ScalesList <- ggproto("ScalesList", NULL, } } ) - diff --git a/R/stat-.R b/R/stat-.R index 11cdbc67d6..3a7c1f3d91 100644 --- a/R/stat-.R +++ b/R/stat-.R @@ -128,7 +128,7 @@ Stat <- ggproto("Stat", # Record columns that are not constant within groups. We will drop them later. non_constant_columns <- character(0) - stats <- mapply(function(new, old) { + stats <- Map(function(new, old) { # In this function, # # - `new` is the computed result. All the variables will be picked. @@ -160,7 +160,7 @@ Stat <- ggproto("Stat", # one of the group has a constant value (see #4394 for the details). old[rep(1, nrow(new)), , drop = FALSE] ) - }, stats, groups, SIMPLIFY = FALSE) + }, stats, groups) non_constant_columns <- unique0(non_constant_columns) @@ -172,8 +172,8 @@ Stat <- ggproto("Stat", if (length(dropped) > 0) { cli::cli_warn(c( "The following aesthetics were dropped during statistical transformation: {.field {dropped}}.", - "i" = "This can happen when ggplot fails to infer the correct grouping structure in the data.", - "i" = "Did you forget to specify a {.code group} aesthetic or to convert a numerical variable into a factor?" + i = "This can happen when ggplot fails to infer the correct grouping structure in the data.", + i = "Did you forget to specify a {.code group} aesthetic or to convert a numerical variable into a factor?" )) } @@ -212,7 +212,7 @@ Stat <- ggproto("Stat", if (is.null(self$required_aes)) { required_aes <- NULL } else { - required_aes <- unlist(strsplit(self$required_aes, '|', fixed = TRUE)) + required_aes <- unlist(strsplit(self$required_aes, "|", fixed = TRUE)) } c(union(required_aes, names(self$default_aes)), self$optional_aes, "group") } diff --git a/R/stat-bin.R b/R/stat-bin.R index c085f818a2..77343ccfbe 100644 --- a/R/stat-bin.R +++ b/R/stat-bin.R @@ -103,8 +103,8 @@ StatBin <- ggproto("StatBin", Stat, if (is_mapped_discrete(data[[x]])) { cli::cli_abort(c( "{.fn {snake_class(self)}} requires a continuous {.field {x}} aesthetic.", - "x" = "the {.field {x}} aesthetic is discrete.", - "i" = "Perhaps you want {.code stat=\"count\"}?" + x = "the {.field {x}} aesthetic is discrete.", + i = "Perhaps you want {.code stat=\"count\"}?" )) } @@ -149,18 +149,22 @@ StatBin <- ggproto("StatBin", Stat, breaks <- breaks(data[[x]]) } if (!scales[[x]]$is_discrete()) { - breaks <- scales[[x]]$transform(breaks) + breaks <- scales[[x]]$transform(breaks) } bins <- bin_breaks(breaks, closed) } else if (!is.null(binwidth)) { if (is.function(binwidth)) { binwidth <- binwidth(data[[x]]) } - bins <- bin_breaks_width(scales[[x]]$dimension(), binwidth, - center = center, boundary = boundary, closed = closed) + bins <- bin_breaks_width( + scales[[x]]$dimension(), binwidth, + center = center, boundary = boundary, closed = closed + ) } else { - bins <- bin_breaks_bins(scales[[x]]$dimension(), bins, center = center, - boundary = boundary, closed = closed) + bins <- bin_breaks_bins( + scales[[x]]$dimension(), bins, center = center, + boundary = boundary, closed = closed + ) } bins <- bin_vector(data[[x]], bins, weight = data$weight, pad = pad) bins$flipped_aes <- flipped_aes @@ -173,4 +177,3 @@ StatBin <- ggproto("StatBin", Stat, dropped_aes = "weight" # after statistical transformation, weights are no longer available ) - diff --git a/R/stat-bin2d.R b/R/stat-bin2d.R index bdb69db23a..99cd927b72 100644 --- a/R/stat-bin2d.R +++ b/R/stat-bin2d.R @@ -104,7 +104,7 @@ dual_param <- function(x, default = list(x = NULL, y = NULL)) { } bin2d_breaks <- function(scale, breaks = NULL, origin = NULL, binwidth = NULL, - bins = 30, closed = "right") { + bins = 30, closed = "right") { # Bins for categorical data should take the width of one level, # and should show up centered over their tick marks. All other parameters # are ignored. diff --git a/R/stat-bindot.R b/R/stat-bindot.R index 85eecc4d54..ad0308e4e9 100644 --- a/R/stat-bindot.R +++ b/R/stat-bindot.R @@ -6,7 +6,6 @@ StatBindot <- ggproto("StatBindot", Stat, required_aes = "x", non_missing_aes = "weight", default_aes = aes(y = after_stat(count)), - dropped_aes = c("bin", "bincenter"), # these are temporary variables that are created and then removed by the stat setup_params = function(data, params) { if (is.null(params$binwidth)) { @@ -30,15 +29,19 @@ StatBindot <- ggproto("StatBindot", Stat, # for all data before it's split into groups. if (method == "dotdensity" && binpositions == "all") { if (binaxis == "x") { - newdata <- densitybin(x = data$x, weight = data$weight, binwidth = binwidth, - method = method) + newdata <- densitybin( + x = data$x, weight = data$weight, binwidth = binwidth, + method = method + ) data <- data[order(data$x), ] newdata <- newdata[order(newdata$x), ] } else if (binaxis == "y") { - newdata <- densitybin(x = data$y, weight = data$weight, binwidth = binwidth, - method = method) + newdata <- densitybin( + x = data$y, weight = data$weight, binwidth = binwidth, + method = method + ) data <- data[order(data$y), ] newdata <- newdata[order(newdata$x), ] @@ -51,10 +54,12 @@ StatBindot <- ggproto("StatBindot", Stat, } - ggproto_parent(Stat, self)$compute_panel(data, scales, binwidth = binwidth, + ggproto_parent(Stat, self)$compute_panel( + data, scales, binwidth = binwidth, binaxis = binaxis, method = method, binpositions = binpositions, origin = origin, width = width, drop = drop, - right = right) + right = right + ) }, compute_group = function(self, data, scales, binwidth = NULL, binaxis = "x", @@ -95,8 +100,10 @@ StatBindot <- ggproto("StatBindot", Stat, # If bin centers are found by group instead of by all, find the bin centers # (If binpositions=="all", then we'll already have bin centers.) if (binpositions == "bygroup") - data <- densitybin(x = values, weight = data$weight, binwidth = binwidth, - method = method, range = range) + data <- densitybin( + x = values, weight = data$weight, binwidth = binwidth, + method = method, range = range + ) # Collapse each bin and get a count data <- dapply(data, "bincenter", function(x) { @@ -134,43 +141,43 @@ StatBindot <- ggproto("StatBindot", Stat, # It returns a data frame with the original data (x), weights, bin #, and the bin centers. densitybin <- function(x, weight = NULL, binwidth = NULL, method = method, range = NULL) { - if (length(stats::na.omit(x)) == 0) return(data_frame0()) - if (is.null(weight)) weight <- rep(1, length(x)) - weight[is.na(weight)] <- 0 + if (length(stats::na.omit(x)) == 0) return(data_frame0()) + if (is.null(weight)) weight <- rep(1, length(x)) + weight[is.na(weight)] <- 0 - if (is.null(range)) range <- range(x, na.rm = TRUE, finite = TRUE) - if (is.null(binwidth)) binwidth <- diff(range) / 30 + if (is.null(range)) range <- range(x, na.rm = TRUE, finite = TRUE) + if (is.null(binwidth)) binwidth <- diff(range) / 30 - # Sort weight and x, by x - weight <- weight[order(x)] - x <- sort(x, na.last = TRUE) + # Sort weight and x, by x + weight <- weight[order(x)] + x <- sort(x, na.last = TRUE) - cbin <- 0 # Current bin ID - bin <- rep.int(NA, length(x)) # The bin ID for each observation - binend <- -Inf # End position of current bin (scan left to right) + cbin <- 0 # Current bin ID + bin <- rep.int(NA, length(x)) # The bin ID for each observation + binend <- -Inf # End position of current bin (scan left to right) - # Scan list and put dots in bins - for (i in seq_along(x)) { - # If past end of bin, start a new bin at this point - if (x[i] >= binend) { - binend <- x[i] + binwidth - cbin <- cbin + 1 - } - - bin[i] <- cbin + # Scan list and put dots in bins + for (i in seq_along(x)) { + # If past end of bin, start a new bin at this point + if (x[i] >= binend) { + binend <- x[i] + binwidth + cbin <- cbin + 1 } - results <- data_frame0( - x = x, - bin = bin, - binwidth = binwidth, - weight = weight, - .size = length(x) - ) - results <- dapply(results, "bin", function(df) { - df$bincenter = (min(df$x) + max(df$x)) / 2 - return(df) - }) - - return(results) + bin[i] <- cbin + } + + results <- data_frame0( + x = x, + bin = bin, + binwidth = binwidth, + weight = weight, + .size = length(x) + ) + results <- dapply(results, "bin", function(df) { + df$bincenter <- (min(df$x) + max(df$x)) / 2 + return(df) + }) + + return(results) } diff --git a/R/stat-binhex.R b/R/stat-binhex.R index 0b5d3991c6..237b33dec4 100644 --- a/R/stat-binhex.R +++ b/R/stat-binhex.R @@ -65,4 +65,3 @@ StatBinhex <- ggproto("StatBinhex", Stat, # weight is no longer available after transformation dropped_aes = "weight" ) - diff --git a/R/stat-boxplot.R b/R/stat-boxplot.R index 46ce14879f..1799435926 100644 --- a/R/stat-boxplot.R +++ b/R/stat-boxplot.R @@ -47,7 +47,7 @@ stat_boxplot <- function(mapping = NULL, data = NULL, #' @usage NULL #' @export StatBoxplot <- ggproto("StatBoxplot", Stat, - required_aes = c("y|x"), + required_aes = "y|x", non_missing_aes = "weight", # either the x or y aesthetic will get dropped during # statistical transformation, depending on the orientation @@ -81,7 +81,7 @@ StatBoxplot <- ggproto("StatBoxplot", Stat, if (!is_mapped_discrete(data$x) && is.double(data$x) && !has_groups(data) && any(data$x != data$x[1L])) { cli::cli_warn(c( "Continuous {.field {flipped_names(params$flipped_aes)$x}} aesthetic", - "i" = "did you forget {.code aes(group = ...)}?" + i = "did you forget {.code aes(group = ...)}?" )) } diff --git a/R/stat-contour.R b/R/stat-contour.R index e0590f2ec9..4040daa010 100644 --- a/R/stat-contour.R +++ b/R/stat-contour.R @@ -147,7 +147,7 @@ StatContourFilled <- ggproto("StatContourFilled", Stat, path_df$level <- ordered(path_df$level, levels = names(isobands)) path_df$level_low <- breaks[as.numeric(path_df$level)] path_df$level_high <- breaks[as.numeric(path_df$level) + 1] - path_df$level_mid <- 0.5*(path_df$level_low + path_df$level_high) + path_df$level_mid <- 0.5 * (path_df$level_low + path_df$level_high) path_df$nlevel <- rescale_max(path_df$level_high) path_df @@ -182,9 +182,9 @@ contour_breaks <- function(z_range, bins = NULL, binwidth = NULL, breaks = NULL) if (!is.null(bins)) { # round lower limit down and upper limit up to make sure # we generate bins that span the data range nicely - accuracy <- signif(diff(z_range), 1)/10 - z_range[1] <- floor(z_range[1]/accuracy)*accuracy - z_range[2] <- ceiling(z_range[2]/accuracy)*accuracy + accuracy <- signif(diff(z_range), 1) / 10 + z_range[1] <- floor(z_range[1] / accuracy) * accuracy + z_range[2] <- ceiling(z_range[2] / accuracy) * accuracy if (bins == 1) { return(z_range) @@ -317,7 +317,7 @@ pretty_isoband_levels <- function(isoband_levels, dig.lab = 3) { breaks <- unique(c(interval_low, interval_high)) - while(anyDuplicated(format(breaks, digits = dig.lab, trim = TRUE))) { + while (anyDuplicated(format(breaks, digits = dig.lab, trim = TRUE))) { dig.lab <- dig.lab + 1 } diff --git a/R/stat-density-2d.R b/R/stat-density-2d.R index 3fd6cf60ee..63c0b5650a 100644 --- a/R/stat-density-2d.R +++ b/R/stat-density-2d.R @@ -212,4 +212,3 @@ StatDensity2dFilled <- ggproto("StatDensity2dFilled", StatDensity2d, default_aes = aes(colour = NA, fill = after_stat(level)), contour_type = "bands" ) - diff --git a/R/stat-density.R b/R/stat-density.R index 5b948f5d88..3e911efa7c 100644 --- a/R/stat-density.R +++ b/R/stat-density.R @@ -103,9 +103,11 @@ StatDensity <- ggproto("StatDensity", Stat, range <- scales[[flipped_names(flipped_aes)$x]]$dimension() } - density <- compute_density(data$x, data$weight, from = range[1], + density <- compute_density( + data$x, data$weight, from = range[1], to = range[2], bw = bw, adjust = adjust, kernel = kernel, n = n, - bounds = bounds) + bounds = bounds + ) density$flipped_aes <- flipped_aes flip_data(density, flipped_aes) } diff --git a/R/stat-ecdf.R b/R/stat-ecdf.R index 96430b1e32..6b6f206cc9 100644 --- a/R/stat-ecdf.R +++ b/R/stat-ecdf.R @@ -93,7 +93,7 @@ stat_ecdf <- function(mapping = NULL, data = NULL, #' @usage NULL #' @export StatEcdf <- ggproto("StatEcdf", Stat, - required_aes = c("x|y"), + required_aes = "x|y", default_aes = aes(x = after_stat(ecdf), y = after_stat(ecdf), weight = NULL), @@ -151,7 +151,7 @@ wecdf <- function(x, weights = NULL) { cli::cli_warn(c(paste0( "The {.field weight} aesthetic does not support non-finite or ", "{.code NA} values." - ), "i" = "These weights were replaced by {.val 0}.")) + ), i = "These weights were replaced by {.val 0}.")) weights[!is.finite(weights)] <- 0 } @@ -167,7 +167,7 @@ wecdf <- function(x, weights = NULL) { } cli::cli_warn(c( "The sum of the {.field weight} aesthetic is close to {.val 0}.", - "i" = "Computed eCDF might be unstable." + i = "Computed eCDF might be unstable." )) } diff --git a/R/stat-ellipse.R b/R/stat-ellipse.R index 152b27d280..520911950c 100644 --- a/R/stat-ellipse.R +++ b/R/stat-ellipse.R @@ -84,7 +84,7 @@ StatEllipse <- ggproto("StatEllipse", Stat, } ) -calculate_ellipse <- function(data, vars, type, level, segments){ +calculate_ellipse <- function(data, vars, type, level, segments) { dfn <- 2 dfd <- nrow(data) - 1 @@ -96,22 +96,22 @@ calculate_ellipse <- function(data, vars, type, level, segments){ ellipse <- matrix(NA_real_, ncol = 2) } else { if (type == "t") { - v <- MASS::cov.trob(data[,vars]) + v <- MASS::cov.trob(data[, vars]) } else if (type == "norm") { - v <- stats::cov.wt(data[,vars]) + v <- stats::cov.wt(data[, vars]) } else if (type == "euclid") { - v <- stats::cov.wt(data[,vars]) + v <- stats::cov.wt(data[, vars]) v$cov <- diag(rep(min(diag(v$cov)), 2)) } shape <- v$cov center <- v$center chol_decomp <- chol(shape) if (type == "euclid") { - radius <- level/max(chol_decomp) + radius <- level / max(chol_decomp) } else { radius <- sqrt(dfn * stats::qf(level, dfn, dfd)) } - angles <- (0:segments) * 2 * pi/segments + angles <- (0:segments) * 2 * pi / segments unit.circle <- cbind(cos(angles), sin(angles)) ellipse <- t(center + radius * t(unit.circle %*% chol_decomp)) } diff --git a/R/stat-qq-line.R b/R/stat-qq-line.R index 8133216779..8c4d09c44f 100644 --- a/R/stat-qq-line.R +++ b/R/stat-qq-line.R @@ -46,9 +46,9 @@ stat_qq_line <- geom_qq_line StatQqLine <- ggproto("StatQqLine", Stat, default_aes = aes(x = after_stat(x), y = after_stat(y)), - required_aes = c("sample"), + required_aes = "sample", - dropped_aes = c("sample"), + dropped_aes = "sample", compute_group = function(data, scales, diff --git a/R/stat-qq.R b/R/stat-qq.R index dc3762dacd..6341eaef7b 100644 --- a/R/stat-qq.R +++ b/R/stat-qq.R @@ -82,7 +82,7 @@ stat_qq <- geom_qq StatQq <- ggproto("StatQq", Stat, default_aes = aes(y = after_stat(sample), x = after_stat(theoretical)), - required_aes = c("sample"), + required_aes = "sample", compute_group = function(self, data, scales, quantiles = NULL, distribution = stats::qnorm, dparams = list(), diff --git a/R/stat-sf-coordinates.R b/R/stat-sf-coordinates.R index b54c8f6376..869ced0888 100644 --- a/R/stat-sf-coordinates.R +++ b/R/stat-sf-coordinates.R @@ -121,5 +121,5 @@ StatSfCoordinates <- ggproto( }, default_aes = aes(x = after_stat(x), y = after_stat(y)), - required_aes = c("geometry") + required_aes = "geometry" ) diff --git a/R/stat-sf.R b/R/stat-sf.R index cf0b55c0ec..2e177afd31 100644 --- a/R/stat-sf.R +++ b/R/stat-sf.R @@ -10,7 +10,7 @@ StatSf <- ggproto("StatSf", Stat, }, compute_panel = function(data, scales, coord) { - geometry_data <- data[[ geom_column(data) ]] + geometry_data <- data[[geom_column(data)]] geometry_crs <- sf::st_crs(geometry_data) bbox <- sf::st_bbox(geometry_data) @@ -28,8 +28,8 @@ StatSf <- ggproto("StatSf", Stat, # backtransform bbox_trans <- sf_transform_xy( list( - x = c(rep(0.5*(bbox[["xmin"]] + bbox[["xmax"]]), 2), bbox[["xmin"]], bbox[["xmax"]]), - y = c(bbox[["ymin"]], bbox[["ymax"]], rep(0.5*(bbox[["ymin"]] + bbox[["ymax"]]), 2)) + x = c(rep(0.5 * (bbox[["xmin"]] + bbox[["xmax"]]), 2), bbox[["xmin"]], bbox[["xmax"]]), + y = c(bbox[["ymin"]], bbox[["ymax"]], rep(0.5 * (bbox[["ymin"]] + bbox[["ymax"]]), 2)) ), coord$get_default_crs(), geometry_crs @@ -53,7 +53,7 @@ StatSf <- ggproto("StatSf", Stat, data }, - required_aes = c("geometry") + required_aes = "geometry" ) #' @export @@ -76,4 +76,3 @@ stat_sf <- function(mapping = NULL, data = NULL, geom = "rect", ) ) } - diff --git a/R/stat-smooth.R b/R/stat-smooth.R index 147bd06e41..cf66cd7b84 100644 --- a/R/stat-smooth.R +++ b/R/stat-smooth.R @@ -209,7 +209,7 @@ StatSmooth <- ggproto("StatSmooth", Stat, flip_data(prediction, flipped_aes) }, - dropped_aes = c("weight"), + dropped_aes = "weight", required_aes = c("x", "y") ) diff --git a/R/stat-summary-hex.R b/R/stat-summary-hex.R index 959630b4ac..237923c131 100644 --- a/R/stat-summary-hex.R +++ b/R/stat-summary-hex.R @@ -49,7 +49,9 @@ StatSummaryHex <- ggproto("StatSummaryHex", Stat, binwidth <- binwidth %||% hex_binwidth(bins, scales) fun <- as_function(fun) - hexBinSummarise(data$x, data$y, data$z, binwidth, - fun = fun, fun.args = fun.args, drop = drop) + hexBinSummarise( + data$x, data$y, data$z, binwidth, + fun = fun, fun.args = fun.args, drop = drop + ) } ) diff --git a/R/stat-summary.R b/R/stat-summary.R index a32eda8ca0..d2113afffb 100644 --- a/R/stat-summary.R +++ b/R/stat-summary.R @@ -227,7 +227,7 @@ summarise_by_x <- function(data, summary, ...) { # # @keyword internal uniquecols <- function(df) { - df <- df[1, sapply(df, is_unique), drop = FALSE] + df <- df[1, vapply(df, is_unique, logical(1)), drop = FALSE] attr(df, "row.names") <- .set_row_names(nrow(df)) df } diff --git a/R/stat-ydensity.R b/R/stat-ydensity.R index 4eadd8ca58..211325880e 100644 --- a/R/stat-ydensity.R +++ b/R/stat-ydensity.R @@ -79,8 +79,8 @@ StatYdensity <- ggproto("StatYdensity", Stat, extra_params = c("na.rm", "orientation"), compute_group = function(self, data, scales, width = NULL, bw = "nrd0", adjust = 1, - kernel = "gaussian", trim = TRUE, na.rm = FALSE, - drop = TRUE, flipped_aes = FALSE, bounds = c(-Inf, Inf)) { + kernel = "gaussian", trim = TRUE, na.rm = FALSE, + drop = TRUE, flipped_aes = FALSE, bounds = c(-Inf, Inf)) { if (nrow(data) < 2) { if (isTRUE(drop)) { cli::cli_warn(c( @@ -88,7 +88,8 @@ StatYdensity <- ggproto("StatYdensity", Stat, i = paste0( "Set {.code drop = FALSE} to consider such groups for position ", "adjustment purposes." - ))) + ) + )) return(data_frame0()) } ans <- data_frame0(x = data$x, n = nrow(data)) @@ -125,7 +126,7 @@ StatYdensity <- ggproto("StatYdensity", Stat, data <- flip_data(data, flipped_aes) data <- ggproto_parent(Stat, self)$compute_panel( data, scales, width = width, bw = bw, adjust = adjust, kernel = kernel, - trim = trim, na.rm = na.rm, drop = drop, bounds = bounds, + trim = trim, na.rm = na.rm, drop = drop, bounds = bounds ) if (!drop && any(data$n < 2)) { cli::cli_warn( diff --git a/R/summary.R b/R/summary.R index 4a227a3599..1a89866d46 100644 --- a/R/summary.R +++ b/R/summary.R @@ -10,16 +10,15 @@ #' geom_point() #' summary(p) summary.ggplot <- function(object, ...) { - wrap <- function(x) paste( - paste(strwrap(x, exdent = 2), collapse = "\n"), - "\n", sep = "" - ) + wrap <- function(x) { + paste0(paste(strwrap(x, exdent = 2), collapse = "\n"), "\n") + } if (!is.null(object$data)) { - output <- paste( + output <- paste0( "data: ", paste(names(object$data), collapse = ", "), - " [", nrow(object$data), "x", ncol(object$data), "] ", - "\n", sep = "") + " [", nrow(object$data), "x", ncol(object$data), "]\n" + ) cat(wrap(output)) } if (length(object$mapping) > 0) { diff --git a/R/theme-current.R b/R/theme-current.R index ac24ec4724..3c1ad58e99 100644 --- a/R/theme-current.R +++ b/R/theme-current.R @@ -126,7 +126,7 @@ theme_replace <- replace_theme #' @rdname get_theme #' @export -"%+replace%" <- function(e1, e2) { +`%+replace%` <- function(e1, e2) { if (!is.theme(e1) || !is.theme(e2)) { cli::cli_abort("{.code %+replace%} requires two theme objects") } @@ -141,4 +141,3 @@ theme_replace <- replace_theme e1 } - diff --git a/R/theme-defaults.R b/R/theme-defaults.R index 8be7999d4d..9486183fde 100644 --- a/R/theme-defaults.R +++ b/R/theme-defaults.R @@ -258,7 +258,7 @@ theme_grey <- function(base_size = 11, base_family = "", size = rel(1.2), hjust = 0.5, vjust = 0.5 ), - plot.tag.position = 'topleft', + plot.tag.position = "topleft", plot.margin = NULL, complete = TRUE @@ -566,7 +566,7 @@ theme_void <- function(base_size = 11, base_family = "", size = rel(1.2), hjust = 0.5, vjust = 0.5 ), - plot.tag.position = 'topleft', + plot.tag.position = "topleft", complete = TRUE ) @@ -719,7 +719,7 @@ theme_test <- function(base_size = 11, base_family = "", size = rel(1.2), hjust = 0.5, vjust = 0.5 ), - plot.tag.position = 'topleft', + plot.tag.position = "topleft", plot.margin = NULL, complete = TRUE @@ -735,11 +735,8 @@ theme_all_null <- function() { # We read from `.element_tree` instead of `ggplot_global$element_tree` # because we don't want to change our results just because a user # has defined new theme elements. - elements <- sapply( - names(.element_tree), - function(x) NULL, - simplify = FALSE, USE.NAMES = TRUE - ) + elements <- rep(list(NULL), length.out = length(.element_tree)) + names(elements) <- names(.element_tree) args <- c(elements, list(complete = TRUE)) inject(theme(!!!args)) diff --git a/R/theme-elements.R b/R/theme-elements.R index 7e5de2f777..8e2030f7cb 100644 --- a/R/theme-elements.R +++ b/R/theme-elements.R @@ -72,8 +72,9 @@ element_blank <- function() { #' @export #' @rdname element -element_rect <- function(fill = NULL, colour = NULL, linewidth = NULL, - linetype = NULL, color = NULL, inherit.blank = FALSE, size = deprecated()) { +element_rect <- function( + fill = NULL, colour = NULL, linewidth = NULL, + linetype = NULL, color = NULL, inherit.blank = FALSE, size = deprecated()) { if (lifecycle::is_present(size)) { deprecate_soft0("3.4.0", "element_rect(size)", "element_rect(linewidth)") @@ -96,9 +97,10 @@ element_rect <- function(fill = NULL, colour = NULL, linewidth = NULL, #' digits which give the lengths in consecutive positions in the string. #' @param lineend Line end Line end style (round, butt, square) #' @param arrow Arrow specification, as created by [grid::arrow()] -element_line <- function(colour = NULL, linewidth = NULL, linetype = NULL, - lineend = NULL, color = NULL, arrow = NULL, arrow.fill = NULL, - inherit.blank = FALSE, size = deprecated()) { +element_line <- function( + colour = NULL, linewidth = NULL, linetype = NULL, + lineend = NULL, color = NULL, arrow = NULL, arrow.fill = NULL, + inherit.blank = FALSE, size = deprecated()) { if (lifecycle::is_present(size)) { deprecate_soft0("3.4.0", "element_line(size)", "element_line(linewidth)") @@ -110,8 +112,10 @@ element_line <- function(colour = NULL, linewidth = NULL, linetype = NULL, arrow <- arrow %||% FALSE structure( - list(colour = colour, linewidth = linewidth, linetype = linetype, lineend = lineend, - arrow = arrow, arrow.fill = arrow.fill, inherit.blank = inherit.blank), + list( + colour = colour, linewidth = linewidth, linetype = linetype, lineend = lineend, + arrow = arrow, arrow.fill = arrow.fill, inherit.blank = inherit.blank + ), class = c("element_line", "element") ) } @@ -131,9 +135,10 @@ element_line <- function(colour = NULL, linewidth = NULL, linetype = NULL, #' is anchored. #' @export #' @rdname element -element_text <- function(family = NULL, face = NULL, colour = NULL, - size = NULL, hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL, - color = NULL, margin = NULL, debug = NULL, inherit.blank = FALSE) { +element_text <- function( + family = NULL, face = NULL, colour = NULL, + size = NULL, hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL, + color = NULL, margin = NULL, debug = NULL, inherit.blank = FALSE) { if (!is.null(color)) colour <- color @@ -144,15 +149,17 @@ element_text <- function(family = NULL, face = NULL, colour = NULL, if (n > 1) { cli::cli_warn(c( "Vectorized input to {.fn element_text} is not officially supported.", - "i" = "Results may be unexpected or may change in future versions of ggplot2." + i = "Results may be unexpected or may change in future versions of ggplot2." )) } structure( - list(family = family, face = face, colour = colour, size = size, + list( + family = family, face = face, colour = colour, size = size, hjust = hjust, vjust = vjust, angle = angle, lineheight = lineheight, - margin = margin, debug = debug, inherit.blank = inherit.blank), + margin = margin, debug = debug, inherit.blank = inherit.blank + ), class = c("element_text", "element") ) } @@ -166,15 +173,15 @@ element_text <- function(family = NULL, face = NULL, colour = NULL, #' @rdname element element_geom <- function( # colours - ink = NULL, paper = NULL, accent = NULL, - # linewidth - linewidth = NULL, borderwidth = NULL, - # linetype - linetype = NULL, bordertype = NULL, - # text - family = NULL, fontsize = NULL, - # points - pointsize = NULL, pointshape = NULL) { + ink = NULL, paper = NULL, accent = NULL, + # linewidth + linewidth = NULL, borderwidth = NULL, + # linetype + linetype = NULL, bordertype = NULL, + # text + family = NULL, fontsize = NULL, + # points + pointsize = NULL, pointshape = NULL) { if (!is.null(fontsize)) { fontsize <- fontsize / .pt @@ -218,7 +225,7 @@ rel <- function(x) { } #' @export -print.rel <- function(x, ...) print(noquote(paste(x, " *", sep = ""))) +print.rel <- function(x, ...) print(noquote(paste0(x, " *"))) #' Reports whether x is a rel object #' @param x An object to test @@ -263,9 +270,10 @@ element_grob <- function(element, ...) { element_grob.element_blank <- function(element, ...) zeroGrob() #' @export -element_grob.element_rect <- function(element, x = 0.5, y = 0.5, - width = 1, height = 1, - fill = NULL, colour = NULL, linewidth = NULL, linetype = NULL, ..., size = deprecated()) { +element_grob.element_rect <- function( + element, x = 0.5, y = 0.5, width = 1, height = 1, + fill = NULL, colour = NULL, linewidth = NULL, linetype = NULL, ..., + size = deprecated()) { if (lifecycle::is_present(size)) { deprecate_soft0("3.4.0", "element_grob.element_rect(size)", "element_grob.element_rect(linewidth)") @@ -274,18 +282,21 @@ element_grob.element_rect <- function(element, x = 0.5, y = 0.5, # The gp settings can override element_gp gp <- gg_par(lwd = linewidth, col = colour, fill = fill, lty = linetype) - element_gp <- gg_par(lwd = element$linewidth, col = element$colour, - fill = element$fill, lty = element$linetype) + element_gp <- gg_par( + lwd = element$linewidth, col = element$colour, + fill = element$fill, lty = element$linetype + ) rectGrob(x, y, width, height, gp = modify_list(element_gp, gp), ...) } #' @export -element_grob.element_text <- function(element, label = "", x = NULL, y = NULL, - family = NULL, face = NULL, colour = NULL, size = NULL, - hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL, - margin = NULL, margin_x = FALSE, margin_y = FALSE, ...) { +element_grob.element_text <- function( + element, label = "", x = NULL, y = NULL, + family = NULL, face = NULL, colour = NULL, size = NULL, + hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL, + margin = NULL, margin_x = FALSE, margin_y = FALSE, ...) { if (is.null(label)) return(zeroGrob()) @@ -297,25 +308,32 @@ element_grob.element_text <- function(element, label = "", x = NULL, y = NULL, angle <- angle %||% element$angle %||% 0 # The gp settings can override element_gp - gp <- gg_par(fontsize = size, col = colour, + gp <- gg_par( + fontsize = size, col = colour, fontfamily = family, fontface = face, - lineheight = lineheight) - element_gp <- gg_par(fontsize = element$size, col = element$colour, + lineheight = lineheight + ) + element_gp <- gg_par( + fontsize = element$size, col = element$colour, fontfamily = element$family, fontface = element$face, - lineheight = element$lineheight) + lineheight = element$lineheight + ) - titleGrob(label, x, y, hjust = hj, vjust = vj, angle = angle, + titleGrob( + label, x, y, hjust = hj, vjust = vj, angle = angle, gp = modify_list(element_gp, gp), margin = margin, - margin_x = margin_x, margin_y = margin_y, debug = element$debug, ...) + margin_x = margin_x, margin_y = margin_y, debug = element$debug, ... + ) } #' @export -element_grob.element_line <- function(element, x = 0:1, y = 0:1, - colour = NULL, linewidth = NULL, linetype = NULL, lineend = NULL, - arrow.fill = NULL, - default.units = "npc", id.lengths = NULL, ..., size = deprecated()) { +element_grob.element_line <- function( + element, x = 0:1, y = 0:1, + colour = NULL, linewidth = NULL, linetype = NULL, lineend = NULL, + arrow.fill = NULL, + default.units = "npc", id.lengths = NULL, ..., size = deprecated()) { if (lifecycle::is_present(size)) { deprecate_soft0("3.4.0", "element_grob.element_line(size)", "element_grob.element_line(linewidth)") @@ -568,7 +586,7 @@ el_def <- function(class = NULL, inherit = NULL, description = NULL) { c("unit", "rel"), c("axis.minor.ticks.length.y", "axis.ticks.length.y.right") ), axis.minor.ticks.length.theta = el_def( - c("unit", "rel"), c("axis.minor.ticks.length.x", "axis.ticks.length.theta"), + c("unit", "rel"), c("axis.minor.ticks.length.x", "axis.ticks.length.theta") ), axis.minor.ticks.length.r = el_def( c("unit", "rel"), c("axis.minor.ticks.length.y", "axis.ticks.length.r") diff --git a/R/theme.R b/R/theme.R index 2eedd300c5..9fc891cac8 100644 --- a/R/theme.R +++ b/R/theme.R @@ -486,7 +486,7 @@ theme <- function(..., if (is.unit(elements$legend.margin) && !is.margin(elements$legend.margin)) { cli::cli_warn(c( "{.var legend.margin} must be specified using {.fn margin}", - "i" = "For the old behavior use {.var legend.spacing}" + i = "For the old behavior use {.var legend.spacing}" )) elements$legend.spacing <- elements$legend.margin elements$legend.margin <- margin() @@ -560,7 +560,7 @@ validate_theme <- function(theme, tree = get_element_tree(), call = caller_env() if (!is_theme_validate(theme)) { return() } - mapply( + Map( validate_element, theme, names(theme), MoreArgs = list(element_tree = tree, call = call) ) @@ -899,7 +899,7 @@ combine_elements <- function(e1, e2) { # If e2 is 'richer' than e1, fill e2 with e1 parameters is_subclass <- !any(inherits(e2, class(e1), which = TRUE) == 0) - is_subclass <- is_subclass && length(setdiff(class(e2), class(e1)) > 0) + is_subclass <- is_subclass && length(setdiff(class(e2), class(e1))) > 0 if (is_subclass) { new <- defaults(e1, e2) e2[names(new)] <- new diff --git a/R/utilities-break.R b/R/utilities-break.R index 11bc22019d..7beee44100 100644 --- a/R/utilities-break.R +++ b/R/utilities-break.R @@ -36,7 +36,7 @@ cut_number <- function(x, n = NULL, ...) { brk <- breaks(x, "numbers", n) if (anyDuplicated(brk)) cli::cli_abort("Insufficient data values to produce {n} bins.") - cut(x, brk , include.lowest = TRUE, ...) + cut(x, brk, include.lowest = TRUE, ...) } #' @export @@ -112,4 +112,3 @@ breaks <- function(x, equal, nbins = NULL, binwidth = NULL) { } } - diff --git a/R/utilities-checks.R b/R/utilities-checks.R index a1ed1b5091..138458b295 100644 --- a/R/utilities-checks.R +++ b/R/utilities-checks.R @@ -183,7 +183,7 @@ check_inherits <- function(x, #' # Possibly throw an error #' try(check_device("glyphs", action = "abort")) check_device <- function(feature, action = "warn", op = NULL, maybe = FALSE, - call = caller_env()) { + call = caller_env()) { check_bool(maybe, allow_na = TRUE) @@ -229,10 +229,10 @@ check_device <- function(feature, action = "warn", op = NULL, maybe = FALSE, capable <- switch( feature, glyphs = version >= "4.3.0", - paths =, transformations =, compositing =, - patterns =, lumi_masks =, blending =, + paths = , transformations = , compositing = , + patterns = , lumi_masks = , blending = , gradients = version >= "4.2.0", - alpha_masks =, + alpha_masks = , clippingPaths = version >= "4.1.0", TRUE ) @@ -270,7 +270,7 @@ check_device <- function(feature, action = "warn", op = NULL, maybe = FALSE, if (!is.null(op) && feature %in% c("blending", "compositing")) { op <- arg_match0(op, c(.blend_ops, .compo_ops)) .blend_ops <- .compo_ops <- op - feat_name <- paste0("'", gsub("\\.", " ", op), "' ", feat_name) + feat_name <- paste0("'", gsub(".", " ", op, fixed = TRUE), "' ", feat_name) } # The dev.capabilities() approach may work from R 4.2.0 onwards diff --git a/R/utilities-help.R b/R/utilities-help.R index 87f5419612..2f74b3644f 100644 --- a/R/utilities-help.R +++ b/R/utilities-help.R @@ -43,7 +43,7 @@ rd_match_docpage <- function(aes) { index <- match( flat, c( - "x", "y", "xmin", "xmax", "ymin", "ymax", "xend", 'yend', + "x", "y", "xmin", "xmax", "ymin", "ymax", "xend", "yend", "colour", "fill", "alpha", "group", "linetype", "size", "shape", "linewidth" @@ -67,14 +67,14 @@ rd_orientation <- function() { c( "@section Orientation: ", paste( - 'This geom treats each axis differently and, thus, can thus have two orientations.', - 'Often the orientation is easy to deduce from a combination of the given', - 'mappings and the types of positional scales in use. Thus, ggplot2 will by', - 'default try to guess which orientation the layer should have. Under rare', - 'circumstances, the orientation is ambiguous and guessing may fail. In that', - 'case the orientation can be specified directly using the \\code{orientation} parameter,', - 'which can be either \\code{"x"} or \\code{"y"}. The value gives the axis that the geom', - 'should run along, \\code{"x"} being the default orientation you would expect for the geom.' + "This geom treats each axis differently and, thus, can thus have two orientations.", + "Often the orientation is easy to deduce from a combination of the given", + "mappings and the types of positional scales in use. Thus, ggplot2 will by", + "default try to guess which orientation the layer should have. Under rare", + "circumstances, the orientation is ambiguous and guessing may fail. In that", + "case the orientation can be specified directly using the \\code{orientation} parameter,", + "which can be either \\code{\"x\"} or \\code{\"y\"}. The value gives the axis that the geom", + "should run along, \\code{\"x\"} being the default orientation you would expect for the geom." ) ) } @@ -118,7 +118,7 @@ rd_computed_vars <- function(..., .details = "", .skip_intro = FALSE) { "with [delayed evaluation][aes_eval]. " ) if (.skip_intro) intro <- "" - preamble <- c(header, paste0(intro, gsub("\n", "", .details))) + preamble <- c(header, paste0(intro, gsub("\n", "", .details, fixed = TRUE))) # Format items fmt_items <- gsub(",", ")`, `after_stat(", items, fixed = TRUE) @@ -127,7 +127,7 @@ rd_computed_vars <- function(..., .details = "", .skip_intro = FALSE) { fmt_items <- paste0("* `after_stat(", fmt_items, ")`") # Compose item-list - fmt_descr <- gsub("\n", "", descr) + fmt_descr <- gsub("\n", "", descr, fixed = TRUE) fmt_list <- paste(fmt_items, fmt_descr, sep = "\\cr ") c(preamble, fmt_list) diff --git a/R/utilities-patterns.R b/R/utilities-patterns.R index e7cdd308bc..b4aa3b7287 100644 --- a/R/utilities-patterns.R +++ b/R/utilities-patterns.R @@ -112,4 +112,3 @@ pattern_alpha.GridTilingPattern <- function(x, alpha) { pattern_alpha.list <- function(x, alpha) { Map(pattern_alpha, x = x, alpha = alpha) } - diff --git a/R/utilities.R b/R/utilities.R index 8772ed771b..450ae0fbe6 100644 --- a/R/utilities.R +++ b/R/utilities.R @@ -7,11 +7,11 @@ #' geom_point(colour = alpha("blue", 0.5)) scales::alpha -"%||%" <- function(a, b) { +`%||%` <- function(a, b) { if (!is.null(a)) a else b } -"%|W|%" <- function(a, b) { +`%|W|%` <- function(a, b) { if (!is.waive(a)) a else b } @@ -81,7 +81,7 @@ check_required_aesthetics <- function(required, present, name, call = caller_env #X clist(list(a=1, b=2)) #X clist(par()[1:5]) clist <- function(l) { - paste(paste(names(l), l, sep = " = ", collapse = ", "), sep = "") + paste(names(l), l, sep = " = ", collapse = ", ") } #' Convenience function to remove missing values from a data.frame @@ -107,7 +107,7 @@ remove_missing <- function(df, na.rm = FALSE, vars = names(df), name = "", if (any(missing)) { df <- df[!missing, , drop = FALSE] if (!na.rm) { - if (name != "") name <- paste(" ({.fn ", name, "})", sep = "") + if (name != "") name <- paste0(" ({.fn ", name, "})") msg <- paste0( "Removed {sum(missing)} row{?s} containing ", if (finite) "non-finite" else "missing values or values", @@ -216,15 +216,15 @@ gg_dep <- function(version, msg) { # If current major number is greater than last-good major number, or if # current minor number is more than 1 greater than last-good minor number, # give error. - if (cv[[1,1]] > v[[1,1]] || cv[[1,2]] > v[[1,2]] + 1) { + if (cv[[1, 1]] > v[[1, 1]] || cv[[1, 2]] > v[[1, 2]] + 1) { cli::cli_abort(text) - # If minor number differs by one, give warning - } else if (cv[[1,2]] > v[[1,2]]) { + } else if (cv[[1, 2]] > v[[1, 2]]) { + # If minor number differs by one, give warning cli::cli_warn(text) - # If only subminor number is greater, give message - } else if (cv[[1,3]] > v[[1,3]]) { + } else if (cv[[1, 3]] > v[[1, 3]]) { + # If only subminor number is greater, give message cli::cli_inform(text) } @@ -670,7 +670,7 @@ with_ordered_restart <- function(expr, .call) { } } else if (is.factor(x) || is.factor(y)) { restart <- TRUE - lev <- c() + lev <- NULL if (is.factor(x)) { lev <- c(lev, levels(x)) } @@ -783,7 +783,7 @@ warn_dots_used <- function(env = caller_env(), call = caller_env()) { # Demote from error to warning error = function(cnd) { # cli uses \f as newlines, not \n - msg <- gsub("\n", "\f", cnd_message(cnd)) + msg <- gsub("\n", "\f", cnd_message(cnd), fixed = TRUE) cli::cli_warn(msg, call = call) } ) @@ -828,7 +828,7 @@ prompt_install <- function(pkg, reason = NULL) { } question <- "Would you like to install {cli::qty(pkg)}{?it/them}?" - cli::cli_bullets(c("!" = message, "i" = question)) + cli::cli_bullets(c("!" = message, i = question)) if (utils::menu(c("Yes", "No")) != 1) { return(FALSE) } diff --git a/R/zzz.R b/R/zzz.R index 398cb7d7b6..82435b5e45 100644 --- a/R/zzz.R +++ b/R/zzz.R @@ -35,7 +35,5 @@ on_load( } release_questions <- function() { - c( - "Have you built the book?" - ) + "Have you built the book?" } diff --git a/tests/testthat/helper-vdiffr.R b/tests/testthat/helper-vdiffr.R index 20823ba45c..2a6d9f54cd 100644 --- a/tests/testthat/helper-vdiffr.R +++ b/tests/testthat/helper-vdiffr.R @@ -2,7 +2,7 @@ # VDIFFR_RUN_TESTS is explicitly set to "true", which should be the case only on # a GitHub Actions CI runner with stable version of R. -if (requireNamespace("vdiffr", quietly = TRUE) && utils::packageVersion('testthat') >= '3.0.3') { +if (requireNamespace("vdiffr", quietly = TRUE) && utils::packageVersion("testthat") >= "3.0.3") { expect_doppelganger <- vdiffr::expect_doppelganger } else { # If vdiffr is not available and visual tests are explicitly required, raise error. diff --git a/tests/testthat/test-add.R b/tests/testthat/test-add.R index a860a55845..2b56bf3718 100644 --- a/tests/testthat/test-add.R +++ b/tests/testthat/test-add.R @@ -1,4 +1,4 @@ test_that("mapping class is preserved when adding uneval objects", { p <- ggplot(mtcars) + aes(wt, mpg) - expect_identical(class(p$mapping), "uneval") + expect_s3_class(p$mapping, "uneval") }) diff --git a/tests/testthat/test-aes-calculated.R b/tests/testthat/test-aes-calculated.R index b453af02f5..0ea34a4a9d 100644 --- a/tests/testthat/test-aes-calculated.R +++ b/tests/testthat/test-aes-calculated.R @@ -17,8 +17,8 @@ test_that("strip_dots remove dots around calculated aesthetics", { expect_identical(strip_dots(aes(..density..))$x, quo(density)) expect_identical(strip_dots(aes(mean(..density..)))$x, quo(mean(density))) expect_equal( - strip_dots(aes(sapply(..density.., function(x) mean(x)))$x), - quo(sapply(density, function(x) mean(x))) + strip_dots(aes(vapply(..density.., mean, numeric(1)))$x), + quo(vapply(density, mean, numeric(1))) ) }) @@ -52,7 +52,7 @@ test_that("make_labels() deparses mappings properly", { test_that("staged aesthetics warn appropriately for duplicated names", { # Test should *not* report `NA` as the duplicated aes (#4707) - df <- data.frame(x = 1, y = 1, lab = "test") + df <- data_frame0(x = 1, y = 1, lab = "test") # One warning in plot code due to evaluation of `aes()` expect_snapshot_warning( @@ -94,8 +94,8 @@ test_that("calculated aesthetics throw warnings when lengths mismatch", { test_that("A deprecated warning is issued when stat(var) or ..var.. is used", { p1 <- ggplot(NULL, aes(stat(foo))) - expect_snapshot_warning(b1 <- ggplot_build(p1)) + expect_snapshot_warning(ggplot_build(p1)) p2 <- ggplot(NULL, aes(..bar..)) - expect_snapshot_warning(b2 <- ggplot_build(p2)) + expect_snapshot_warning(ggplot_build(p2)) }) diff --git a/tests/testthat/test-aes.R b/tests/testthat/test-aes.R index 1cb333fcac..e3db7c9f4d 100644 --- a/tests/testthat/test-aes.R +++ b/tests/testthat/test-aes.R @@ -188,7 +188,7 @@ test_that("aes() supports `!!!` in named arguments (#2675)", { }) test_that("alternative_aes_extract_usage() can inspect the call", { - x <- quote(test[['var']]) + x <- quote(test[["var"]]) expect_identical(alternative_aes_extract_usage(x), ".data[[\"var\"]]") x <- quote(test$var) expect_identical(alternative_aes_extract_usage(x), "var") diff --git a/tests/testthat/test-annotate.R b/tests/testthat/test-annotate.R index 129b5b6720..9074219bc6 100644 --- a/tests/testthat/test-annotate.R +++ b/tests/testthat/test-annotate.R @@ -1,8 +1,8 @@ test_that("dates in segment annotation work", { - dt <- structure(list(month = structure(c(1364774400, 1377993600), - class = c("POSIXct", "POSIXt"), tzone = "UTC"), total = c(-10.3, - 11.7)), .Names = c("month", "total"), row.names = c(NA, -2L), class = - "data.frame") + dt <- structure(list( + month = structure(c(1364774400, 1377993600), class = c("POSIXct", "POSIXt"), tzone = "UTC"), + total = c(-10.3, 11.7) + ), .Names = c("month", "total"), row.names = c(NA, -2L), class = "data.frame") p <- ggplot(dt, aes(month, total)) + geom_point() + @@ -74,7 +74,7 @@ test_that("unsupported geoms signal a warning (#4719)", { }) test_that("annotate() checks aesthetic lengths match", { - expect_snapshot_error(annotate("point", 1:3, 1:3, fill = c('red', 'black'))) + expect_snapshot_error(annotate("point", 1:3, 1:3, fill = c("red", "black"))) }) test_that("annotation_logticks warns about deprecated `size` argument", { diff --git a/tests/testthat/test-coord-.R b/tests/testthat/test-coord-.R index f1e910c807..931de27e9a 100644 --- a/tests/testthat/test-coord-.R +++ b/tests/testthat/test-coord-.R @@ -44,10 +44,10 @@ test_that("check coord limits errors only on bad inputs", { # Should return NULL if valid values are passed expect_null(check_coord_limits(NULL)) expect_null(check_coord_limits(1:2)) - expect_null(check_coord_limits(c(1,2))) + expect_null(check_coord_limits(c(1, 2))) # Should raise error if Scale object is passed - expect_error(check_coord_limits(xlim(1,2))) + expect_error(check_coord_limits(xlim(1, 2))) # Should raise error if vector of wrong length is passed expect_error(check_coord_limits(1:3)) @@ -107,4 +107,3 @@ test_that("coord expand takes a vector", { expect_equal(pp$y.range, c(-0.5, 10)) }) - diff --git a/tests/testthat/test-coord-cartesian.R b/tests/testthat/test-coord-cartesian.R index 23bed331ae..9cb0677db0 100644 --- a/tests/testthat/test-coord-cartesian.R +++ b/tests/testthat/test-coord-cartesian.R @@ -16,10 +16,10 @@ test_that("clipping can be turned off and on", { test_that("cartesian coords throws error when limits are badly specified", { # throws error when limit is a Scale object instead of vector - expect_snapshot_error(ggplot() + coord_cartesian(xlim(1,1))) + expect_snapshot_error(ggplot() + coord_cartesian(xlim(1, 1))) # throws error when limit's length is different than two - expect_snapshot_error(ggplot() + coord_cartesian(ylim=1:3)) + expect_snapshot_error(ggplot() + coord_cartesian(ylim = 1:3)) }) diff --git a/tests/testthat/test-coord-flip.R b/tests/testthat/test-coord-flip.R index 0a346ebb24..15dd00ef2c 100644 --- a/tests/testthat/test-coord-flip.R +++ b/tests/testthat/test-coord-flip.R @@ -10,8 +10,8 @@ test_that("secondary labels are correctly turned off", { test_that("flip coords throws error when limits are badly specified", { # throws error when limit is a Scale object instead of vector - expect_snapshot_error(ggplot() + coord_flip(xlim(1,1))) + expect_snapshot_error(ggplot() + coord_flip(xlim(1, 1))) # throws error when limit's length is different than two - expect_snapshot_error(ggplot() + coord_flip(ylim=1:3)) + expect_snapshot_error(ggplot() + coord_flip(ylim = 1:3)) }) diff --git a/tests/testthat/test-coord-map.R b/tests/testthat/test-coord-map.R index cc4a1b0f3a..23e66e79d0 100644 --- a/tests/testthat/test-coord-map.R +++ b/tests/testthat/test-coord-map.R @@ -34,7 +34,7 @@ test_that("Inf is squished to range", { skip_if(packageVersion("base") < "3.5.0") d <- cdata( ggplot(data_frame(x = 0, y = 0)) + - geom_point(aes(x,y)) + + geom_point(aes(x, y)) + annotate("text", -Inf, Inf, label = "Top-left") + coord_map() ) @@ -45,14 +45,14 @@ test_that("Inf is squished to range", { test_that("coord map throws error when limits are badly specified", { # throws error when limit is a Scale object instead of vector - expect_snapshot_error(ggplot() + coord_map(xlim=xlim(1,1))) + expect_snapshot_error(ggplot() + coord_map(xlim = xlim(1, 1))) # throws error when limit's length is different than two - expect_snapshot_error(ggplot() + coord_cartesian(ylim=1:3)) + expect_snapshot_error(ggplot() + coord_cartesian(ylim = 1:3)) }) test_that("coord_map throws informative warning about guides", { expect_snapshot_warning( - ggplot_build(ggplot() + coord_map() + guides(x = guide_axis())) + ggplot_build(ggplot() + coord_map() + guides(x = guide_axis())) ) }) diff --git a/tests/testthat/test-coord-polar.R b/tests/testthat/test-coord-polar.R index da49368108..a00035415c 100644 --- a/tests/testthat/test-coord-polar.R +++ b/tests/testthat/test-coord-polar.R @@ -1,10 +1,11 @@ test_that("polar distance is calculated correctly", { dat <- data_frame( - theta = c(0, 2*pi, 2, 6, 6, 1, 1, 0), - r = c(0, 0, 0.5, 0.5, 1, 1, 0.75, 0.5)) + theta = c(0, 2 * pi, 2, 6, 6, 1, 1, 0), + r = c(0, 0, 0.5, 0.5, 1, 1, 0.75, 0.5) + ) scales <- list( - x = scale_x_continuous(limits = c(0, 2*pi)), + x = scale_x_continuous(limits = c(0, 2 * pi)), y = scale_y_continuous(limits = c(0, 1)) ) coord <- coord_polar() @@ -16,8 +17,10 @@ test_that("polar distance is calculated correctly", { maxlen <- spiral_arc_length(1 / (2 * pi), 0, 2 * pi) # These are the expected lengths. I think they're correct... - expect_equal(dists, - c(0, -1.225737494, -2, -0.5, -5, -0.25, -0.6736885011) / maxlen) + expect_equal( + dists, + c(0, -1.225737494, -2, -0.5, -5, -0.25, -0.6736885011) / maxlen + ) # The picture can be visualized with: # ggplot(dat, aes(x=theta, y=r)) + geom_path() + @@ -178,8 +181,8 @@ test_that("polar coordinates draw correctly", { ) dat <- data_frame( - theta = c(0, 2*pi, 2, 6, 6, 1, 1, 0), - r = c(0, 0, 0.5, 0.5, 1, 1, 0.75, 0.5), + theta = c(0, 2 * pi, 2, 6, 6, 1, 1, 0), + r = c(0, 0, 0.5, 0.5, 1, 1, 0.75, 0.5), g = 1:8 ) expect_doppelganger("Rays, circular arcs, and spiral arcs", @@ -225,7 +228,7 @@ test_that("coord_radial() draws correctly", { # Theme to test for axis placement theme <- theme( axis.line.theta = element_line(colour = "tomato"), - axis.line.r = element_line(colour = "dodgerblue"), + axis.line.r = element_line(colour = "dodgerblue") ) sec_guides <- guides( diff --git a/tests/testthat/test-coord-transform.R b/tests/testthat/test-coord-transform.R index abb05a3cae..436a5efa64 100644 --- a/tests/testthat/test-coord-transform.R +++ b/tests/testthat/test-coord-transform.R @@ -18,7 +18,7 @@ test_that("warnings are generated when coord_trans() results in new infinite val test_that("no warnings are generated when original data has Inf values, but no new Inf values created from the transformation", { p <- ggplot(data_frame(x = c(-Inf, 2, 0), y = c(Inf, 6, 4)), aes(x, y)) + geom_point() + - coord_trans(x = 'identity') + coord_trans(x = "identity") expect_silent(benchplot(p)) }) @@ -126,8 +126,8 @@ test_that("second axes display in coord_trans()", { test_that("coord_trans() throws error when limits are badly specified", { # throws error when limit is a Scale object instead of vector - expect_snapshot_error(ggplot() + coord_trans(xlim=xlim(1,1))) + expect_snapshot_error(ggplot() + coord_trans(xlim = xlim(1, 1))) # throws error when limit's length is different than two - expect_snapshot_error(ggplot() + coord_trans(ylim=1:3)) + expect_snapshot_error(ggplot() + coord_trans(ylim = 1:3)) }) diff --git a/tests/testthat/test-coord_sf.R b/tests/testthat/test-coord_sf.R index 12a667be5b..be2dace655 100644 --- a/tests/testthat/test-coord_sf.R +++ b/tests/testthat/test-coord_sf.R @@ -47,7 +47,7 @@ test_that("graticule lines and axes can be removed via scales", { test_that("axis labels are correct for manual breaks", { skip_if_not_installed("sf") - plot <- ggplot(sf::st_polygon(list(matrix(1e3*c(1, 2, 3, 1, 1, 3, 2, 1), ncol = 2)))) + + plot <- ggplot(sf::st_polygon(list(matrix(1e3 * c(1, 2, 3, 1, 1, 3, 2, 1), ncol = 2)))) + geom_sf() # autogenerated labels @@ -70,7 +70,7 @@ test_that("axis labels are correct for manual breaks", { test_that("axis labels can be set manually", { skip_if_not_installed("sf") - plot <- ggplot(sf::st_polygon(list(matrix(1e3*c(1, 2, 3, 1, 1, 3, 2, 1), ncol = 2)))) + + plot <- ggplot(sf::st_polygon(list(matrix(1e3 * c(1, 2, 3, 1, 1, 3, 2, 1), ncol = 2)))) + geom_sf() # character labels @@ -114,7 +114,7 @@ test_that("axis labels can be set manually", { test_that("factors are treated like character labels and are not parsed", { skip_if_not_installed("sf") - plot <- ggplot(sf::st_polygon(list(matrix(1e3*c(1, 2, 3, 1, 1, 3, 2, 1), ncol = 2)))) + + plot <- ggplot(sf::st_polygon(list(matrix(1e3 * c(1, 2, 3, 1, 1, 3, 2, 1), ncol = 2)))) + geom_sf() b <- ggplot_build( @@ -142,7 +142,7 @@ test_that("factors are treated like character labels and are not parsed", { test_that("expressions can be mixed with character labels", { skip_if_not_installed("sf") - plot <- ggplot(sf::st_polygon(list(matrix(1e3*c(1, 2, 3, 1, 1, 3, 2, 1), ncol = 2)))) + + plot <- ggplot(sf::st_polygon(list(matrix(1e3 * c(1, 2, 3, 1, 1, 3, 2, 1), ncol = 2)))) + geom_sf() b <- ggplot_build( @@ -197,7 +197,7 @@ test_that("degree labels are automatically parsed", { skip_if_not_installed("sf") data <- sf::st_sfc( - sf::st_polygon(list(matrix(1e1*c(1, 2, 3, 1, 1, 3, 2, 1), ncol = 2))), + sf::st_polygon(list(matrix(1e1 * c(1, 2, 3, 1, 1, 3, 2, 1), ncol = 2))), crs = 4326 # basic long-lat crs ) plot <- ggplot(data) + geom_sf() @@ -366,8 +366,8 @@ test_that("coord_sf() uses the guide system", { test_that("coord_sf() throws error when limits are badly specified", { skip_if_not_installed("sf") # throws error when limit is a Scale object instead of vector - expect_snapshot_error(ggplot() + coord_sf(xlim(1,1))) + expect_snapshot_error(ggplot() + coord_sf(xlim(1, 1))) # throws error when limit's length is different than two - expect_snapshot_error(ggplot() + coord_sf(ylim=1:3)) + expect_snapshot_error(ggplot() + coord_sf(ylim = 1:3)) }) diff --git a/tests/testthat/test-draw-key.R b/tests/testthat/test-draw-key.R index 223bfd6d5c..6a0e1f2a1b 100644 --- a/tests/testthat/test-draw-key.R +++ b/tests/testthat/test-draw-key.R @@ -9,7 +9,7 @@ test_that("alternative key glyphs work", { geom_line(aes(color = "line"), key_glyph = "timeseries") + geom_point(aes(fill = z), pch = 21, size = 3, key_glyph = "polygon") + guides(fill = guide_legend(order = 1)) - ) + ) # specify key glyph by function expect_doppelganger("rectangle and dotplot key glyphs", @@ -39,14 +39,14 @@ test_that("keys can communicate their size", { # Orientation-aware key glyphs -------------------------------------------- test_that("horizontal key glyphs work", { - df <- data.frame( + df <- data_frame0( middle = 1:2, lower = 0:1, upper = 2:3, min = -1:0, max = 3:4, - group1 = c("a","b"), - group2 = c("c","d") + group1 = c("a", "b"), + group2 = c("c", "d") ) p <- ggplot(df, aes( @@ -104,11 +104,11 @@ test_that("keep_draw_key", { p <- ggplot(data.frame(x = 1:2), aes(x, x)) + geom_point( aes(colour = "point", alpha = "point"), - show.legend = c("colour" = NA, alpha = FALSE) + show.legend = c(colour = NA, alpha = FALSE) ) + geom_line( aes(colour = "line", alpha = "line"), - show.legend = c("colour" = NA, alpha = TRUE) + show.legend = c(colour = NA, alpha = TRUE) ) + suppressWarnings(scale_alpha_discrete()) diff --git a/tests/testthat/test-empty-data.R b/tests/testthat/test-empty-data.R index bdcc02003c..c7a9fb3c61 100644 --- a/tests/testthat/test-empty-data.R +++ b/tests/testthat/test-empty-data.R @@ -2,10 +2,10 @@ df0 <- data_frame(mpg = numeric(0), wt = numeric(0), am = numeric(0), cyl = nume test_that("layers with empty data are silently omitted", { # Empty data (no visible points) - d <- ggplot(df0, aes(mpg,wt)) + geom_point() + d <- ggplot(df0, aes(mpg, wt)) + geom_point() expect_equal(nrow(get_layer_data(d)), 0) - d <- ggplot() + geom_point(data = df0, aes(mpg,wt)) + d <- ggplot() + geom_point(data = df0, aes(mpg, wt)) expect_equal(nrow(get_layer_data(d)), 0) # Regular mtcars data, x=mpg, y=wt, normal points and points from empty data frame diff --git a/tests/testthat/test-facet-.R b/tests/testthat/test-facet-.R index 5084737622..a5bfac851d 100644 --- a/tests/testthat/test-facet-.R +++ b/tests/testthat/test-facet-.R @@ -6,7 +6,7 @@ test_that("as_facets_list() coerces formulas", { exp <- list(quos(foo = foo, bar = bar), quos(baz = baz, bam = bam)) expect_identical(as_facets_list(foo + bar ~ baz + bam), exp) - exp <- list(quos(`foo()`= foo(), `bar()` = bar()), quos(`baz()` = baz(), `bam()` = bam())) + exp <- list(quos(`foo()` = foo(), `bar()` = bar()), quos(`baz()` = baz(), `bam()` = bam())) expect_identical(as_facets_list(foo() + bar() ~ baz() + bam()), exp) }) @@ -186,20 +186,20 @@ test_that("facets with free scales scale independently", { # facet_wrap() l1 <- p + facet_wrap(~z, scales = "free") d1 <- cdata(l1)[[1]] - expect_true(sd(d1$x) < 1e-10) - expect_true(sd(d1$y) < 1e-10) + expect_lt(sd(d1$x), 1e-10) + expect_lt(sd(d1$y), 1e-10) # RHS of facet_grid() l2 <- p + facet_grid(. ~ z, scales = "free") d2 <- cdata(l2)[[1]] - expect_true(sd(d2$x) < 1e-10) + expect_lt(sd(d2$x), 1e-10) expect_length(unique(d2$y), 3) # LHS of facet_grid() l3 <- p + facet_grid(z ~ ., scales = "free") d3 <- cdata(l3)[[1]] expect_length(unique(d3$x), 3) - expect_true(sd(d3$y) < 1e-10) + expect_lt(sd(d3$y), 1e-10) }) test_that("shrink parameter affects scaling", { @@ -288,16 +288,16 @@ test_that("facet_grid `axes` can draw inner axes.", { ctrl <- ggplotGrob(p + facet_grid(vars(fy), vars(fx), axes = "margins")) # 4 x-axes if all axes should be drawn - bottom <- case$grobs[grepl("axis-b", case$layout$name)] + bottom <- case$grobs[grepl("axis-b", case$layout$name, fixed = TRUE)] expect_equal(sum(vapply(bottom, inherits, logical(1), "absoluteGrob")), 4) # 2 x-axes if drawing at the margins - bottom <- ctrl$grobs[grepl("axis-b", ctrl$layout$name)] + bottom <- ctrl$grobs[grepl("axis-b", ctrl$layout$name, fixed = TRUE)] expect_equal(sum(vapply(bottom, inherits, logical(1), "absoluteGrob")), 2) # Ditto for y-axes - left <- case$grobs[grepl("axis-l", case$layout$name)] + left <- case$grobs[grepl("axis-l", case$layout$name, fixed = TRUE)] expect_equal(sum(vapply(left, inherits, logical(1), "absoluteGrob")), 4) - left <- ctrl$grobs[grepl("axis-l", ctrl$layout$name)] + left <- ctrl$grobs[grepl("axis-l", ctrl$layout$name, fixed = TRUE)] expect_equal(sum(vapply(left, inherits, logical(1), "absoluteGrob")), 2) }) @@ -312,16 +312,16 @@ test_that("facet_wrap `axes` can draw inner axes.", { ctrl <- ggplotGrob(p + facet_wrap(vars(facet), axes = "margins")) # 4 x-axes if all axes should be drawn - bottom <- case$grobs[grepl("axis-b", case$layout$name)] + bottom <- case$grobs[grepl("axis-b", case$layout$name, fixed = TRUE)] expect_equal(sum(vapply(bottom, inherits, logical(1), "absoluteGrob")), 4) # 2 x-axes if drawing at the margins - bottom <- ctrl$grobs[grepl("axis-b", ctrl$layout$name)] + bottom <- ctrl$grobs[grepl("axis-b", ctrl$layout$name, fixed = TRUE)] expect_equal(sum(vapply(bottom, inherits, logical(1), "absoluteGrob")), 2) # Ditto for y-axes - left <- case$grobs[grepl("axis-l", case$layout$name)] + left <- case$grobs[grepl("axis-l", case$layout$name, fixed = TRUE)] expect_equal(sum(vapply(left, inherits, logical(1), "absoluteGrob")), 4) - left <- ctrl$grobs[grepl("axis-l", ctrl$layout$name)] + left <- ctrl$grobs[grepl("axis-l", ctrl$layout$name, fixed = TRUE)] expect_equal(sum(vapply(left, inherits, logical(1), "absoluteGrob")), 2) }) @@ -402,14 +402,14 @@ test_that("combine_vars() generates the correct combinations", { expect_snapshot_error( combine_vars( list(data.frame(a = 1:2, b = 2:3), data.frame(a = 1:2, c = 2:3)), - vars = vars(b=b, c=c) + vars = vars(b = b, c = c) ) ) expect_snapshot_error( combine_vars( list(data.frame(a = 1:2), data.frame(b = numeric())), - vars = vars(b=b) + vars = vars(b = b) ) ) }) @@ -449,22 +449,22 @@ test_that("combine_vars() generates the correct combinations with multiple data }) test_that("eval_facet() is tolerant for missing columns (#2963)", { - expect_null(eval_facet(quo(2 * x), data_frame(foo = 1), possible_columns = c("x"))) - expect_null(eval_facet(quo(2 * .data$x), data_frame(foo = 1), possible_columns = c("x"))) + expect_null(eval_facet(quo(2 * x), data_frame(foo = 1), possible_columns = "x")) + expect_null(eval_facet(quo(2 * .data$x), data_frame(foo = 1), possible_columns = "x")) # Even if there's the same name of external variable, eval_facet() returns NULL before # reaching to the variable bar <- 2 - expect_null(eval_facet(quo(2 * bar), data_frame(foo = 1), possible_columns = c("bar"))) + expect_null(eval_facet(quo(2 * bar), data_frame(foo = 1), possible_columns = "bar")) # If there's no same name of columns, the external variable is used expect_equal( - eval_facet(quo(2 * bar), data_frame(foo = 1), possible_columns = c("x")), + eval_facet(quo(2 * bar), data_frame(foo = 1), possible_columns = "x"), 4 ) # If the expression contains any non-existent variable, it fails expect_error( - eval_facet(quo(no_such_variable * x), data_frame(foo = 1), possible_columns = c("x")), + eval_facet(quo(no_such_variable * x), data_frame(foo = 1), possible_columns = "x"), "object 'no_such_variable' not found" ) }) diff --git a/tests/testthat/test-facet-labels.R b/tests/testthat/test-facet-labels.R index c8613bc978..c64fd6bb64 100644 --- a/tests/testthat/test-facet-labels.R +++ b/tests/testthat/test-facet-labels.R @@ -84,25 +84,29 @@ test_that("labeller() dispatches labellers", { expect_equal(get_labels_matrix(p2), expected_cyl_both) # facet_wrap() shouldn't get both rows and cols - p3 <- p + facet_wrap(~cyl, labeller = labeller( - .cols = label_both, .rows = label_both)) + p3 <- p + facet_wrap( + ~cyl, labeller = labeller(.cols = label_both, .rows = label_both) + ) expect_error(ggplotGrob(p3)) # facet_grid() can get both rows and cols - p4 <- p + facet_grid(am ~ cyl, labeller = labeller( - .cols = label_both, .rows = label_both)) + p4 <- p + facet_grid( + am ~ cyl, labeller = labeller(.cols = label_both, .rows = label_both) + ) expect_equal(get_labels_matrix(p4, "rows"), expected_am_both) expect_equal(get_labels_matrix(p4, "cols"), expected_cyl_both) # Cannot have a specific labeller for a variable which already has a # margin-wide labeller - p5 <- p + facet_wrap(~cyl, labeller = labeller( - .rows = label_both, cyl = label_value)) + p5 <- p + facet_wrap( + ~cyl, labeller = labeller(.rows = label_both, cyl = label_value) + ) expect_error(ggplotGrob(p5)) # Variables can be attributed labellers - p6 <- p + facet_grid(am + cyl ~ ., labeller = labeller( - am = label_both, cyl = label_both)) + p6 <- p + facet_grid( + am + cyl ~ ., labeller = labeller(am = label_both, cyl = label_both) + ) expect_equal( get_labels_matrix(p6, "rows"), cbind( @@ -135,10 +139,11 @@ test_that("old school labellers still work", { paste0("var = ", as.character(value)) } - expect_warning(p <- - ggplot(mtcars, aes(disp, drat)) + - geom_point() + - facet_grid(~cyl, labeller = my_labeller)) + expect_warning( + p <- ggplot(mtcars, aes(disp, drat)) + + geom_point() + + facet_grid(~cyl, labeller = my_labeller) + ) expected_labels <- cbind(paste("var =", c(4, 6, 8))) expect_identical(get_labels_matrix(p, "cols"), expected_labels) @@ -160,7 +165,7 @@ test_that("parsed labels are rendered correctly", { test_that("outside-justified labels are justified across panels", { - df <- data.frame( + df <- data_frame0( x = c("X\nX\nX\nX\nX", "X"), y = c("YYYYY", "Y"), f1 = c("A", "B"), diff --git a/tests/testthat/test-facet-layout.R b/tests/testthat/test-facet-layout.R index a008a0c80d..cec1a562e1 100644 --- a/tests/testthat/test-facet-layout.R +++ b/tests/testthat/test-facet-layout.R @@ -10,15 +10,15 @@ panel_layout <- function(facet, data) { } test_that("grid: single row and single col are equivalent", { - row <- panel_layout(facet_grid(a~.), list(a)) - col <- panel_layout(facet_grid(.~a), list(a)) + row <- panel_layout(facet_grid(a ~ .), list(a)) + col <- panel_layout(facet_grid(. ~ a), list(a)) expect_equal(row$ROW, 1:2) expect_equal(row$ROW, col$COL) expect_equal(row[c("PANEL", "a")], col[c("PANEL", "a")]) - row <- panel_layout(facet_grid(a~.), list(a, b)) - col <- panel_layout(facet_grid(.~a), list(a, b)) + row <- panel_layout(facet_grid(a ~ .), list(a, b)) + col <- panel_layout(facet_grid(. ~ a), list(a, b)) expect_equal(row$ROW, 1:3) expect_equal(row$ROW, col$COL) @@ -27,7 +27,7 @@ test_that("grid: single row and single col are equivalent", { test_that("grid: includes all combinations", { d <- data_frame(a = c(1, 2), b = c(2, 1)) - all <- panel_layout(facet_grid(a~b), list(d)) + all <- panel_layout(facet_grid(a ~ b), list(d)) expect_equal(nrow(all), 4) }) @@ -37,7 +37,7 @@ test_that("wrap: layout sorting is correct", { dummy <- list(data_frame0(x = 1:5)) test <- panel_layout(facet_wrap(~x, dir = "lt"), dummy) - expect_equal(test$ROW, rep(c(1,2), c(3, 2))) + expect_equal(test$ROW, rep(c(1, 2), c(3, 2))) expect_equal(test$COL, c(1:3, 1:2)) test <- panel_layout(facet_wrap(~x, dir = "tl"), dummy) @@ -71,17 +71,17 @@ test_that("wrap: layout sorting is correct", { }) test_that("wrap and grid are equivalent for 1d data", { - rowg <- panel_layout(facet_grid(a~.), list(a)) - roww <- panel_layout(facet_wrap(~a, ncol = 1), list(a)) + rowg <- panel_layout(facet_grid(a ~ .), list(a)) + roww <- panel_layout(facet_wrap(~ a, ncol = 1), list(a)) expect_equal(roww, rowg) - colg <- panel_layout(facet_grid(.~a), list(a)) - colw <- panel_layout(facet_wrap(~a, nrow = 1), list(a)) + colg <- panel_layout(facet_grid(. ~ a), list(a)) + colw <- panel_layout(facet_wrap(~ a, nrow = 1), list(a)) expect_equal(colw, colg) }) test_that("grid: crossed rows/cols create no more combinations than necessary", { - facet <- facet_grid(a~b) + facet <- facet_grid(a ~ b) one <- panel_layout(facet, list(a)) expect_equal(nrow(one), 4) @@ -100,13 +100,13 @@ test_that("grid: crossed rows/cols create no more combinations than necessary", }) test_that("grid: nested rows/cols create no more combinations than necessary", { - one <- panel_layout(facet_grid(drv+cyl~.), list(mpg)) + one <- panel_layout(facet_grid(drv + cyl ~ .), list(mpg)) expect_equal(one$PANEL, factor(1:9)) expect_equal(one$ROW, 1:9) }) test_that("grid: margins add correct combinations", { - one <- panel_layout(facet_grid(a~b, margins = TRUE), list(a)) + one <- panel_layout(facet_grid(a ~ b, margins = TRUE), list(a)) expect_equal(nrow(one), 4 + 2 + 2 + 1) }) @@ -127,10 +127,10 @@ test_that("wrap: as.table = FALSE gets axes", { }) test_that("grid: as.table reverses rows", { - one <- panel_layout(facet_grid(a~., as.table = FALSE), list(a)) + one <- panel_layout(facet_grid(a ~ ., as.table = FALSE), list(a)) expect_equal(as.character(one$a), c("2", "1")) - two <- panel_layout(facet_grid(a~., as.table = TRUE), list(a)) + two <- panel_layout(facet_grid(a ~ ., as.table = TRUE), list(a)) expect_equal(as.character(two$a), c("1", "2")) }) @@ -158,15 +158,15 @@ test_that("wrap: drop = FALSE preserves unused levels", { }) test_that("grid: drop = FALSE preserves unused levels", { - grid_a <- panel_layout(facet_grid(a~., drop = FALSE), list(a2)) + grid_a <- panel_layout(facet_grid(a ~ ., drop = FALSE), list(a2)) expect_equal(nrow(grid_a), 4) expect_equal(as.character(grid_a$a), as.character(1:4)) - grid_b <- panel_layout(facet_grid(b~., drop = FALSE), list(a2)) + grid_b <- panel_layout(facet_grid(b ~ ., drop = FALSE), list(a2)) expect_equal(nrow(grid_b), 4) expect_equal(as.character(grid_b$b), as.character(4:1)) - grid_ab <- panel_layout(facet_grid(a~b, drop = FALSE), list(a2)) + grid_ab <- panel_layout(facet_grid(a ~ b, drop = FALSE), list(a2)) expect_equal(nrow(grid_ab), 16) expect_equal(as.character(grid_ab$a), as.character(rep(1:4, each = 4))) expect_equal(as.character(grid_ab$b), as.character(rep(4:1, 4))) @@ -200,12 +200,12 @@ a3 <- data_frame( ) test_that("missing values get a panel", { - wrap_a <- panel_layout(facet_wrap(~a), list(a3)) - wrap_b <- panel_layout(facet_wrap(~b), list(a3)) - wrap_c <- panel_layout(facet_wrap(~c), list(a3)) - grid_a <- panel_layout(facet_grid(a~.), list(a3)) - grid_b <- panel_layout(facet_grid(b~.), list(a3)) - grid_c <- panel_layout(facet_grid(c~.), list(a3)) + wrap_a <- panel_layout(facet_wrap(~ a), list(a3)) + wrap_b <- panel_layout(facet_wrap(~ b), list(a3)) + wrap_c <- panel_layout(facet_wrap(~ c), list(a3)) + grid_a <- panel_layout(facet_grid(a ~ .), list(a3)) + grid_b <- panel_layout(facet_grid(b ~ .), list(a3)) + grid_c <- panel_layout(facet_grid(c ~ .), list(a3)) expect_equal(nrow(wrap_a), 4) expect_equal(nrow(wrap_b), 4) @@ -243,12 +243,12 @@ test_that("facet_wrap throws errors at bad layout specs", { test_that("facet_grid throws errors at bad layout specs", { p <- ggplot(mtcars) + geom_point(aes(mpg, disp)) + - facet_grid(.~gear, scales = "free") + + facet_grid(. ~ gear, scales = "free") + coord_fixed() expect_snapshot_error(ggplotGrob(p)) p <- ggplot(mtcars) + geom_point(aes(mpg, disp)) + - facet_grid(.~gear, space = "free") + + facet_grid(. ~ gear, space = "free") + theme(aspect.ratio = 1) expect_snapshot_error(ggplotGrob(p)) }) diff --git a/tests/testthat/test-facet-map.R b/tests/testthat/test-facet-map.R index de2bf20af2..5ae8f2b5ae 100644 --- a/tests/testthat/test-facet-map.R +++ b/tests/testthat/test-facet-map.R @@ -9,7 +9,7 @@ panel_map_one <- function(facet, data, plot_data = data) { } test_that("two col cases with no missings adds a single extra column", { - loc <- panel_map_one(facet_grid(cyl~vs), mtcars) + loc <- panel_map_one(facet_grid(cyl ~ vs), mtcars) expect_equal(nrow(loc), nrow(mtcars)) expect_equal(ncol(loc), ncol(mtcars) + 1) @@ -19,7 +19,7 @@ test_that("two col cases with no missings adds a single extra column", { }) test_that("margins add extra data", { - loc <- panel_map_one(facet_grid(a~b, margins = "b"), df) + loc <- panel_map_one(facet_grid(a ~ b, margins = "b"), df) expect_equal(nrow(loc), nrow(df) * 2) @@ -29,7 +29,7 @@ test_that("margins add extra data", { }) test_that("grid: missing facet columns are duplicated", { - facet <- facet_grid(a~b) + facet <- facet_grid(a ~ b) loc_a <- panel_map_one(facet, df_a, plot_data = df) expect_equal(nrow(loc_a), 4) @@ -45,7 +45,7 @@ test_that("grid: missing facet columns are duplicated", { }) test_that("wrap: missing facet columns are duplicated", { - facet <- facet_wrap(~a+b, ncol = 1) + facet <- facet_wrap(~ a + b, ncol = 1) loc_a <- panel_map_one(facet, df_a, plot_data = df) expect_equal(nrow(loc_a), 4) @@ -96,7 +96,7 @@ test_that("wrap and grid can facet by a POSIXct variable", { # Missing behaviour ---------------------------------------------------------- a3 <- data_frame( -# a = c(1:3, NA), Not currently supported + # a = c(1:3, NA), Not currently supported b = factor(c(1:3, NA)), c = factor(c(1:3, NA), exclude = NULL) ) @@ -112,11 +112,11 @@ test_that("wrap: missing values are located correctly", { }) test_that("grid: missing values are located correctly", { - facet <- facet_grid(b~.) + facet <- facet_grid(b ~ .) loc_b <- panel_map_one(facet, data_frame(b = NA), plot_data = a3) expect_equal(as.character(loc_b$PANEL), "4") - facet <- facet_grid(c~.) + facet <- facet_grid(c ~ .) loc_c <- panel_map_one(facet, data_frame(c = NA), plot_data = a3) expect_equal(as.character(loc_c$PANEL), "4") }) @@ -126,9 +126,11 @@ test_that("grid: missing values are located correctly", { get_layout <- function(p) ggplot_build(p)$layout$layout # Data with factor f with levels CBA -d <- data_frame(x = 1:9, y = 1:9, +d <- data_frame( + x = 1:9, y = 1:9, fx = factor(rep(letters[1:3], each = 3), levels = letters[3:1]), - fy = factor(rep(LETTERS[1:3], each = 3), levels = LETTERS[3:1])) + fy = factor(rep(LETTERS[1:3], each = 3), levels = LETTERS[3:1]) +) # Data with factor f with only level B d2 <- data_frame(x = 1:9, y = 2:10, fx = factor("a"), fy = factor("B")) @@ -139,55 +141,79 @@ test_that("grid: facet order follows default data frame order", { # CBA for rows 1:3 # cba for cols 1:3 lay <- get_layout(ggplot(d, aes(x, y)) + facet_grid(fy ~ fx) + geom_point()) - expect_equal(as.character(lay$fy), c("C","B","A")[lay$ROW]) - expect_equal(as.character(lay$fx), c("c","b","a")[lay$COL]) + expect_equal(as.character(lay$fy), c("C", "B", "A")[lay$ROW]) + expect_equal(as.character(lay$fx), c("c", "b", "a")[lay$COL]) # When adding d2, facets should still be in order: # CBA for rows 1:3 # cba for cols 1:3 - lay <- get_layout(ggplot(d, aes(x, y)) + facet_grid(fy ~ fx) + - geom_blank(data = d2) + geom_point()) - expect_equal(as.character(lay$fy), c("C","B","A")[lay$ROW]) - expect_equal(as.character(lay$fx), c("c","b","a")[lay$COL]) + lay <- get_layout( + ggplot(d, aes(x, y)) + + facet_grid(fy ~ fx) + + geom_blank(data = d2) + + geom_point() + ) + expect_equal(as.character(lay$fy), c("C", "B", "A")[lay$ROW]) + expect_equal(as.character(lay$fx), c("c", "b", "a")[lay$COL]) # With no default data: should search each layer in order # BCA for rows 1:3 # acb for cols 1:3 - lay <- get_layout(ggplot(mapping = aes(x, y)) + facet_grid(fy ~ fx) + - geom_blank(data = d2) + geom_point(data = d)) - expect_equal(as.character(lay$fy), c("B","C","A")[lay$ROW]) - expect_equal(as.character(lay$fx), c("a","c","b")[lay$COL]) + lay <- get_layout( + ggplot(mapping = aes(x, y)) + + facet_grid(fy ~ fx) + + geom_blank(data = d2) + + geom_point(data = d) + ) + expect_equal(as.character(lay$fy), c("B", "C", "A")[lay$ROW]) + expect_equal(as.character(lay$fx), c("a", "c", "b")[lay$COL]) # Same as previous, but different layer order. # CBA for rows 1:3 # cba for cols 1:3 - lay <- get_layout(ggplot(mapping = aes(x, y)) + facet_grid(fy ~ fx) + - geom_point(data = d) + geom_blank(data = d2)) - expect_equal(as.character(lay$fy), c("C","B","A")[lay$ROW]) - expect_equal(as.character(lay$fx), c("c","b","a")[lay$COL]) + lay <- get_layout( + ggplot(mapping = aes(x, y)) + + facet_grid(fy ~ fx) + + geom_point(data = d) + + geom_blank(data = d2) + ) + expect_equal(as.character(lay$fy), c("C", "B", "A")[lay$ROW]) + expect_equal(as.character(lay$fx), c("c", "b", "a")[lay$COL]) }) test_that("wrap: facet order follows default data frame order", { # Facets should be in order: # cba for panels 1:3 lay <- get_layout(ggplot(d, aes(x, y)) + facet_wrap(~fx) + geom_point()) - expect_equal(as.character(lay$fx), c("c","b","a")[lay$PANEL]) + expect_equal(as.character(lay$fx), c("c", "b", "a")[lay$PANEL]) # When adding d2, facets should still be in order: # cba for panels 1:3 - lay <- get_layout(ggplot(d, aes(x, y)) + facet_wrap(~fx) + - geom_blank(data = d2) + geom_point()) - expect_equal(as.character(lay$fx), c("c","b","a")[lay$PANEL]) + lay <- get_layout( + ggplot(d, aes(x, y)) + + facet_wrap(~fx) + + geom_blank(data = d2) + + geom_point() + ) + expect_equal(as.character(lay$fx), c("c", "b", "a")[lay$PANEL]) # With no default data: should search each layer in order # acb for panels 1:3 - lay <- get_layout(ggplot(mapping = aes(x, y)) + facet_wrap(~fx) + - geom_blank(data = d2) + geom_point(data = d)) - expect_equal(as.character(lay$fx), c("a","c","b")[lay$PANEL]) + lay <- get_layout( + ggplot(mapping = aes(x, y)) + + facet_wrap(~fx) + + geom_blank(data = d2) + + geom_point(data = d) + ) + expect_equal(as.character(lay$fx), c("a", "c", "b")[lay$PANEL]) # Same as previous, but different layer order. # cba for panels 1:3 - lay <- get_layout(ggplot(mapping = aes(x, y)) + facet_wrap(~fx) + - geom_point(data = d) + geom_blank(data = d2)) - expect_equal(as.character(lay$fx), c("c","b","a")[lay$PANEL]) + lay <- get_layout( + ggplot(mapping = aes(x, y)) + + facet_wrap(~fx) + + geom_point(data = d) + + geom_blank(data = d2) + ) + expect_equal(as.character(lay$fx), c("c", "b", "a")[lay$PANEL]) }) diff --git a/tests/testthat/test-facet-strips.R b/tests/testthat/test-facet-strips.R index d13f8d500c..75d02630f8 100644 --- a/tests/testthat/test-facet-strips.R +++ b/tests/testthat/test-facet-strips.R @@ -131,8 +131,8 @@ test_that("strips can be removed", { facet_wrap(~a) + theme(strip.background = element_blank(), strip.text = element_blank()) g_grobs <- ggplotGrob(g) - strip_grobs <- g_grobs$grobs[grepl('strip-', g_grobs$layout$name)] - expect_true(all(sapply(strip_grobs, inherits, 'zeroGrob'))) + strip_grobs <- g_grobs$grobs[grepl("strip-", g_grobs$layout$name, fixed = TRUE)] + expect_true(all(vapply(strip_grobs, inherits, "zeroGrob", FUN.VALUE = logical(1)))) }) test_that("padding is only added if axis is present", { @@ -226,4 +226,3 @@ test_that("strip labels can be accessed", { ) ) }) - diff --git a/tests/testthat/test-fortify.R b/tests/testthat/test-fortify.R index 3a48c76ba0..8977a30563 100644 --- a/tests/testthat/test-fortify.R +++ b/tests/testthat/test-fortify.R @@ -4,26 +4,28 @@ test_that("spatial polygons have correct ordering", { }) - make_square <- function(x = 0, y = 0, height = 1, width = 1){ - delx <- width/2 - dely <- height/2 - sp::Polygon(matrix(c(x + delx, x - delx,x - delx,x + delx,x + delx , - y - dely,y - dely,y + dely,y + dely,y - dely), ncol = 2)) + make_square <- function(x = 0, y = 0, height = 1, width = 1) { + delx <- width / 2 + dely <- height / 2 + sp::Polygon(matrix(c( + x + delx, x - delx, x - delx, x + delx, x + delx, + y - dely, y - dely, y + dely, y + dely, y - dely + ), ncol = 2)) } - make_hole <- function(x = 0, y = 0, height = 0.5, width = 0.5){ + make_hole <- function(x = 0, y = 0, height = 0.5, width = 0.5) { p <- make_square(x = x, y = y, height = height, width = width) p@hole <- TRUE p } - fake_data <- data_frame(ids = 1:5, region = c(1,1,2,3,4)) + fake_data <- data_frame(ids = 1:5, region = c(1, 1, 2, 3, 4)) rownames(fake_data) <- 1:5 polys <- list(sp::Polygons(list(make_square(), make_hole()), 1), - sp::Polygons(list(make_square(1,0), make_square(2, 0)), 2), - sp::Polygons(list(make_square(1,1)), 3), - sp::Polygons(list(make_square(0,1)), 4), - sp::Polygons(list(make_square(0,3)), 5)) + sp::Polygons(list(make_square(1, 0), make_square(2, 0)), 2), + sp::Polygons(list(make_square(1, 1)), 3), + sp::Polygons(list(make_square(0, 1)), 4), + sp::Polygons(list(make_square(0, 3)), 5)) polys_sp <- sp::SpatialPolygons(polys) fake_sp <- sp::SpatialPolygonsDataFrame(polys_sp, fake_data) @@ -72,7 +74,7 @@ test_that("fortify.default can handle healthy data-frame-like objects", { # Unhealthy data-frame-like (matrix with no colnames) - expect_error(fortify(cbind(X, Y, Z, deparse.level=0))) + expect_error(fortify(cbind(X, Y, Z, deparse.level = 0))) # Healthy data-frame-like (matrix with colnames) @@ -92,11 +94,11 @@ test_that("fortify.default can handle healthy data-frame-like objects", { as.data.frame.foo <- function(x, row.names = NULL, ...) { key <- if (is.null(names(x))) rownames(x) else names(x) - data.frame(key=key, value=unname(unclass(x))) + data.frame(key = key, value = unname(unclass(x))) } registerS3method("as.data.frame", "foo", as.data.frame.foo) - expect_identical(fortify(object), data.frame(key=names(object), value=Y)) + expect_identical(fortify(object), data.frame(key = names(object), value = Y)) # Rejected by fortify.default() because of unhealthy dim() behavior @@ -163,7 +165,7 @@ test_that("fortify.default can handle healthy data-frame-like objects", { as.data.frame.foo <- function(x, row.names = NULL, ...) { key <- if (is.null(names(x))) rownames(x) else names(x) - data.frame(oops=key, value=unname(unclass(x))) + data.frame(oops = key, value = unname(unclass(x))) } registerS3method("as.data.frame", "foo", as.data.frame.foo) expect_error(fortify(object)) diff --git a/tests/testthat/test-function-args.R b/tests/testthat/test-function-args.R index 2a78bf9f50..ffc095d567 100644 --- a/tests/testthat/test-function-args.R +++ b/tests/testthat/test-function-args.R @@ -34,9 +34,12 @@ test_that("geom_xxx and GeomXxx$draw arg defaults match", { common_names <- intersect(names(fun_args), names(draw_args)) - expect_identical(fun_args[common_names], draw_args[common_names], - info = paste0("Mismatch between arg defaults for ", geom_fun_name, - " and ", class(geom_fun()$geom)[1], "'s $draw and/or $draw_group functions.") + expect_identical( + fun_args[common_names], draw_args[common_names], + info = paste0( + "Mismatch between arg defaults for ", geom_fun_name, " and ", + class(geom_fun()$geom)[1], "'s $draw and/or $draw_group functions." + ) ) }) }) @@ -67,9 +70,12 @@ test_that("stat_xxx and StatXxx$compute_panel arg defaults match", { common_names <- intersect(names(fun_args), names(calc_args)) - expect_identical(fun_args[common_names], calc_args[common_names], - info = paste0("Mismatch between arg defaults for ", stat_fun_name, - " and ", class(stat_fun()$stat)[1], "'s $compute_panel and/or $compute_group functions.") + expect_identical( + fun_args[common_names], calc_args[common_names], + info = paste0( + "Mismatch between arg defaults for ", stat_fun_name, " and ", + class(stat_fun()$stat)[1], "'s $compute_panel and/or $compute_group functions." + ) ) }) }) diff --git a/tests/testthat/test-geom-bar.R b/tests/testthat/test-geom-bar.R index 28d2430c09..ab91938f3c 100644 --- a/tests/testthat/test-geom-bar.R +++ b/tests/testthat/test-geom-bar.R @@ -27,8 +27,10 @@ test_that("geom_bar works in both directions", { test_that("geom_bar default widths considers panels", { - dat <- data_frame0(x = c(1:2, 1:2 + 0.1), y = 1, - PANEL = factor(rep(1:2, each = 2))) + dat <- data_frame0( + x = c(1:2, 1:2 + 0.1), y = 1, + PANEL = factor(rep(1:2, each = 2)) + ) layer <- geom_bar() params <- layer$geom_params diff --git a/tests/testthat/test-geom-boxplot.R b/tests/testthat/test-geom-boxplot.R index 195a3d9ade..e6be38e3ad 100644 --- a/tests/testthat/test-geom-boxplot.R +++ b/tests/testthat/test-geom-boxplot.R @@ -1,13 +1,13 @@ # thanks wch for providing the test code test_that("geom_boxplot range includes all outliers", { - dat <- data_frame(x = 1, y = c(-(1:20) ^ 3, (1:20) ^ 3) ) - p <- ggplot_build(ggplot(dat, aes(x,y)) + geom_boxplot()) + dat <- data_frame(x = 1, y = c(-(1:20) ^ 3, (1:20) ^ 3)) + p <- ggplot_build(ggplot(dat, aes(x, y)) + geom_boxplot()) miny <- p$layout$panel_params[[1]]$y.range[1] maxy <- p$layout$panel_params[[1]]$y.range[2] - expect_true(miny <= min(dat$y)) - expect_true(maxy >= max(dat$y)) + expect_lte(miny, min(dat$y)) + expect_gte(maxy, max(dat$y)) # Unless specifically directed not to p <- ggplot_build(ggplot(dat, aes(x, y)) + geom_boxplot(outliers = FALSE)) @@ -20,7 +20,7 @@ test_that("geom_boxplot range includes all outliers", { }) test_that("geom_boxplot works in both directions", { - dat <- data_frame(x = 1, y = c(-(1:20) ^ 3, (1:20) ^ 3) ) + dat <- data_frame(x = 1, y = c(-(1:20) ^ 3, (1:20) ^ 3)) p <- ggplot(dat, aes(x, y)) + geom_boxplot() x <- get_layer_data(p) @@ -36,7 +36,7 @@ test_that("geom_boxplot works in both directions", { }) test_that("geom_boxplot for continuous x gives warning if more than one x (#992)", { - dat <- expand.grid(x = 1:2, y = c(-(1:5) ^ 3, (1:5) ^ 3) ) + dat <- expand.grid(x = 1:2, y = c(-(1:5) ^ 3, (1:5) ^ 3)) bplot <- function(aes = NULL, extra = list()) { ggplot_build(ggplot(dat, aes) + geom_boxplot(aes) + extra) diff --git a/tests/testthat/test-geom-col.R b/tests/testthat/test-geom-col.R index 5849ea0bcc..d6e8e75111 100644 --- a/tests/testthat/test-geom-col.R +++ b/tests/testthat/test-geom-col.R @@ -26,7 +26,7 @@ test_that("geom_col works in both directions", { x$flipped_aes <- NULL y$flipped_aes <- NULL - expect_identical(x, flip_data(y, TRUE)[,names(x)]) + expect_identical(x, flip_data(y, TRUE)[, names(x)]) }) test_that("geom_col supports alignment of columns", { diff --git a/tests/testthat/test-geom-dotplot.R b/tests/testthat/test-geom-dotplot.R index 648c52f926..26bc0cadf3 100644 --- a/tests/testthat/test-geom-dotplot.R +++ b/tests/testthat/test-geom-dotplot.R @@ -30,8 +30,8 @@ test_that("dodging works", { expect_true(all(abs(df$x - (xbase + xoffset)) < 1e-6)) # Check that xmin and xmax are in the right place - expect_true(all(abs(df$xmax - df$x - dwidth/2) < 1e-6)) - expect_true(all(abs(df$x - df$xmin - dwidth/2) < 1e-6)) + expect_true(all(abs(df$xmax - df$x - dwidth / 2) < 1e-6)) + expect_true(all(abs(df$x - df$xmin - dwidth / 2) < 1e-6)) }) test_that("binning works", { @@ -55,32 +55,32 @@ test_that("binning works", { test_that("NA's result in warning from stat_bindot", { set.seed(122) dat <- data_frame(x = rnorm(20)) - dat$x[c(2,10)] <- NA + dat$x[c(2, 10)] <- NA # Need to assign it to a var here so that it doesn't automatically print expect_snapshot_warning(ggplot_build(ggplot(dat, aes(x)) + geom_dotplot(binwidth = 0.2))) }) test_that("when binning on y-axis, limits depend on the panel", { - p <- ggplot(mtcars, aes(factor(cyl), mpg)) + - geom_dotplot(binaxis='y', binwidth = 1/30 * diff(range(mtcars$mpg))) + p <- ggplot(mtcars, aes(factor(cyl), mpg)) + + geom_dotplot(binaxis = "y", binwidth = 1 / 30 * diff(range(mtcars$mpg))) - b1 <- ggplot_build(p + facet_wrap(~am)) - b2 <- ggplot_build(p + facet_wrap(~am, scales = "free_y")) + b1 <- ggplot_build(p + facet_wrap(~am)) + b2 <- ggplot_build(p + facet_wrap(~am, scales = "free_y")) - equal_limits1 <- (b1$layout$panel_params[[1]]$y.range == b1$layout$panel_params[[2]]$y.range) - equal_limits2 <- (b2$layout$panel_params[[1]]$y.range == b2$layout$panel_params[[2]]$y.range) + equal_limits1 <- (b1$layout$panel_params[[1]]$y.range == b1$layout$panel_params[[2]]$y.range) + equal_limits2 <- (b2$layout$panel_params[[1]]$y.range == b2$layout$panel_params[[2]]$y.range) - expect_true(all(equal_limits1)) - expect_false(all(equal_limits2)) + expect_true(all(equal_limits1)) + expect_false(all(equal_limits2)) }) test_that("weight aesthetic is checked", { - p <- ggplot(mtcars, aes(x = mpg, weight = gear/3)) + - geom_dotplot(binwidth = 1/30 * diff(range(mtcars$mpg))) + p <- ggplot(mtcars, aes(x = mpg, weight = gear / 3)) + + geom_dotplot(binwidth = 1 / 30 * diff(range(mtcars$mpg))) expect_snapshot_warning(ggplot_build(p)) p <- ggplot(mtcars, aes(x = mpg, weight = -gear)) + - geom_dotplot(binwidth = 1/30 * diff(range(mtcars$mpg))) + geom_dotplot(binwidth = 1 / 30 * diff(range(mtcars$mpg))) expect_snapshot_warning(ggplot_build(p)) }) @@ -177,7 +177,7 @@ test_that("geom_dotplot draws correctly", { coord_flip() ) expect_doppelganger("bin y, three x groups, fill and dodge", - ggplot(dat2, aes(x, y, fill = g)) + scale_y_continuous(breaks = seq(-4 ,4, 0.4)) + + ggplot(dat2, aes(x, y, fill = g)) + scale_y_continuous(breaks = seq(-4, 4, 0.4)) + geom_dotplot(binwidth = 0.2, position = "dodge", binaxis = "y", stackdir = "center") ) expect_doppelganger("bin y, continous x-axis, grouping by x", diff --git a/tests/testthat/test-geom-hex.R b/tests/testthat/test-geom-hex.R index 0934f8fd27..99075cb006 100644 --- a/tests/testthat/test-geom-hex.R +++ b/tests/testthat/test-geom-hex.R @@ -36,6 +36,6 @@ test_that("geom_hex works in non-linear coordinate systems", { p + coord_trans(y = "sqrt") ) expect_doppelganger("hex bin plot in polar coordinates", - p + coord_polar() + p + coord_polar() ) }) diff --git a/tests/testthat/test-geom-hline-vline-abline.R b/tests/testthat/test-geom-hline-vline-abline.R index b637cd0a2f..a81583318a 100644 --- a/tests/testthat/test-geom-hline-vline-abline.R +++ b/tests/testthat/test-geom-hline-vline-abline.R @@ -39,7 +39,7 @@ test_that("curved lines in map projections", { nzmap + coord_map() ) expect_doppelganger("lines curved in azequalarea", - nzmap + coord_map(projection = 'azequalarea', orientation = c(-36.92, 174.6, 0)) + nzmap + coord_map(projection = "azequalarea", orientation = c(-36.92, 174.6, 0)) ) }) diff --git a/tests/testthat/test-geom-path.R b/tests/testthat/test-geom-path.R index 3255a2f4cb..01ce11db43 100644 --- a/tests/testthat/test-geom-path.R +++ b/tests/testthat/test-geom-path.R @@ -6,12 +6,12 @@ test_that("keep_mid_true drops leading/trailing FALSE", { }) test_that("geom_path() throws meaningful error on bad combination of varying aesthetics", { - p <- ggplot(economics, aes(unemploy/pop, psavert, colour = pop)) + geom_path(linetype = 2) + p <- ggplot(economics, aes(unemploy / pop, psavert, colour = pop)) + geom_path(linetype = 2) expect_snapshot_error(ggplotGrob(p)) }) test_that("repair_segment_arrow() repairs sensibly", { - group <- c(1,1,1,1,2,2) + group <- c(1, 1, 1, 1, 2, 2) ans <- repair_segment_arrow(arrow(ends = "last"), group) expect_equal(ans$ends, rep(2L, 4)) @@ -35,7 +35,7 @@ test_that("stairstep() does not error with too few observations", { test_that("stairstep() exists with error when an invalid `direction` is given", { df <- data_frame(x = 1:3, y = 1:3) - expect_error(stairstep(df, direction="invalid")) + expect_error(stairstep(df, direction = "invalid")) }) test_that("stairstep() output is correct for direction = 'vh'", { @@ -68,7 +68,7 @@ test_that("geom_path draws correctly", { nCategory <- 5 nItem <- 6 df <- data_frame(category = rep(LETTERS[1:nCategory], 1, each = nItem), - item = paste("Item#", rep(1:nItem, nCategory, each = 1), sep = ''), + item = paste0("Item#", rep(1:nItem, nCategory, each = 1)), value = rep(1:nItem, nCategory, each = 1) + runif(nCategory * nItem) * 0.8) df2 <- df[c(1, 2, 7, 8, 13, 14, 3:6, 9:12, 15:nrow(df)), ] diff --git a/tests/testthat/test-geom-polygon.R b/tests/testthat/test-geom-polygon.R index 3cf3636655..fbbbaf1b1a 100644 --- a/tests/testthat/test-geom-polygon.R +++ b/tests/testthat/test-geom-polygon.R @@ -1,7 +1,7 @@ # Visual tests ------------------------------------------------------------ -skip_if(utils::packageVersion('grid') < "3.6") +skip_if(utils::packageVersion("grid") < "3.6") test_that("geom_polygon draws correctly", { tbl <- data_frame( diff --git a/tests/testthat/test-geom-ribbon.R b/tests/testthat/test-geom-ribbon.R index c923942dde..8e6dade69c 100644 --- a/tests/testthat/test-geom-ribbon.R +++ b/tests/testthat/test-geom-ribbon.R @@ -16,7 +16,7 @@ test_that("geom_ribbon() checks the aesthetics", { test_that("NAs are not dropped from the data", { df <- data_frame(x = 1:5, y = c(1, 1, NA, 1, 1)) - p <- ggplot(df, aes(x))+ + p <- ggplot(df, aes(x)) + geom_ribbon(aes(ymin = y - 1, ymax = y + 1)) expect_equal(get_layer_data(p)$ymin, c(0, 0, NA, 0, 0)) @@ -37,7 +37,7 @@ test_that("geom_ribbon works in both directions", { x$flipped_aes <- NULL y$flipped_aes <- NULL - expect_identical(x, flip_data(y, TRUE)[,names(x)]) + expect_identical(x, flip_data(y, TRUE)[, names(x)]) }) test_that("outline.type option works", { diff --git a/tests/testthat/test-geom-rug.R b/tests/testthat/test-geom-rug.R index 7539a494a6..45c1a8febd 100644 --- a/tests/testthat/test-geom-rug.R +++ b/tests/testthat/test-geom-rug.R @@ -1,6 +1,6 @@ n <- 10 df <- data_frame(x = 1:n, y = (1:n)^3) -p <- ggplot(df, aes(x, y)) + geom_point() + geom_rug(sides = 'l') +p <- ggplot(df, aes(x, y)) + geom_point() + geom_rug(sides = "l") test_that("coord_flip flips the rugs", { a <- get_layer_grob(p, 2) @@ -20,7 +20,7 @@ test_that("coord_flip flips the rugs", { }) test_that("Rug length needs unit object", { - p <- ggplot(df, aes(x,y)) + p <- ggplot(df, aes(x, y)) expect_snapshot_error(print(p + geom_rug(length = 0.01))) }) @@ -31,7 +31,7 @@ test_that("Rug lengths are correct", { expect_equal(a[[1]]$children[[1]]$x0, unit(0, "npc")) expect_equal(a[[1]]$children[[1]]$x1, unit(0.03, "npc")) - p <- ggplot(df, aes(x, y)) + geom_point() + geom_rug(sides = 'l', length = unit(12, "pt")) + p <- ggplot(df, aes(x, y)) + geom_point() + geom_rug(sides = "l", length = unit(12, "pt")) b <- get_layer_grob(p, 2) # Check default length is changed diff --git a/tests/testthat/test-geom-sf.R b/tests/testthat/test-geom-sf.R index e52a13e917..363b73da73 100644 --- a/tests/testthat/test-geom-sf.R +++ b/tests/testthat/test-geom-sf.R @@ -3,26 +3,29 @@ test_that("geom_sf() determines the legend type automatically", { if (packageVersion("sf") < "0.5.3") skip("Need sf 0.5.3") mp <- sf::st_sf( - geometry = sf::st_sfc(sf::st_multipoint(rbind(c(1,1), c(2,2), c(3,3)))), - v = "a") + geometry = sf::st_sfc(sf::st_multipoint(rbind(c(1, 1), c(2, 2), c(3, 3)))), + v = "a" + ) - s1 <- rbind(c(0,3),c(0,4),c(1,5),c(2,5)) - s2 <- rbind(c(0.2,3), c(0.2,4), c(1,4.8), c(2,4.8)) - s3 <- rbind(c(0,4.4), c(0.6,5)) + s1 <- rbind(c(0, 3), c(0, 4), c(1, 5), c(2, 5)) + s2 <- rbind(c(0.2, 3), c(0.2, 4), c(1, 4.8), c(2, 4.8)) + s3 <- rbind(c(0, 4.4), c(0.6, 5)) mls <- sf::st_sf( - geometry = sf::st_sfc(sf::st_multilinestring(list(s1,s2,s3))), - v = "a") + geometry = sf::st_sfc(sf::st_multilinestring(list(s1, s2, s3))), + v = "a" + ) - p1 <- rbind(c(0,0), c(1,0), c(3,2), c(2,4), c(1,4), c(0,0)) - p2 <- rbind(c(1,1), c(1,2), c(2,2), c(1,1)) - p3 <- rbind(c(3,0), c(4,0), c(4,1), c(3,1), c(3,0)) - p4 <- rbind(c(3.3,0.3), c(3.8,0.3), c(3.8,0.8), c(3.3,0.8), c(3.3,0.3))[5:1,] - p5 <- rbind(c(3,3), c(4,2), c(4,3), c(3,3)) + p1 <- rbind(c(0, 0), c(1, 0), c(3, 2), c(2, 4), c(1, 4), c(0, 0)) + p2 <- rbind(c(1, 1), c(1, 2), c(2, 2), c(1, 1)) + p3 <- rbind(c(3, 0), c(4, 0), c(4, 1), c(3, 1), c(3, 0)) + p4 <- rbind(c(3.3, 0.3), c(3.8, 0.3), c(3.8, 0.8), c(3.3, 0.8), c(3.3, 0.3))[5:1, ] + p5 <- rbind(c(3, 3), c(4, 2), c(4, 3), c(3, 3)) mpol <- sf::st_sf( - geometry = sf::st_sfc(sf::st_multipolygon(list(list(p1,p2), list(p3,p4), list(p5)))), - v = "a") + geometry = sf::st_sfc(sf::st_multipolygon(list(list(p1, p2), list(p3, p4), list(p5)))), + v = "a" + ) fun_geom_sf <- function(sf, show.legend) { p <- ggplot() + geom_sf(aes(colour = v), data = sf, show.legend = show.legend) @@ -54,10 +57,10 @@ test_that("geom_sf() determines the legend type from mapped geometry column", { skip_if_not_installed("sf") if (packageVersion("sf") < "0.5.3") skip("Need sf 0.5.3") - p1 <- rbind(c(1,1), c(2,2), c(3,3)) - s1 <- rbind(c(0,3), c(0,4), c(1,5), c(2,5)) - s2 <- rbind(c(0.2,3), c(0.2,4), c(1,4.8), c(2,4.8)) - s3 <- rbind(c(0,4.4), c(0.6,5)) + p1 <- rbind(c(1, 1), c(2, 2), c(3, 3)) + s1 <- rbind(c(0, 3), c(0, 4), c(1, 5), c(2, 5)) + s2 <- rbind(c(0.2, 3), c(0.2, 4), c(1, 4.8), c(2, 4.8)) + s3 <- rbind(c(0, 4.4), c(0.6, 5)) d_sf <- sf::st_sf( g_point = sf::st_sfc(sf::st_multipoint(p1)), @@ -195,7 +198,7 @@ test_that("geom_sf data type renders appropriate legends", { # Point data data <- sf::st_as_sf( - data.frame(lon = c(1, 2), lat = c(3, 4), col = c("foo", "bar")), + data_frame0(lon = c(1, 2), lat = c(3, 4), col = c("foo", "bar")), coords = c("lon", "lat") ) expect_doppelganger( @@ -233,7 +236,7 @@ test_that("geom_sf data type renders appropriate legends", { test_that("geom_sf uses combinations of geometry correctly", { skip_if_not_installed("sf") - t <- seq(0, 2 *pi, length.out = 10) + t <- seq(0, 2 * pi, length.out = 10) data <- sf::st_sf(sf::st_sfc( sf::st_multipoint(cbind(1:2, 3:4)), sf::st_multilinestring(list( @@ -306,19 +309,20 @@ test_that("geom_sf draws arrows correctly", { ) nc <- sf::st_linestring( - sf::st_coordinates(sf::st_as_sf(nc_tiny_coords, coords = c("x", "y"), crs = 4326)) - ) + sf::st_coordinates(sf::st_as_sf(nc_tiny_coords, coords = c("x", "y"), crs = 4326)) + ) nc2 <- sf::st_cast( sf::st_sfc( sf::st_multilinestring(lapply( 1:(length(sf::st_coordinates(nc)[, 1]) - 1), - function(x) rbind( + function(x) { + rbind( as.numeric(sf::st_coordinates(nc)[x, 1:2]), as.numeric(sf::st_coordinates(nc)[x + 1, 1:2]) - ) - ) - ) + ) + } + )) ), "LINESTRING" ) diff --git a/tests/testthat/test-geom-smooth.R b/tests/testthat/test-geom-smooth.R index 42c82108c7..7b40300dc4 100644 --- a/tests/testthat/test-geom-smooth.R +++ b/tests/testthat/test-geom-smooth.R @@ -1,7 +1,7 @@ test_that("data is ordered by x", { df <- data_frame(x = c(1, 5, 2, 3, 4), y = 1:5) - ps <- ggplot(df, aes(x, y))+ + ps <- ggplot(df, aes(x, y)) + geom_smooth(stat = "identity", se = FALSE) expect_equal(get_layer_data(ps)[c("x", "y")], df[order(df$x), ], ignore_attr = TRUE) @@ -9,18 +9,18 @@ test_that("data is ordered by x", { test_that("geom_smooth works in both directions", { p <- ggplot(mpg, aes(displ, hwy)) + - geom_smooth(method = 'loess', formula = y ~ x) + geom_smooth(method = "loess", formula = y ~ x) x <- get_layer_data(p) expect_false(x$flipped_aes[1]) p <- ggplot(mpg, aes(hwy, displ)) + - geom_smooth(orientation = "y", method = 'loess', formula = y ~ x) + geom_smooth(orientation = "y", method = "loess", formula = y ~ x) y <- get_layer_data(p) expect_true(y$flipped_aes[1]) x$flipped_aes <- NULL y$flipped_aes <- NULL - expect_identical(x, flip_data(y, TRUE)[,names(x)]) + expect_identical(x, flip_data(y, TRUE)[, names(x)]) }) test_that("default smoothing methods for small and large data sets work", { diff --git a/tests/testthat/test-geom-violin.R b/tests/testthat/test-geom-violin.R index 7d73c04e94..b6bc1dee11 100644 --- a/tests/testthat/test-geom-violin.R +++ b/tests/testthat/test-geom-violin.R @@ -25,13 +25,13 @@ test_that("geom_violin works in both directions", { x$flipped_aes <- NULL y$flipped_aes <- NULL - expect_identical(x, flip_data(y, TRUE)[,names(x)]) + expect_identical(x, flip_data(y, TRUE)[, names(x)]) }) # create_quantile_segment_frame ------------------------------------------------- test_that("create_quantile_segment_frame functions for 3 quantiles", { - density.data <- data_frame(y = (1:256)/256, density = 1/256) # uniform density + density.data <- data_frame(y = (1:256) / 256, density = 1 / 256) # uniform density qs <- c(0.25, 0.5, 0.75) # 3 quantiles expect_equal(create_quantile_segment_frame(density.data, qs)$y, @@ -39,7 +39,7 @@ test_that("create_quantile_segment_frame functions for 3 quantiles", { }) test_that("quantiles do not fail on zero-range data", { - zero.range.data <- data_frame(y = rep(1,3)) + zero.range.data <- data_frame(y = rep(1, 3)) p <- ggplot(zero.range.data) + geom_violin(aes(1, y), draw_quantiles = 0.5) # This should return without error and have length one @@ -81,13 +81,13 @@ test_that("quantiles do not issue warning", { test_that("geom_violin draws correctly", { set.seed(111) dat <- data_frame(x = rep(factor(LETTERS[1:3]), 30), y = rnorm(90)) - dat <- dat[dat$x != "C" | c(TRUE, FALSE),] # Keep half the C's + dat <- dat[dat$x != "C" | c(TRUE, FALSE), ] # Keep half the C's expect_doppelganger("basic", ggplot(dat, aes(x = x, y = y)) + geom_violin() ) expect_doppelganger("scale area to sample size (C is smaller)", - ggplot(dat, aes(x = x, y = y)) + geom_violin(scale = "count"), + ggplot(dat, aes(x = x, y = y)) + geom_violin(scale = "count") ) expect_doppelganger("narrower (width=.5)", ggplot(dat, aes(x = x, y = y)) + geom_violin(width = 0.5) @@ -117,7 +117,7 @@ test_that("geom_violin draws correctly", { ggplot(dat, aes(x = as.numeric(1), y = y)) + geom_violin() ) expect_doppelganger("quantiles", - ggplot(dat, aes(x=x, y=y)) + geom_violin(draw_quantiles=c(0.25,0.5,0.75)) + ggplot(dat, aes(x = x, y = y)) + geom_violin(draw_quantiles = c(0.25, 0.5, 0.75)) ) dat2 <- data_frame(x = rep(factor(LETTERS[1:3]), 30), y = rnorm(90), g = rep(factor(letters[5:6]), 45)) diff --git a/tests/testthat/test-ggsave.R b/tests/testthat/test-ggsave.R index a5d7a5283c..a63c23cbaa 100644 --- a/tests/testthat/test-ggsave.R +++ b/tests/testthat/test-ggsave.R @@ -55,7 +55,7 @@ test_that("ggsave uses theme background as image background", { img <- xml2::read_xml(path) # Find background rect in svg bg <- as.character(xml2::xml_find_first(img, xpath = "d1:rect/@style")) - expect_true(grepl("fill: #00CCCC", bg)) + expect_true(grepl("fill: #00CCCC", bg, fixed = TRUE)) }) test_that("ggsave can handle blank background", { @@ -70,7 +70,7 @@ test_that("ggsave can handle blank background", { ggsave(path, p, device = "svg", width = 5, height = 5) img <- xml2::read_xml(path) bg <- as.character(xml2::xml_find_first(img, xpath = "d1:rect/@style")) - expect_true(grepl("fill: none", bg)) + expect_true(grepl("fill: none", bg, fixed = TRUE)) }) test_that("ggsave warns about empty or multiple filenames", { diff --git a/tests/testthat/test-guides.R b/tests/testthat/test-guides.R index 23df1f75e2..89f4867bb8 100644 --- a/tests/testthat/test-guides.R +++ b/tests/testthat/test-guides.R @@ -60,7 +60,7 @@ test_that("Colorbar respects show.legend in layer", { test_that("show.legend handles named vectors", { n_legends <- function(p) { g <- ggplotGrob(p) - gb <- grep("guide-box", g$layout$name) + gb <- grep("guide-box", g$layout$name, fixed = TRUE) n <- vapply(g$grobs[gb], function(x) { if (is.zero(x)) return(0) length(x$grobs) - 1 @@ -222,9 +222,9 @@ test_that("guide merging for guide_legend() works as expected", { }) test_that("size = NA doesn't throw rendering errors", { - df <- data.frame( + df <- data_frame0( x = c(1, 2), - group = c("a","b") + group = c("a", "b") ) p <- ggplot(df, aes(x = x, y = 0, colour = group)) + geom_point(size = NA, na.rm = TRUE) @@ -327,7 +327,7 @@ test_that("guide_coloursteps can parse (un)even steps from discrete scales", { g <- guide_coloursteps(even.steps = TRUE) decor <- g$train(scale = scale, aesthetics = "colour")$decor - expect_equal(decor$max - decor$min, rep(1/3, 3)) + expect_equal(decor$max - decor$min, rep(1 / 3, 3)) g <- guide_coloursteps(even.steps = FALSE) decor <- g$train(scale = scale, aesthetics = "colour")$decor @@ -447,14 +447,14 @@ test_that("guide_axis_logticks calculates appropriate ticks", { } guide <- guide_axis_logticks(negative.small = 10) - outcome <- c((1:10)*10, (2:10)*100) + outcome <- c((1:10) * 10, (2:10) * 100) # Test the classic log10 transformation scale <- test_scale(transform_log10(), c(10, 1000)) key <- train_guide(guide, scale)$logkey expect_equal(sort(key$x), log10(outcome)) - expect_equal(key$.type, rep(c(1,2,3), c(3, 2, 14))) + expect_equal(key$.type, rep(c(1, 2, 3), c(3, 2, 14))) # Test compound transformation scale <- test_scale(transform_compose(transform_log10(), transform_reverse()), c(10, 1000)) @@ -468,7 +468,7 @@ test_that("guide_axis_logticks calculates appropriate ticks", { unlog <- sort(transform_pseudo_log()$inverse(key$x)) expect_equal(unlog, c(-rev(outcome), 0, outcome)) - expect_equal(key$.type, rep(c(1,2,3), c(7, 4, 28))) + expect_equal(key$.type, rep(c(1, 2, 3), c(7, 4, 28))) # Test expanded argument scale <- test_scale(transform_log10(), c(20, 900)) @@ -875,16 +875,16 @@ test_that("guides are positioned correctly", { p1 + theme(legend.position = "top") ) expect_doppelganger("facet_grid, legend on left", - p1 + facet_grid(x~y) + theme(legend.position = "left") + p1 + facet_grid(x ~ y) + theme(legend.position = "left") ) expect_doppelganger("facet_grid, legend on bottom", - p1 + facet_grid(x~y) + theme(legend.position = "bottom") + p1 + facet_grid(x ~ y) + theme(legend.position = "bottom") ) expect_doppelganger("facet_grid, legend on right", - p1 + facet_grid(x~y) + theme(legend.position = "right") + p1 + facet_grid(x ~ y) + theme(legend.position = "right") ) expect_doppelganger("facet_grid, legend on top", - p1 + facet_grid(x~y) + theme(legend.position = "top") + p1 + facet_grid(x ~ y) + theme(legend.position = "top") ) expect_doppelganger("facet_wrap, legend on left", p1 + facet_wrap(~ x) + theme(legend.position = "left") @@ -915,13 +915,13 @@ test_that("guides are positioned correctly", { p2 + theme(legend.position.inside = c(0.5, 0.5)) ) expect_doppelganger("legend inside plot, bottom left", - p2 + theme(legend.justification = c(0,0), legend.position.inside = c(0,0)) + p2 + theme(legend.justification = c(0, 0), legend.position.inside = c(0, 0)) ) expect_doppelganger("legend inside plot, top right", - p2 + theme(legend.justification = c(1,1), legend.position.inside = c(1,1)) + p2 + theme(legend.justification = c(1, 1), legend.position.inside = c(1, 1)) ) expect_doppelganger("legend inside plot, bottom left of legend at center", - p2 + theme(legend.justification = c(0,0), legend.position.inside = c(0.5,0.5)) + p2 + theme(legend.justification = c(0, 0), legend.position.inside = c(0.5, 0.5)) ) }) @@ -995,7 +995,7 @@ test_that("guides title and text are positioned correctly", { ) ) - expect_doppelganger("rotated guide titles and labels", p ) + expect_doppelganger("rotated guide titles and labels", p) # title justification p <- ggplot(data.frame(x = 1:2)) + @@ -1049,12 +1049,12 @@ test_that("colorbar can be styled", { p <- ggplot(df, aes(x, x, color = x)) + geom_point() expect_doppelganger("white-to-red colorbar, white ticks, no frame", - p + scale_color_gradient(low = 'white', high = 'red') + p + scale_color_gradient(low = "white", high = "red") ) expect_doppelganger("customized colorbar", p + scale_color_gradient( - low = 'white', high = 'red', + low = "white", high = "red", guide = guide_colorbar( theme = theme( legend.frame = element_rect(colour = "green", linewidth = 1.5 / .pt), @@ -1144,22 +1144,22 @@ test_that("binning scales understand the different combinations of limits, break expect_doppelganger("guide_bins understands coinciding limits and bins", p + scale_color_binned(limits = c(1999, 2008), breaks = c(1999, 2000, 2002, 2004, 2006), - guide = 'bins') + guide = "bins") ) expect_doppelganger("guide_bins understands coinciding limits and bins 2", p + scale_color_binned(limits = c(1999, 2008), breaks = c(2000, 2002, 2004, 2006, 2008), - guide = 'bins') + guide = "bins") ) expect_doppelganger("guide_bins understands coinciding limits and bins 3", p + scale_color_binned(limits = c(1999, 2008), breaks = c(1999, 2000, 2002, 2004, 2006), - guide = 'bins', show.limits = TRUE) + guide = "bins", show.limits = TRUE) ) expect_doppelganger("guide_bins sets labels when limits is in breaks", p + scale_color_binned(limits = c(1999, 2008), breaks = c(1999, 2000, 2002, 2004, 2006), - labels = 1:5, guide = 'bins') + labels = 1:5, guide = "bins") ) expect_snapshot_warning(ggplotGrob(p + scale_color_binned(labels = 1:4, show.limits = TRUE, guide = "bins"))) diff --git a/tests/testthat/test-labels.R b/tests/testthat/test-labels.R index 6a26578c0b..601468270c 100644 --- a/tests/testthat/test-labels.R +++ b/tests/testthat/test-labels.R @@ -1,52 +1,52 @@ test_that("setting guide labels works", { - expect_identical(xlab("my label")$x, "my label") - expect_identical(labs(x = "my label")$x, "my label") - - expect_identical(ylab("my label")$y, "my label") - expect_identical(labs(y = "my label")$y, "my label") - - # Plot titles - expect_identical(labs(title = "my title")$title, "my title") - expect_identical(labs(title = "my title", - subtitle = "my subtitle")$subtitle, "my subtitle") - - # whole plot annotations - expect_identical(labs(caption = "my notice")$caption, "my notice") - expect_identical(labs(title = "my title", - caption = "my notice")$caption, "my notice") - expect_identical(labs(tag = "A)")$tag, "A)") - expect_identical(labs(title = "my title", - tag = "A)")$tag, "A)") - - # Colour - expect_identical(labs(colour = "my label")$colour, "my label") - # American spelling - expect_identical(labs(color = "my label")$colour, "my label") - - # No extra elements exists - expect_equal(labs(title = "my title"), list(title = "my title"), ignore_attr = TRUE) # formal argument - expect_equal(labs(colour = "my label"), list(colour = "my label"), ignore_attr = TRUE) # dot - expect_equal(labs(foo = "bar"), list(foo = "bar"), ignore_attr = TRUE) # non-existent param - - # labs() has list-splicing semantics - params <- list(title = "my title", tag = "A)") - expect_identical(labs(!!!params)$tag, "A)") - - # NULL is preserved - expect_equal(labs(title = NULL), list(title = NULL), ignore_attr = TRUE) - - # ggtitle works in the same way as labs() - expect_identical(ggtitle("my title")$title, "my title") - expect_identical( - ggtitle("my title", subtitle = "my subtitle")$subtitle, - "my subtitle" - ) - expect_equal( - unclass(ggtitle("my title", subtitle = NULL)), - list(title = "my title", subtitle = NULL), - ignore_attr = TRUE - ) + expect_identical(xlab("my label")$x, "my label") + expect_identical(labs(x = "my label")$x, "my label") + + expect_identical(ylab("my label")$y, "my label") + expect_identical(labs(y = "my label")$y, "my label") + + # Plot titles + expect_identical(labs(title = "my title")$title, "my title") + expect_identical(labs(title = "my title", + subtitle = "my subtitle")$subtitle, "my subtitle") + + # whole plot annotations + expect_identical(labs(caption = "my notice")$caption, "my notice") + expect_identical(labs(title = "my title", + caption = "my notice")$caption, "my notice") + expect_identical(labs(tag = "A)")$tag, "A)") + expect_identical(labs(title = "my title", + tag = "A)")$tag, "A)") + + # Colour + expect_identical(labs(colour = "my label")$colour, "my label") + # American spelling + expect_identical(labs(color = "my label")$colour, "my label") + + # No extra elements exists + expect_equal(labs(title = "my title"), list(title = "my title"), ignore_attr = TRUE) # formal argument + expect_equal(labs(colour = "my label"), list(colour = "my label"), ignore_attr = TRUE) # dot + expect_equal(labs(foo = "bar"), list(foo = "bar"), ignore_attr = TRUE) # non-existent param + + # labs() has list-splicing semantics + params <- list(title = "my title", tag = "A)") + expect_identical(labs(!!!params)$tag, "A)") + + # NULL is preserved + expect_equal(labs(title = NULL), list(title = NULL), ignore_attr = TRUE) + + # ggtitle works in the same way as labs() + expect_identical(ggtitle("my title")$title, "my title") + expect_identical( + ggtitle("my title", subtitle = "my subtitle")$subtitle, + "my subtitle" + ) + expect_equal( + unclass(ggtitle("my title", subtitle = NULL)), + list(title = "my title", subtitle = NULL), + ignore_attr = TRUE + ) }) test_that("Labels from default stat mapping are overwritten by default labels", { @@ -103,7 +103,7 @@ test_that("get_alt_text checks dots", { }) test_that("warnings are thrown for unknown labels", { - p <- ggplot(mtcars, aes(mpg, disp)) + geom_point() + labs(foo = 'bar') + p <- ggplot(mtcars, aes(mpg, disp)) + geom_point() + labs(foo = "bar") expect_snapshot_warning(ggplot_build(p)) }) diff --git a/tests/testthat/test-layer.R b/tests/testthat/test-layer.R index 51f0cd9eee..ac65e5c147 100644 --- a/tests/testthat/test-layer.R +++ b/tests/testthat/test-layer.R @@ -112,7 +112,7 @@ test_that("inherit.aes works", { }) test_that("retransform works on computed aesthetics in `map_statistic`", { - df <- data.frame(x = rep(c(1,2), c(9, 25))) + df <- data.frame(x = rep(c(1, 2), c(9, 25))) p <- ggplot(df, aes(x)) + geom_bar() + scale_y_sqrt() expect_equal(get_layer_data(p)$y, c(3, 5)) @@ -148,10 +148,10 @@ test_that("layer warns for constant aesthetics", { test_that("layer names can be resolved", { p <- ggplot() + geom_point() + geom_point() - expect_equal(names(p$layers), c("geom_point", "geom_point...2")) + expect_named(p$layers, c("geom_point", "geom_point...2")) p <- ggplot() + geom_point(name = "foo") + geom_point(name = "bar") - expect_equal(names(p$layers), c("foo", "bar")) + expect_named(p$layers, c("foo", "bar")) l <- geom_point(name = "foobar") expect_error( diff --git a/tests/testthat/test-munch.R b/tests/testthat/test-munch.R index 5c26cab9a6..940451dd5a 100644 --- a/tests/testthat/test-munch.R +++ b/tests/testthat/test-munch.R @@ -1,49 +1,51 @@ test_that("interp works", { - single_interp_test <- function(start, end, n) { - i <- interp(start, end, n) - info <- paste0("start: ", start, "; end: ", end, "; n: ", n) - expect_equal(length(i), n, info = info) - expect_true(start %in% i, info = info) - expect_false(end %in% i, info = info) - expect_true(all(i >= start), info = info) - expect_true(all(i <= end), info = info) - } - single_interp_test(0, 1, 1) - single_interp_test(0, 1, 2) - single_interp_test(0, 1, 7) - single_interp_test(-23, 56, 1) - single_interp_test(-23, 56, 4) - single_interp_test(31.276, 34.443, 1) - single_interp_test(31.276, 34.443, 100) + single_interp_test <- function(start, end, n) { + i <- interp(start, end, n) + info <- paste0("start: ", start, "; end: ", end, "; n: ", n) + expect_equal(length(i), n, info = info) + expect_true(start %in% i, info = info) + expect_false(end %in% i, info = info) + expect_true(all(i >= start), info = info) + expect_true(all(i <= end), info = info) + } + single_interp_test(0, 1, 1) + single_interp_test(0, 1, 2) + single_interp_test(0, 1, 7) + single_interp_test(-23, 56, 1) + single_interp_test(-23, 56, 4) + single_interp_test(31.276, 34.443, 1) + single_interp_test(31.276, 34.443, 100) }) test_that("munch_data works", { - single_munch_test <- function(data, dist=NULL, segment_length = 0.01) { - md <- munch_data(data, dist, segment_length) - # all rows of dat are in md - expect_equal(nrow(merge(md, dat)), nrow(dat)) - expect_true(nrow(md) >= nrow(dat)) - } - dat <- data_frame(x = c(0, 60, 30, 20, 40, 45), - y = c(1, 1, 2, 2, 2, 2), - group = c(1L, 1L, 1L, 2L, 2L, 2L)) - dist <- dist_euclidean(dat$x, dat$y) - dist[dat$group[-1] != dat$group[-nrow(dat)]] <- NA - single_munch_test(dat, dist) - single_munch_test(dat, dist, segment_length = 10) - single_munch_test(dat, dist, segment_length = 100) - dist <- coord_polar(theta = "x")$distance(dat$x, dat$y, - list(r.range = range(c(0,dat$y)), - theta.range = range(dat$x))) - dist[dat$group[-1] != dat$group[-nrow(dat)]] <- NA - single_munch_test(dat, dist) - single_munch_test(dat, dist, segment_length = 10) - single_munch_test(dat, dist, segment_length = 100) - dist <- coord_polar(theta = "y")$distance(dat$x, dat$y, - list(r.range = range(c(0,dat$x)), - theta.range = range(dat$y))) - dist[dat$group[-1] != dat$group[-nrow(dat)]] <- NA - single_munch_test(dat, dist) - single_munch_test(dat, dist, segment_length = 10) - single_munch_test(dat, dist, segment_length = 100) + single_munch_test <- function(data, dist = NULL, segment_length = 0.01) { + md <- munch_data(data, dist, segment_length) + # all rows of dat are in md + expect_equal(nrow(merge(md, dat)), nrow(dat)) + expect_gte(nrow(md), nrow(dat)) + } + dat <- data_frame( + x = c(0, 60, 30, 20, 40, 45), + y = c(1, 1, 2, 2, 2, 2), + group = c(1L, 1L, 1L, 2L, 2L, 2L) + ) + dist <- dist_euclidean(dat$x, dat$y) + dist[dat$group[-1] != dat$group[-nrow(dat)]] <- NA + single_munch_test(dat, dist) + single_munch_test(dat, dist, segment_length = 10) + single_munch_test(dat, dist, segment_length = 100) + dist <- coord_polar(theta = "x")$distance( + dat$x, dat$y, list(r.range = range(c(0, dat$y)), theta.range = range(dat$x)) + ) + dist[dat$group[-1] != dat$group[-nrow(dat)]] <- NA + single_munch_test(dat, dist) + single_munch_test(dat, dist, segment_length = 10) + single_munch_test(dat, dist, segment_length = 100) + dist <- coord_polar(theta = "y")$distance( + dat$x, dat$y, list(r.range = range(c(0, dat$x)), theta.range = range(dat$y)) + ) + dist[dat$group[-1] != dat$group[-nrow(dat)]] <- NA + single_munch_test(dat, dist) + single_munch_test(dat, dist, segment_length = 10) + single_munch_test(dat, dist, segment_length = 100) }) diff --git a/tests/testthat/test-performance.R b/tests/testthat/test-performance.R index 1c65622b4a..233c2cc170 100644 --- a/tests/testthat/test-performance.R +++ b/tests/testthat/test-performance.R @@ -30,5 +30,5 @@ test_that("modify_list adds new values", { test_that("modify_list erases null elements", { res <- modify_list(testlist, testappend) expect_null(res$c) - expect_named(res, c('a', 'b', 'd')) + expect_named(res, c("a", "b", "d")) }) diff --git a/tests/testthat/test-plot-summary-api.R b/tests/testthat/test-plot-summary-api.R index 2b4704e94c..90dd397093 100644 --- a/tests/testthat/test-plot-summary-api.R +++ b/tests/testthat/test-plot-summary-api.R @@ -9,7 +9,7 @@ pg <- p + facet_grid(drv ~ cyl) test_that("layout summary - basic plot", { l <- summarise_layout(ggplot_build(p)) - empty_named_list <- list(a=1)[0] + empty_named_list <- list(a = 1)[0] expect_equal(l$panel, factor(1)) expect_equal(l$row, 1) @@ -115,10 +115,10 @@ test_that("summarise_layers", { l <- summarise_layers(ggplot_build(p)) expect_equal(l$mapping[[1]], list(x = quo(displ), y = quo(hwy)), ignore_attr = TRUE) - p2 <- p + geom_point(aes(x = displ/2, y = hwy/2)) + p2 <- p + geom_point(aes(x = displ / 2, y = hwy / 2)) l2 <- summarise_layers(ggplot_build(p2)) expect_equal(l2$mapping[[1]], list(x = quo(displ), y = quo(hwy)), ignore_attr = TRUE) # Here use _identical because the quosures are supposed to be local - expect_identical(l2$mapping[[2]], list(x = quo(displ/2), y = quo(hwy/2))) + expect_identical(l2$mapping[[2]], list(x = quo(displ / 2), y = quo(hwy / 2))) }) diff --git a/tests/testthat/test-position-collide.R b/tests/testthat/test-position-collide.R index 232725e710..5cb3d6fcd1 100644 --- a/tests/testthat/test-position-collide.R +++ b/tests/testthat/test-position-collide.R @@ -1,6 +1,6 @@ test_that("collide() checks the input data", { data <- data.frame(x = 1:4, group = 1L) - expect_snapshot_error(collide(data, width = 1, 'test', pos_stack)) + expect_snapshot_error(collide(data, width = 1, "test", pos_stack)) data$y <- 1 - expect_snapshot_warning(collide(data, width = 2, 'test', pos_stack)) + expect_snapshot_warning(collide(data, width = 2, "test", pos_stack)) }) diff --git a/tests/testthat/test-position-dodge2.R b/tests/testthat/test-position-dodge2.R index 5377f14b2d..c04fef213e 100644 --- a/tests/testthat/test-position-dodge2.R +++ b/tests/testthat/test-position-dodge2.R @@ -78,7 +78,7 @@ test_that("boxes in facetted plots keep the correct width", { ) p <- ggplot(df, aes(subgroup, value)) + - facet_wrap( ~ group) + + facet_wrap(~ group) + geom_boxplot() d <- get_layer_data(p) @@ -111,7 +111,7 @@ test_that("NA values are given their own group", { expect_equal(find_x_overlaps(df), seq_len(4)) }) -test_that("groups are different when two blocks have externall touching point",{ +test_that("groups are different when two blocks have externall touching point", { df1 <- data.frame( xmin = c(0.5, 1.5), xmax = c(1.5, 2.5) diff --git a/tests/testthat/test-position-stack.R b/tests/testthat/test-position-stack.R index 54c6b858e8..3d326c4ab0 100644 --- a/tests/testthat/test-position-stack.R +++ b/tests/testthat/test-position-stack.R @@ -1,6 +1,6 @@ test_that("data keeps its order after stacking", { df <- data_frame( - x = rep(c(1:10), 3), + x = rep(1:10, 3), var = rep(c("a", "b", "c"), 10), y = round(runif(30, 1, 5)) ) @@ -13,9 +13,9 @@ test_that("data keeps its order after stacking", { test_that("negative and positive values are handled separately", { df <- data_frame( - x = c(1,1,1,2,2), - g = c(1,2,3,1,2), - y = c(1,-1,1,2,-3) + x = c(1, 1, 1, 2, 2), + g = c(1, 2, 3, 1, 2), + y = c(1, -1, 1, 2, -3) ) p <- ggplot(df, aes(x, y, fill = factor(g))) + geom_col() dat <- get_layer_data(p) @@ -69,7 +69,7 @@ test_that("position_stack() can stack correctly when ymax is NA", { test_that("Stacking produces the expected output", { data <- data_frame( x = rep(1:4, each = 2), - category = rep(c("A","B"), 4), + category = rep(c("A", "B"), 4), value = c(0, 0, 2, 1, 3, 6, -4, 3) ) p <- ggplot(data, aes(x = x, y = value, fill = category)) + diff --git a/tests/testthat/test-position_dodge.R b/tests/testthat/test-position_dodge.R index 9107de1d92..a78614fa22 100644 --- a/tests/testthat/test-position_dodge.R +++ b/tests/testthat/test-position_dodge.R @@ -12,7 +12,7 @@ test_that("can control whether to preserve total or individual width", { test_that("position_dodge() can dodge points vertically", { - df <- data.frame(x = c(1, 2, 3, 4), y = c("a", "a", "b", "b")) + df <- data_frame0(x = c(1, 2, 3, 4), y = c("a", "a", "b", "b")) horizontal <- ggplot(df, aes(y, x, group = seq_along(x))) + geom_point(position = position_dodge(width = 1, orientation = "x")) @@ -26,7 +26,7 @@ test_that("position_dodge() can dodge points vertically", { test_that("position_dodge() can reverse the dodge order", { - df <- data.frame(x = c(1, 2, 2, 3, 3), group = c("A", "A", "B", "B", "C")) + df <- data_frame0(x = c(1, 2, 2, 3, 3), group = c("A", "A", "B", "B", "C")) # Use label as easy to track identifier p <- ggplot(df, aes(x, y = 1, fill = group, label = group)) diff --git a/tests/testthat/test-prohibited-functions.R b/tests/testthat/test-prohibited-functions.R index 278dfbd8fc..5a38efd35c 100644 --- a/tests/testthat/test-prohibited-functions.R +++ b/tests/testthat/test-prohibited-functions.R @@ -59,7 +59,7 @@ test_that("list up R files properly", { skip_on_covr() skip_on_cran() - expect_true(length(R_files) > 0) + expect_gt(length(R_files), 0) }) test_that("do not use stop()", { @@ -113,7 +113,7 @@ test_that("No new argument names use underscores", { formals <- lapply(functions, fn_fmls_names) - underscore_args <- lapply(formals, function(x) x[grep("_", x, fixed = TRUE)]) + underscore_args <- lapply(formals, grep, pattern = "_", fixed = TRUE, value = TRUE) underscore_args <- underscore_args[lengths(underscore_args) > 0] underscore_args <- underscore_args[order(names(underscore_args))] diff --git a/tests/testthat/test-qplot.R b/tests/testthat/test-qplot.R index 58e8fa1e14..3b6ba3b5be 100644 --- a/tests/testthat/test-qplot.R +++ b/tests/testthat/test-qplot.R @@ -46,7 +46,7 @@ test_that("qplot() evaluates layers in package environment", { } lifecycle::expect_deprecated( - expect_error(p <- qplot(1, 1, geom = "line"), NA) + expect_error(qplot(1, 1, geom = "line"), NA) ) }) diff --git a/tests/testthat/test-scale-binned.R b/tests/testthat/test-scale-binned.R index 31e32e9eba..1749bf98f4 100644 --- a/tests/testthat/test-scale-binned.R +++ b/tests/testthat/test-scale-binned.R @@ -59,7 +59,7 @@ test_that("binned scales can calculate breaks with reverse transformation", { expect_equal(scale$get_breaks(), 8:2) }) -test_that('binned scales can calculate breaks on dates', { +test_that("binned scales can calculate breaks on dates", { data <- seq(as.Date("2000-01-01"), as.Date("2020-01-01"), length.out = 100) @@ -74,7 +74,7 @@ test_that('binned scales can calculate breaks on dates', { ) }) -test_that('binned scales can calculate breaks on date-times', { +test_that("binned scales can calculate breaks on date-times", { data <- seq( strptime("2000-01-01", "%Y-%m-%d"), strptime("2020-01-01", "%Y-%m-%d"), diff --git a/tests/testthat/test-scale-brewer.R b/tests/testthat/test-scale-brewer.R index d14edd1a8b..987678545b 100644 --- a/tests/testthat/test-scale-brewer.R +++ b/tests/testthat/test-scale-brewer.R @@ -3,13 +3,13 @@ test_that("mid-point in diverging brewer color scale", { p <- ggplot(d) + aes(x = x, y = 1, color = x) + - scale_color_distiller(palette = 'RdBu', direction = 1, limits = c(-1, 1)) + scale_color_distiller(palette = "RdBu", direction = 1, limits = c(-1, 1)) expect_equal(get_layer_data(p)$colour, c("#B2182B", "#F7F7F7", "#2166AC")) p <- ggplot(d) + aes(x = x, y = 1, fill = x) + - scale_fill_distiller(palette = 'RdBu', direction = 1, limits = c(-1, 1)) + scale_fill_distiller(palette = "RdBu", direction = 1, limits = c(-1, 1)) expect_equal(get_layer_data(p)$fill, c("#B2182B", "#F7F7F7", "#2166AC")) }) diff --git a/tests/testthat/test-scale-date.R b/tests/testthat/test-scale-date.R index 1183fcd756..4e7fc3dbb2 100644 --- a/tests/testthat/test-scale-date.R +++ b/tests/testthat/test-scale-date.R @@ -11,7 +11,7 @@ df <- data_frame( test_that("inherits timezone from data", { if (!is.null(attr(df$time1, "tzone"))) - skip("Local time zone not available") + skip("Local time zone not available") # Local time p <- ggplot(df, aes(y = y)) + geom_point(aes(time1)) diff --git a/tests/testthat/test-scale-discrete.R b/tests/testthat/test-scale-discrete.R index 9e8eeaf717..8b6cea3e78 100644 --- a/tests/testthat/test-scale-discrete.R +++ b/tests/testthat/test-scale-discrete.R @@ -166,7 +166,7 @@ test_that("mapped_discrete vectors behaves as predicted", { test_that("palettes work for discrete scales", { - df <- data.frame(x = c("A", "B", "C"), y = 1:3) + df <- data_frame0(x = c("A", "B", "C"), y = 1:3) values <- c(1, 10, 100) p <- ggplot(df, aes(x, y)) + @@ -187,7 +187,7 @@ test_that("palettes work for discrete scales", { test_that("invalid palettes trigger errors", { - df <- data.frame(x = c("A", "B", "C"), y = 1:3) + df <- data_frame0(x = c("A", "B", "C"), y = 1:3) p <- ggplot(df, aes(x, y)) + geom_point() @@ -202,4 +202,3 @@ test_that("invalid palettes trigger errors", { "must return at least 3 values" ) }) - diff --git a/tests/testthat/test-scale-manual.R b/tests/testthat/test-scale-manual.R index 2ad47425f7..6ae719a2af 100644 --- a/tests/testthat/test-scale-manual.R +++ b/tests/testthat/test-scale-manual.R @@ -1,36 +1,37 @@ test_that("names of values used in manual scales", { - s1 <- scale_colour_manual(values = c("8" = "c", "4" = "a", "6" = "b")) - s1$train(c("4", "6", "8")) - expect_equal(s1$map(c("4", "6", "8")), c("a", "b", "c")) - - s2 <- scale_colour_manual(values = c("8" = "c", "4" = "a", "6" = "b"), na.value = NA) - s2$train(c("4", "8")) - expect_equal(s2$map(c("4", "6", "8")), c("a", NA, "c")) - expect_equal(s2$get_limits(), c("4", "8")) - - s3 <- scale_colour_manual(values = c("8" = "c", "4" = "a", "6" = "b"), na.value = "x") - s3$train(c("4", "8", NA)) - expect_equal(s3$map(c("4", "6", "8")), c("a", "x", "c")) - expect_equal(s3$get_limits(), c("4", "8", NA)) - - # Names do not match data - s <- scale_colour_manual(values = c("foo" = "x", "bar" = "y")) - s$train(c("A", "B")) - expect_snapshot_warning( - expect_equal(s$get_limits(), character()) - ) + s1 <- scale_colour_manual(values = c("8" = "c", "4" = "a", "6" = "b")) + s1$train(c("4", "6", "8")) + expect_equal(s1$map(c("4", "6", "8")), c("a", "b", "c")) + + s2 <- scale_colour_manual(values = c("8" = "c", "4" = "a", "6" = "b"), na.value = NA) + s2$train(c("4", "8")) + expect_equal(s2$map(c("4", "6", "8")), c("a", NA, "c")) + expect_equal(s2$get_limits(), c("4", "8")) + + s3 <- scale_colour_manual(values = c("8" = "c", "4" = "a", "6" = "b"), na.value = "x") + s3$train(c("4", "8", NA)) + expect_equal(s3$map(c("4", "6", "8")), c("a", "x", "c")) + expect_equal(s3$get_limits(), c("4", "8", NA)) + + # Names do not match data + s <- scale_colour_manual(values = c(foo = "x", bar = "y")) + s$train(c("A", "B")) + expect_snapshot_warning( + expect_equal(s$get_limits(), character()) + ) }) -dat <- data_frame(g = c("B","A","A")) +dat <- data_frame(g = c("B", "A", "A")) p <- ggplot(dat, aes(g, fill = g)) + geom_bar() -col <- c("A" = "red", "B" = "green", "C" = "blue") +col <- c(A = "red", B = "green", C = "blue") cols <- function(x) ggplot_build(x)$data[[1]][, "fill"] test_that("named values work regardless of order", { - fill_scale <- function(order) scale_fill_manual(values = col[order], - na.value = "black") + fill_scale <- function(order) { + scale_fill_manual(values = col[order], na.value = "black") + } # Order of value vector shouldn't matter expect_equal(cols(p + fill_scale(1:3)), c("red", "green")) @@ -54,16 +55,16 @@ test_that("insufficient values raise an error", { df <- data_frame(x = 1, y = 1:3, z = factor(c(1:2, NA), exclude = NULL)) p <- ggplot(df, aes(x, y, colour = z)) + geom_point() - expect_error(ggplot_build(p + scale_colour_manual(values = "black")), - "Insufficient values") + expect_error(ggplot_build( + p + scale_colour_manual(values = "black") + ), "Insufficient values") # Should be sufficient ggplot_build(p + scale_colour_manual(values = c("black", "black"))) }) test_that("values are matched when scale contains more unique values than are in the data", { - s <- scale_colour_manual(values = c("8" = "c", "4" = "a", - "22" = "d", "6" = "b")) + s <- scale_colour_manual(values = c("8" = "c", "4" = "a", "22" = "d", "6" = "b")) s$train(c("4", "6", "8")) expect_equal(s$map(c("4", "6", "8")), c("a", "b", "c")) }) @@ -85,7 +86,7 @@ test_that("generic scale can be used in place of aesthetic-specific scales", { test_that("named values do not match with breaks in manual scales", { s <- scale_fill_manual( - values = c("data_red" = "red", "data_black" = "black"), + values = c(data_red = "red", data_black = "black"), breaks = c("data_black", "data_red") ) s$train(c("data_black", "data_red")) diff --git a/tests/testthat/test-scales-breaks-labels.R b/tests/testthat/test-scales-breaks-labels.R index c3a314cacc..fd2fb827ca 100644 --- a/tests/testthat/test-scales-breaks-labels.R +++ b/tests/testthat/test-scales-breaks-labels.R @@ -8,9 +8,9 @@ test_that("labels match breaks, even when outside limits", { test_that("labels match breaks", { expect_error(scale_x_discrete(breaks = 1:3, labels = 1:2), - "must have the same length") + "must have the same length") expect_error(scale_x_continuous(breaks = 1:3, labels = 1:2), - "must have the same length") + "must have the same length") }) test_that("labels don't have to match null breaks", { @@ -45,7 +45,7 @@ test_that("out-of-range breaks are dropped", { expect_equal(bi$major_source, 2:4) # Limits are specified, and all breaks are out of range - sc <- scale_x_continuous(breaks = c(1,5), labels = letters[c(1,5)], limits = c(2, 4)) + sc <- scale_x_continuous(breaks = c(1, 5), labels = letters[c(1, 5)], limits = c(2, 4)) bi <- sc$break_info() expect_length(bi$labels, 0) expect_length(bi$major, 0) @@ -69,7 +69,7 @@ test_that("out-of-range breaks are dropped", { expect_equal(bi$major, c(0, 0.5, 1)) # Limits aren't specified, and all breaks are out of range of data - sc <- scale_x_continuous(breaks = c(1,5), labels = letters[c(1,5)]) + sc <- scale_x_continuous(breaks = c(1, 5), labels = letters[c(1, 5)]) sc$train_df(data_frame(x = 2:4)) bi <- sc$break_info() expect_length(bi$labels, 0) @@ -104,8 +104,7 @@ test_that("discrete labels match breaks", { expect_length(sc$get_labels(), 5) expect_equal(sc$get_labels(), letters[2:6]) - sc <- init_scale(breaks = 0:5 * 10, labels = - function(x) paste(x, "-", sep = "")) + sc <- init_scale(breaks = 0:5 * 10, labels = function(x) paste0(x, "-")) expect_equal(sc$get_labels(), c("10-", "20-", "30-", "40-", "50-")) pick_5 <- function(x) sample(x, 5) @@ -237,7 +236,7 @@ test_that("only finite or NA values for breaks for transformed scales (#871)", { test_that("minor breaks are transformed by scales", { sc <- scale_y_continuous(limits = c(1, 100), transform = "log10", - minor_breaks = c(1, 10, 100)) + minor_breaks = c(1, 10, 100)) expect_equal(sc$get_breaks_minor(), c(0, 1, 2)) }) diff --git a/tests/testthat/test-scales.R b/tests/testthat/test-scales.R index 0ba2989e39..dc3cd1d62b 100644 --- a/tests/testthat/test-scales.R +++ b/tests/testthat/test-scales.R @@ -37,15 +37,15 @@ test_that("mapping works", { expect_equal( sc$map_df(data_frame(alpha = c(-10, 11)))[[1]], - c(0, 0)) + c(0, 0) + ) }) test_that("identity scale preserves input values", { df <- data_frame(x = 1:3, z = factor(letters[1:3])) # aesthetic-specific scales - p1 <- ggplot(df, - aes(x, z, colour = z, fill = z, shape = z, size = x, alpha = x)) + + p1 <- ggplot(df, aes(x, z, colour = z, fill = z, shape = z, size = x, alpha = x)) + geom_point() + scale_colour_identity() + scale_fill_identity() + @@ -61,8 +61,7 @@ test_that("identity scale preserves input values", { expect_equal(d1$alpha, as.numeric(df$z)) # generic scales - p2 <- ggplot(df, - aes(x, z, colour = z, fill = z, shape = z, size = x, alpha = x)) + + p2 <- ggplot(df, aes(x, z, colour = z, fill = z, shape = z, size = x, alpha = x)) + geom_point() + scale_discrete_identity(aesthetics = c("colour", "fill", "shape")) + scale_continuous_identity(aesthetics = c("size", "alpha")) @@ -96,7 +95,7 @@ test_that("position scales generate after stats", { plot <- ggplot(df, aes(x)) + geom_bar() ranges <- pranges(plot) - expect_equal(ranges$x[[1]], c("1")) + expect_equal(ranges$x[[1]], "1") expect_equal(ranges$y[[1]], c(0, 3)) }) @@ -109,16 +108,20 @@ test_that("oob affects position values", { y_scale <- function(limits, oob = censor) { scale_y_continuous(limits = limits, oob = oob, expand = c(0, 0)) } - base + scale_y_continuous(limits = c(-0,5)) + base + scale_y_continuous(limits = c(-0, 5)) low_censor <- cdata(base + y_scale(c(0, 5), censor)) mid_censor <- cdata(base + y_scale(c(3, 7), censor)) handle <- GeomBar$handle_na - expect_warning(low_censor[[1]] <- handle(low_censor[[1]], list(na.rm = FALSE)), - "Removed 1 row containing missing values or values outside the scale range") - expect_warning(mid_censor[[1]] <- handle(mid_censor[[1]], list(na.rm = FALSE)), - "Removed 3 rows containing missing values or values outside the scale range") + expect_warning( + low_censor[[1]] <- handle(low_censor[[1]], list(na.rm = FALSE)), + "Removed 1 row containing missing values or values outside the scale range" + ) + expect_warning( + mid_censor[[1]] <- handle(mid_censor[[1]], list(na.rm = FALSE)), + "Removed 3 rows containing missing values or values outside the scale range" + ) low_squish <- cdata(base + y_scale(c(0, 5), squish)) mid_squish <- cdata(base + y_scale(c(3, 7), squish)) @@ -179,8 +182,10 @@ test_that("find_global searches in the right places", { testenv <- new.env(parent = globalenv()) # This should find the scale object in the package environment - expect_identical(find_global("scale_colour_hue", testenv), - ggplot2::scale_colour_hue) + expect_identical( + find_global("scale_colour_hue", testenv), + ggplot2::scale_colour_hue + ) # Set an object with the same name in the environment testenv$scale_colour_hue <- "foo" @@ -190,8 +195,10 @@ test_that("find_global searches in the right places", { # If we search in the empty env, we should end up with the object # from the ggplot2 namespace - expect_identical(find_global("scale_colour_hue", emptyenv()), - ggplot2::scale_colour_hue) + expect_identical( + find_global("scale_colour_hue", emptyenv()), + ggplot2::scale_colour_hue + ) }) test_that("scales warn when transforms introduces non-finite values", { @@ -379,7 +386,7 @@ test_that("All scale_colour_*() have their American versions", { color_scale_exports <- grep("export\\(scale_color_.*\\)", exports, value = TRUE) expect_equal( colour_scale_exports, - sub("color", "colour", color_scale_exports) + sub("color", "colour", color_scale_exports, fixed = TRUE) ) }) diff --git a/tests/testthat/test-sec-axis.R b/tests/testthat/test-sec-axis.R index 7530c4a70c..649b74ea1c 100644 --- a/tests/testthat/test-sec-axis.R +++ b/tests/testthat/test-sec-axis.R @@ -14,7 +14,7 @@ test_that("sec_axis checks the user input", { p <- ggplot(mtcars) + geom_point(aes(disp, mpg)) + scale_y_continuous(sec.axis = ~sin(.)) expect_snapshot_error(ggplot_build(p)) - p <- ggplot(mtcars) + geom_point(aes(disp, mpg)) + scale_y_continuous(sec.axis = ~sin(./100)) + p <- ggplot(mtcars) + geom_point(aes(disp, mpg)) + scale_y_continuous(sec.axis = ~sin(. / 100)) expect_silent(ggplot_build(p)) }) @@ -43,7 +43,7 @@ test_that("sec_axis() works with subtraction", { p <- ggplot(foo, aes(x, y)) + geom_point() + scale_y_continuous( - sec.axis = sec_axis(~1-.) + sec.axis = sec_axis(~1 - .) ) scale <- get_panel_scales(p)$y expect_equal(scale$sec_name(), scale$name) @@ -248,8 +248,7 @@ test_that("sec_axis() respects custom transformations", { magnify_trans_log(interval_low = 0.5, interval_high = 1, reducer = 0.5, reducer2 = 8), breaks = c(0.001, 0.01, 0.1, 0.5, 0.6, 0.7, 0.8, 0.9, 1), limits = c(0.001, 1), sec.axis = sec_axis( - transform = - ~ . * (1 / 2), breaks = c(0.001, 0.01, 0.1, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5) + transform = ~ . * (1 / 2), breaks = c(0.001, 0.01, 0.1, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5) ) ) + theme_linedraw() ) @@ -260,12 +259,10 @@ test_that("sec_axis works with date/time/datetime scales", { withr::local_locale(c(LC_TIME = "C")) df <- data_frame( - dx = seq(as.POSIXct("2012-02-29 12:00:00", - tz = "UTC", - format = "%Y-%m-%d %H:%M:%S" - ), - length.out = 10, by = "4 hour" - ), + dx = seq(as.POSIXct( + "2012-02-29 12:00:00", + tz = "UTC", format = "%Y-%m-%d %H:%M:%S" + ), length.out = 10, by = "4 hour"), price = seq(20, 200000, length.out = 10) ) df$date <- as.Date(df$dx) @@ -383,7 +380,7 @@ test_that("sec_axis() works for power transformations (monotonicity test doesn't test_that("discrete scales can have secondary axes", { - data <- data.frame(x = c("A", "B", "C"), y = c("D", "E", "F")) + data <- data_frame0(x = c("A", "B", "C"), y = c("D", "E", "F")) p <- ggplot(data, aes(x, y)) + geom_point() + scale_x_discrete(sec.axis = dup_axis(labels = c("foo", "bar", "baz"))) + @@ -407,7 +404,7 @@ test_that("n.breaks is respected by secondary axes (#4483)", { ggplot(data.frame(x = c(0, 10)), aes(x, x)) + scale_y_continuous( n.breaks = 11, - sec.axis = sec_axis(~.x*100) + sec.axis = sec_axis(~.x * 100) ) ) diff --git a/tests/testthat/test-stat-align.R b/tests/testthat/test-stat-align.R index 457992e747..fabe0774a2 100644 --- a/tests/testthat/test-stat-align.R +++ b/tests/testthat/test-stat-align.R @@ -42,7 +42,7 @@ test_that("alignment adjusts per panel", { # Here, x-range is large, so adjustment should be larger ld <- get_layer_data(p + geom_area(aes(fill = f))) - expect_equal(diff(ld$x[1:2]), 1/6, tolerance = 1e-4) + expect_equal(diff(ld$x[1:2]), 1 / 6, tolerance = 1e-4) # Here, x-ranges are smaller, so adjustment should be smaller instead of # considering the data as a whole diff --git a/tests/testthat/test-stat-bin.R b/tests/testthat/test-stat-bin.R index 9b55054604..f1ca72631e 100644 --- a/tests/testthat/test-stat-bin.R +++ b/tests/testthat/test-stat-bin.R @@ -19,7 +19,7 @@ test_that("stat_bin works in both directions", { x$flipped_aes <- NULL y$flipped_aes <- NULL - expect_identical(x, flip_data(y, TRUE)[,names(x)]) + expect_identical(x, flip_data(y, TRUE)[, names(x)]) }) test_that("bins specifies the number of bins", { @@ -78,13 +78,13 @@ test_that("fuzzy breaks are used when cutting", { }) test_that("breaks are transformed by the scale", { - df <- data_frame(x = rep(1:4, 1:4)) - base <- ggplot(df, aes(x)) + geom_histogram(breaks = c(1, 2.5, 4)) + df <- data_frame(x = rep(1:4, 1:4)) + base <- ggplot(df, aes(x)) + geom_histogram(breaks = c(1, 2.5, 4)) - out1 <- get_layer_data(base) - out2 <- get_layer_data(base + scale_x_sqrt()) - expect_equal(out1$xmin, c(1, 2.5)) - expect_equal(out2$xmin, sqrt(c(1, 2.5))) + out1 <- get_layer_data(base) + out2 <- get_layer_data(base + scale_x_sqrt()) + expect_equal(out1$xmin, c(1, 2.5)) + expect_equal(out2$xmin, sqrt(c(1, 2.5))) }) test_that("geom_histogram() can be drawn over a 0-width range (#3043)", { @@ -184,7 +184,7 @@ test_that("closed left or right", { res <- comp_bin(dat, binwidth = 10, boundary = 5, pad = FALSE, closed = "left") expect_identical(res$count, c(1, 1)) res <- comp_bin(dat, binwidth = 10, boundary = 0, pad = FALSE, closed = "left") - expect_identical(res$count, c(2)) + expect_identical(res$count, 2) res <- comp_bin(dat, binwidth = 5, boundary = 0, pad = FALSE, closed = "left") expect_identical(res$count, c(1, 1)) }) @@ -230,19 +230,19 @@ test_that("stat_count throws error when both x and y aesthetic present", { test_that("stat_count preserves x order for continuous and discrete", { # x is numeric b <- ggplot_build(ggplot(mtcars, aes(carb)) + geom_bar()) - expect_identical(b$data[[1]]$x, c(1,2,3,4,6,8)) - expect_identical(b$data[[1]]$y, c(7,10,3,10,1,1)) + expect_identical(b$data[[1]]$x, c(1, 2, 3, 4, 6, 8)) + expect_identical(b$data[[1]]$y, c(7, 10, 3, 10, 1, 1)) # x is factor where levels match numeric order mtcars$carb2 <- factor(mtcars$carb) b <- ggplot_build(ggplot(mtcars, aes(carb2)) + geom_bar()) expect_identical(b$data[[1]]$x, mapped_discrete(1:6)) - expect_identical(b$data[[1]]$y, c(7,10,3,10,1,1)) + expect_identical(b$data[[1]]$y, c(7, 10, 3, 10, 1, 1)) # x is factor levels differ from numeric order - mtcars$carb3 <- factor(mtcars$carb, levels = c(4,1,2,3,6,8)) + mtcars$carb3 <- factor(mtcars$carb, levels = c(4, 1, 2, 3, 6, 8)) b <- ggplot_build(ggplot(mtcars, aes(carb3)) + geom_bar()) expect_identical(b$data[[1]]$x, mapped_discrete(1:6)) - expect_identical(b$layout$panel_params[[1]]$x$get_labels(), c("4","1","2","3","6","8")) - expect_identical(b$data[[1]]$y, c(10,7,10,3,1,1)) + expect_identical(b$layout$panel_params[[1]]$x$get_labels(), c("4", "1", "2", "3", "6", "8")) + expect_identical(b$data[[1]]$y, c(10, 7, 10, 3, 1, 1)) }) diff --git a/tests/testthat/test-stat-bin2d.R b/tests/testthat/test-stat-bin2d.R index 54d95679c9..bae13d0277 100644 --- a/tests/testthat/test-stat-bin2d.R +++ b/tests/testthat/test-stat-bin2d.R @@ -39,8 +39,7 @@ test_that("breaks override binwidth", { test_that("breaks are transformed by the scale", { df <- data_frame(x = c(1, 10, 100, 1000), y = 0:3) base <- ggplot(df, aes(x, y)) + - stat_bin_2d( - breaks = list(x = c(5, 50, 500), y = c(0.5, 1.5, 2.5))) + stat_bin_2d(breaks = list(x = c(5, 50, 500), y = c(0.5, 1.5, 2.5))) out1 <- get_layer_data(base) out2 <- get_layer_data(base + scale_x_log10()) diff --git a/tests/testthat/test-stat-contour.R b/tests/testthat/test-stat-contour.R index bab39b7b6d..8b1e8dcc73 100644 --- a/tests/testthat/test-stat-contour.R +++ b/tests/testthat/test-stat-contour.R @@ -27,14 +27,14 @@ test_that("contouring irregularly spaced data works", { # we're testing for set equality here because contour lines are not # guaranteed to start and end at the same point on all architectures d <- get_layer_data(p) - d4 <- d[d$level == 4,] + d4 <- d[d$level == 4, ] expect_equal(nrow(d4), 7) expect_setequal(d4$x, c(4, 10, 100, 700)) - expect_setequal(d4$y, c(2, 8/3, 4/3)) - d8 <- d[d$level == 8,] + expect_setequal(d4$y, c(2, 8 / 3, 4 / 3)) + d8 <- d[d$level == 8, ] expect_equal(nrow(d8), 7) expect_setequal(d8$x, c(8, 10, 100, 300)) - expect_setequal(d8$y, c(2, 20/9, 16/9)) + expect_setequal(d8$y, c(2, 20 / 9, 16 / 9)) }) test_that("contour breaks can be set manually and by bins and binwidth and a function", { @@ -97,6 +97,5 @@ test_that("stat_contour() removes duplicated coordinates", { new <- layer$stat$setup_data(transform(df, group = 1)), "has duplicated" ) - expect_equal(new, df[1:4,], ignore_attr = TRUE) + expect_equal(new, df[1:4, ], ignore_attr = TRUE) }) - diff --git a/tests/testthat/test-stat-density.R b/tests/testthat/test-stat-density.R index 0894fc2944..4a99b20e3a 100644 --- a/tests/testthat/test-stat-density.R +++ b/tests/testthat/test-stat-density.R @@ -113,7 +113,7 @@ test_that("stat_density works in both directions", { x$flipped_aes <- NULL y$flipped_aes <- NULL - expect_identical(x, flip_data(y, TRUE)[,names(x)]) + expect_identical(x, flip_data(y, TRUE)[, names(x)]) p <- ggplot(mpg) + stat_density() expect_snapshot_error(ggplot_build(p)) diff --git a/tests/testthat/test-stat-density2d.R b/tests/testthat/test-stat-density2d.R index 2ecd50a8cb..9fec1224ef 100644 --- a/tests/testthat/test-stat-density2d.R +++ b/tests/testthat/test-stat-density2d.R @@ -8,10 +8,10 @@ test_that("uses scale limits, not data limits", { # Check that the contour data goes beyond data range. # The specific values below are sort of arbitrary; but they go beyond the range # of the data - expect_true(min(ret$x) < 1.2) - expect_true(max(ret$x) > 5.8) - expect_true(min(ret$y) < 8) - expect_true(max(ret$y) > 35) + expect_lt(min(ret$x), 1.2) + expect_gt(max(ret$x), 5.8) + expect_lt(min(ret$y), 8) + expect_gt(max(ret$y), 35) }) test_that("stat_density2d can produce contour and raster data", { @@ -35,8 +35,8 @@ test_that("stat_density2d can produce contour and raster data", { expect_true("density" %in% names(d_raster)) expect_true("ndensity" %in% names(d_raster)) expect_true("count" %in% names(d_raster)) - expect_true(unique(d_raster$level) == 1) - expect_true(unique(d_raster$piece) == 1) + expect_identical(unique(d_raster$level), 1) + expect_identical(unique(d_raster$piece), 1) # stat_density_2d() and stat_density_2d_filled() produce identical # density output with `contour = FALSE` diff --git a/tests/testthat/test-stat-ecdf.R b/tests/testthat/test-stat-ecdf.R index ce839bb3c4..63a390106e 100644 --- a/tests/testthat/test-stat-ecdf.R +++ b/tests/testthat/test-stat-ecdf.R @@ -9,7 +9,7 @@ test_that("stat_ecdf works in both directions", { x$flipped_aes <- NULL y$flipped_aes <- NULL - expect_identical(x, flip_data(y, TRUE)[,names(x)]) + expect_identical(x, flip_data(y, TRUE)[, names(x)]) p <- ggplot(mpg) + stat_ecdf() expect_snapshot_error(ggplot_build(p)) diff --git a/tests/testthat/test-stat-function.R b/tests/testthat/test-stat-function.R index 483578d97f..f506061959 100644 --- a/tests/testthat/test-stat-function.R +++ b/tests/testthat/test-stat-function.R @@ -23,25 +23,25 @@ test_that("uses scale limits, not data limits", { }) test_that("works in plots without any data", { - f <- function(x) 2*x + f <- function(x) 2 * x # default limits, 0 to 1 base <- ggplot() + geom_function(fun = f, n = 6) ret <- get_layer_data(base) expect_identical(ret$x, seq(0, 1, length.out = 6)) - expect_identical(ret$y, 2*ret$x) + expect_identical(ret$y, 2 * ret$x) # manually set limits with xlim() base <- ggplot() + xlim(0, 2) + geom_function(fun = f, n = 6) ret <- get_layer_data(base) expect_identical(ret$x, seq(0, 2, length.out = 6)) - expect_identical(ret$y, 2*ret$x) + expect_identical(ret$y, 2 * ret$x) # manually set limits with xlim argument base <- ggplot() + geom_function(fun = f, n = 6, xlim = c(0, 2)) ret <- get_layer_data(base) expect_identical(ret$x, seq(0, 2, length.out = 6)) - expect_identical(ret$y, 2*ret$x) + expect_identical(ret$y, 2 * ret$x) # mapping of color via aes() works base <- ggplot() + @@ -49,7 +49,7 @@ test_that("works in plots without any data", { scale_color_manual(values = c(fun = "#D55E00")) ret <- get_layer_data(base) expect_identical(ret$x, seq(0, 1, length.out = 6)) - expect_identical(ret$y, 2*ret$x) + expect_identical(ret$y, 2 * ret$x) expect_identical(ret$colour, rep("#D55E00", 6)) }) @@ -133,7 +133,11 @@ test_that("works with formula syntax", { test_that("Warn when drawing multiple copies of the same function", { df <- data_frame(x = 1:3, y = letters[1:3]) p <- ggplot(df, aes(x, color = y)) + stat_function(fun = identity) - f <- function() {pdf(NULL); print(p); dev.off()} + f <- function() { + pdf(NULL) + print(p) + dev.off() + } expect_warning(f(), "Multiple drawing groups") }) diff --git a/tests/testthat/test-stat-ydensity.R b/tests/testthat/test-stat-ydensity.R index 3b70fc7673..ea0b7ec3d7 100644 --- a/tests/testthat/test-stat-ydensity.R +++ b/tests/testthat/test-stat-ydensity.R @@ -8,7 +8,7 @@ test_that("`drop = FALSE` preserves groups with 1 observations", { df <- head(data_frame0( x = factor(rep(1:2, each = 4)), y = rep(1:2, 4), - g = rep(c("A", "A", "B", 'B'), 2) + g = rep(c("A", "A", "B", "B"), 2) ), -1) p <- ggplot(df, mapping = aes(x, y, fill = g)) diff --git a/tests/testthat/test-theme.R b/tests/testthat/test-theme.R index 36ad577c65..7a88b96f28 100644 --- a/tests/testthat/test-theme.R +++ b/tests/testthat/test-theme.R @@ -16,8 +16,8 @@ test_that("theme argument splicing works", { test_that("modifying theme element properties with + operator works", { # Changing a "leaf node" works - t <- theme_grey() + theme(axis.title.x = element_text(colour = 'red', margin = margin())) - expect_identical(t$axis.title.x, element_text(colour = 'red', margin = margin(), vjust = 1)) + t <- theme_grey() + theme(axis.title.x = element_text(colour = "red", margin = margin())) + expect_identical(t$axis.title.x, element_text(colour = "red", margin = margin(), vjust = 1)) # Make sure the theme class didn't change or get dropped expect_true(is.theme(t)) # Make sure the element class didn't change or get dropped @@ -25,12 +25,12 @@ test_that("modifying theme element properties with + operator works", { expect_true(inherits(t$axis.title.x, "element_text")) # Modifying an intermediate node works - t <- theme_grey() + theme(axis.title = element_text(colour = 'red')) - expect_identical(t$axis.title, element_text(colour = 'red')) + t <- theme_grey() + theme(axis.title = element_text(colour = "red")) + expect_identical(t$axis.title, element_text(colour = "red")) # Modifying a root node changes only the specified properties - t <- theme_grey() + theme(text = element_text(colour = 'red')) - expect_identical(t$text$colour, 'red') + t <- theme_grey() + theme(text = element_text(colour = "red")) + expect_identical(t$text$colour, "red") expect_identical(t$text$family, theme_grey()$text$family) expect_identical(t$text$face, theme_grey()$text$face) expect_identical(t$text$size, theme_grey()$text$size) @@ -42,8 +42,8 @@ test_that("modifying theme element properties with + operator works", { expect_identical(t$axis.text.y, element_blank()) # Adding a non-blank element to an element_blank() replaces it - t <- t + theme(axis.text.y = element_text(colour = 'red')) - expect_identical(t$axis.text.y, element_text(colour = 'red')) + t <- t + theme(axis.text.y = element_text(colour = "red")) + expect_identical(t$axis.text.y, element_text(colour = "red")) # Adding empty theme() has no effect t <- theme_grey() + theme() @@ -56,13 +56,13 @@ test_that("adding theme object to ggplot object with + operator works", { ## test with complete theme p <- ggplot(data.frame(x = 1:3), aes(x, x)) + geom_point() + theme_grey() p <- p + theme(axis.title = element_text(size = 20)) - expect_true(p$theme$axis.title$size == 20) + expect_identical(p$theme$axis.title$size, 20) # Should update specified properties, but not reset other properties - p <- p + theme(text = element_text(colour = 'red')) - expect_true(p$theme$text$colour == 'red') + p <- p + theme(text = element_text(colour = "red")) + expect_identical(p$theme$text$colour, "red") tt <- theme_grey()$text - tt$colour <- 'red' + tt$colour <- "red" expect_true(tt$inherit.blank) tt$inherit.blank <- FALSE expect_identical(p$theme$text, tt) @@ -70,11 +70,11 @@ test_that("adding theme object to ggplot object with + operator works", { ## test without complete theme p <- ggplot(data.frame(x = 1:3), aes(x, x)) + geom_point() p <- p + theme(axis.title = element_text(size = 20)) - expect_true(p$theme$axis.title$size == 20) + expect_identical(p$theme$axis.title$size, 20) # Should update specified properties, but not reset other properties - p <- p + theme(text = element_text(colour = 'red')) - expect_true(p$theme$text$colour == 'red') + p <- p + theme(text = element_text(colour = "red")) + expect_identical(p$theme$text$colour, "red") expect_null(p$theme$text$family) expect_null(p$theme$text$face) expect_null(p$theme$text$size) @@ -100,14 +100,14 @@ test_that("adding theme object to ggplot object with + operator works", { test_that("replacing theme elements with %+replace% operator works", { # Changing a "leaf node" works - t <- theme_grey() %+replace% theme(axis.title.x = element_text(colour = 'red')) - expect_identical(t$axis.title.x, element_text(colour = 'red')) + t <- theme_grey() %+replace% theme(axis.title.x = element_text(colour = "red")) + expect_identical(t$axis.title.x, element_text(colour = "red")) # Make sure the class didn't change or get dropped expect_true(is.theme(t)) # Changing an intermediate node works - t <- theme_grey() %+replace% theme(axis.title = element_text(colour = 'red')) - expect_identical(t$axis.title, element_text(colour = 'red')) + t <- theme_grey() %+replace% theme(axis.title = element_text(colour = "red")) + expect_identical(t$axis.title, element_text(colour = "red")) # Descendent is unchanged expect_identical(t$axis.title.x, theme_grey()$axis.title.x) @@ -119,11 +119,11 @@ test_that("replacing theme elements with %+replace% operator works", { }) test_that("calculating theme element inheritance works", { - t <- theme_grey() + theme(axis.title = element_text(colour = 'red')) + t <- theme_grey() + theme(axis.title = element_text(colour = "red")) # Check that properties are passed along from axis.title to axis.title.x - e <- calc_element('axis.title.x', t) - expect_identical(e$colour, 'red') + e <- calc_element("axis.title.x", t) + expect_identical(e$colour, "red") expect_false(is.null(e$family)) expect_false(is.null(e$face)) expect_false(is.null(e$size)) @@ -132,14 +132,14 @@ test_that("calculating theme element inheritance works", { t <- theme_grey(base_size = 12) + theme(axis.title = element_text(size = rel(0.5))) + theme(axis.title.x = element_text(size = rel(0.5))) - e <- calc_element('axis.title', t) + e <- calc_element("axis.title", t) expect_identical(e$size, 6) - ex <- calc_element('axis.title.x', t) + ex <- calc_element("axis.title.x", t) expect_identical(ex$size, 3) # Check that a theme_blank in a parent node gets passed along to children t <- theme_grey() + theme(text = element_blank()) - expect_identical(calc_element('axis.title.x', t), element_blank()) + expect_identical(calc_element("axis.title.x", t), element_blank()) # Check that inheritance from derived class works element_dummyrect <- function(dummy) { # like element_rect but w/ dummy argument @@ -180,8 +180,8 @@ test_that("calculating theme element inheritance works", { theme <- theme_gray() + theme(strip.text = element_blank(), strip.text.x = element_text(inherit.blank = TRUE)) - e1 <- ggplot2:::calc_element("strip.text.x", theme) - e2 <- ggplot2:::calc_element("strip.text", theme) + e1 <- calc_element("strip.text.x", theme) + e2 <- calc_element("strip.text", theme) expect_identical(e1, e2) # Check that rel units are computed appropriately @@ -199,20 +199,20 @@ test_that("complete and non-complete themes interact correctly with each other", # The 'complete' attribute of t1 + t2 is the OR of their 'complete' attributes. # But for _element properties_, the one on the right modifies the one on the left. - t <- theme_bw() + theme(text = element_text(colour = 'red')) + t <- theme_bw() + theme(text = element_text(colour = "red")) expect_true(attr(t, "complete")) - expect_equal(t$text$colour, 'red') + expect_equal(t$text$colour, "red") # A complete theme object (like theme_bw) always trumps a non-complete theme object - t <- theme(text = element_text(colour = 'red')) + theme_bw() + t <- theme(text = element_text(colour = "red")) + theme_bw() expect_true(attr(t, "complete")) expect_equal(t$text$colour, theme_bw()$text$colour) # Adding two non-complete themes: the one on the right modifies the one on the left. - t <- theme(text = element_text(colour = 'blue')) + - theme(text = element_text(colour = 'red')) + t <- theme(text = element_text(colour = "blue")) + + theme(text = element_text(colour = "red")) expect_false(attr(t, "complete")) - expect_equal(t$text$colour, 'red') + expect_equal(t$text$colour, "red") }) test_that("complete and non-complete themes interact correctly with ggplot objects", { @@ -220,32 +220,34 @@ test_that("complete and non-complete themes interact correctly with ggplot objec # Check that adding two theme successive theme objects to a ggplot object # works like adding the two theme object to each other - p <- ggplot_build(base + theme_bw() + theme(text = element_text(colour = 'red'))) + p <- ggplot_build(base + theme_bw() + theme(text = element_text(colour = "red"))) expect_true(attr(p$plot$theme, "complete")) # Compare the theme objects, after sorting the items, because item order can differ pt <- p$plot$theme - tt <- theme_bw() + theme(text = element_text(colour = 'red')) + tt <- theme_bw() + theme(text = element_text(colour = "red")) pt <- pt[order(names(pt))] tt <- tt[order(names(tt))] expect_identical(pt, tt) - p <- ggplot_build(base + theme(text = element_text(colour = 'red')) + theme_bw()) + p <- ggplot_build(base + theme(text = element_text(colour = "red")) + theme_bw()) expect_true(attr(p$plot$theme, "complete")) # Compare the theme objects, after sorting the items, because item order can differ pt <- p$plot$theme - tt <- theme(text = element_text(colour = 'red')) + theme_bw() + tt <- theme(text = element_text(colour = "red")) + theme_bw() pt <- pt[order(names(pt))] tt <- tt[order(names(tt))] expect_identical(pt, tt) - p <- ggplot_build(base + theme(text = element_text(colour = 'red', face = 'italic'))) + p <- ggplot_build(base + theme(text = element_text(colour = "red", face = "italic"))) expect_equal(p$plot$theme$text$colour, "red") expect_equal(p$plot$theme$text$face, "italic") - p <- ggplot_build(base + - theme(text = element_text(colour = 'red')) + - theme(text = element_text(face = 'italic'))) + p <- ggplot_build( + base + + theme(text = element_text(colour = "red")) + + theme(text = element_text(face = "italic")) + ) expect_equal(p$plot$theme$text$colour, "red") expect_equal(p$plot$theme$text$face, "italic") }) @@ -313,7 +315,7 @@ test_that("element tree can be modified", { expect_snapshot_error(ggplotGrob(p1)) # inheritance and final calculation of novel element works - final_theme <- ggplot2:::plot_theme(p, theme_gray()) + final_theme <- plot_theme(p, theme_gray()) e1 <- calc_element("blablabla", final_theme) e2 <- calc_element("text", final_theme) expect_identical(e1$family, e2$family) @@ -619,7 +621,7 @@ test_that("complete_theme completes a theme", { # Visual tests ------------------------------------------------------------ test_that("aspect ratio is honored", { - df <- cbind(data_frame(x = 1:8, y = 1:8, f = gl(2,4)), expand.grid(f1 = 1:2, f2 = 1:2, rep = 1:2)) + df <- cbind(data_frame(x = 1:8, y = 1:8, f = gl(2, 4)), expand.grid(f1 = 1:2, f2 = 1:2, rep = 1:2)) p <- ggplot(df, aes(x, y)) + geom_point() + theme_test() + @@ -639,13 +641,13 @@ test_that("aspect ratio is honored", { p_a + facet_wrap(~f) ) expect_doppelganger("height is 3 times width, 2 column facets", - p_a + facet_grid(.~f) + p_a + facet_grid(. ~ f) ) expect_doppelganger("height is 3 times width, 2 row facets", - p_a + facet_grid(f~.) + p_a + facet_grid(f ~ .) ) expect_doppelganger("height is 3 times width, 2x2 facets", - p_a + facet_grid(f1~f2) + p_a + facet_grid(f1 ~ f2) ) }) @@ -701,22 +703,22 @@ test_that("axes can be styled independently", { scale_x_continuous(sec.axis = dup_axis()) + scale_y_continuous(sec.axis = dup_axis()) + theme( - axis.title.x.top = element_text(colour = 'red'), - axis.title.x.bottom = element_text(colour = 'green'), - axis.title.y.left = element_text(colour = 'blue'), - axis.title.y.right = element_text(colour = 'yellow'), - axis.text.x.top = element_text(colour = 'red'), - axis.text.x.bottom = element_text(colour = 'green'), - axis.text.y.left = element_text(colour = 'blue'), - axis.text.y.right = element_text(colour = 'yellow'), - axis.ticks.x.top = element_line(colour = 'red'), - axis.ticks.x.bottom = element_line(colour = 'green'), - axis.ticks.y.left = element_line(colour = 'blue'), - axis.ticks.y.right = element_line(colour = 'yellow'), - axis.line.x.top = element_line(colour = 'red'), - axis.line.x.bottom = element_line(colour = 'green'), - axis.line.y.left = element_line(colour = 'blue'), - axis.line.y.right = element_line(colour = 'yellow') + axis.title.x.top = element_text(colour = "red"), + axis.title.x.bottom = element_text(colour = "green"), + axis.title.y.left = element_text(colour = "blue"), + axis.title.y.right = element_text(colour = "yellow"), + axis.text.x.top = element_text(colour = "red"), + axis.text.x.bottom = element_text(colour = "green"), + axis.text.y.left = element_text(colour = "blue"), + axis.text.y.right = element_text(colour = "yellow"), + axis.ticks.x.top = element_line(colour = "red"), + axis.ticks.x.bottom = element_line(colour = "green"), + axis.ticks.y.left = element_line(colour = "blue"), + axis.ticks.y.right = element_line(colour = "yellow"), + axis.line.x.top = element_line(colour = "red"), + axis.line.x.bottom = element_line(colour = "green"), + axis.line.y.left = element_line(colour = "blue"), + axis.line.y.right = element_line(colour = "yellow") ) expect_doppelganger("axes_styling", plot) }) @@ -824,7 +826,7 @@ test_that("Legends can on all sides of the plot with custom justification", { test_that("Strips can render custom elements", { element_test <- function(...) { el <- element_text(...) - class(el) <- c('element_test', 'element_text', 'element') + class(el) <- c("element_test", "element_text", "element") el } element_grob.element_test <- function(element, label = "", x = NULL, y = NULL, ...) { @@ -871,7 +873,7 @@ test_that("legend margins are correct when using relative key sizes", { vertical <- p + guides( colour = guide_colourbar(theme = theme(legend.key.height = unit(1, "null"))), - shape = guide_legend(theme = theme(legend.key.height = unit(1/3, "null"))) + shape = guide_legend(theme = theme(legend.key.height = unit(1 / 3, "null"))) ) + theme( legend.box.margin = margin(t = 5, b = 10, unit = "mm"), legend.margin = margin(t = 10, b = 5, unit = "mm") @@ -881,7 +883,7 @@ test_that("legend margins are correct when using relative key sizes", { horizontal <- p + guides( colour = guide_colourbar(theme = theme(legend.key.width = unit(1, "null"))), - shape = guide_legend(theme = theme(legend.key.width = unit(1/3, "null"))) + shape = guide_legend(theme = theme(legend.key.width = unit(1 / 3, "null"))) ) + theme( legend.position = "top", legend.box.margin = margin(l = 5, r = 10, unit = "mm"), diff --git a/tests/testthat/test-utilities.R b/tests/testthat/test-utilities.R index a602eb22c7..4fdde0284e 100644 --- a/tests/testthat/test-utilities.R +++ b/tests/testthat/test-utilities.R @@ -22,7 +22,7 @@ test_that("finite_cases.data.frame", { }) test_that("add_group", { - data <- data_frame(f=letters[7:9], x=1:3, y=4:6, group=c(1, -1, 1)) + data <- data_frame(f = letters[7:9], x = 1:3, y = 4:6, group = c(1, -1, 1)) expect_true(has_groups(add_group(data[2:4]))) # explicit group column expect_true(has_groups(add_group(data[1:3]))) # discrete column expect_false(has_groups(add_group(data[2:3]))) # no group or discrete column diff --git a/vignettes/articles/faq-annotation.Rmd b/vignettes/articles/faq-annotation.Rmd index b92e93e9e1..0ff891d09f 100644 --- a/vignettes/articles/faq-annotation.Rmd +++ b/vignettes/articles/faq-annotation.Rmd @@ -23,7 +23,7 @@ knitr::opts_chunk$set( fig.asp = 0.618, fig.width = 6, out.width = "80%" - ) +) ``` diff --git a/vignettes/articles/faq-axes.Rmd b/vignettes/articles/faq-axes.Rmd index a6996dbe36..423ae41562 100644 --- a/vignettes/articles/faq-axes.Rmd +++ b/vignettes/articles/faq-axes.Rmd @@ -21,7 +21,8 @@ knitr::opts_chunk$set( comment = "#>", fig.asp = 0.618, fig.width = 6, - out.width = "80%") + out.width = "80%" +) ``` ## Label placement @@ -196,7 +197,7 @@ ggplot(sales, aes(x = interaction(quarter, year), y = value, group = 1)) + plot.margin = margin(1, 1, 3, 1, "lines"), axis.title.x = element_blank(), axis.text.x = element_blank() - ) + + ) + annotate(geom = "text", x = seq_len(nrow(sales)), y = 8, label = sales$quarter, size = 3) + annotate(geom = "text", x = c(2.5, 6.5), y = 6, label = unique(sales$year), size = 4) ``` @@ -218,7 +219,7 @@ ggplot(sales, aes(x = interaction(quarter, year), y = value)) + plot.margin = margin(1, 1, 3, 1, "lines"), axis.title.x = element_blank(), axis.text.x = element_blank() - ) + ) ``` If it's undesirable to have the bars flush against the edges of the plot, a similar result can be achieved by leveraging faceting and removing the space between facets to create the appearance of a single plot. @@ -236,7 +237,7 @@ ggplot(sales, aes(x = quarter, y = value)) + panel.spacing = unit(0, "lines"), strip.background = element_blank(), strip.placement = "outside" - ) + + ) + labs(x = NULL) ``` @@ -454,7 +455,7 @@ ggplot(mpg, aes(x = cty^2, y = log(hwy, base = 10))) + theme( axis.title.x = ggtext::element_markdown(), axis.title.y = ggtext::element_markdown() - ) + ) ``` diff --git a/vignettes/articles/faq-bars.Rmd b/vignettes/articles/faq-bars.Rmd index 3cbacf4d79..825cec4c53 100644 --- a/vignettes/articles/faq-bars.Rmd +++ b/vignettes/articles/faq-bars.Rmd @@ -25,7 +25,7 @@ knitr::opts_chunk$set( fig.asp = 0.618, fig.width = 6, out.width = "80%" - ) +) ``` ## Colors @@ -391,7 +391,7 @@ In order to obtain a bar plot with limited y-axis, you need to instead set the l #| of drive train. The y-axis starts at 20, and all bars touch the x-axis." ggplot(mpg, aes(x = drv)) + geom_bar() + - coord_cartesian(ylim = c(20,110)) + coord_cartesian(ylim = c(20, 110)) ``` This is, indeed, a deceiving plot. diff --git a/vignettes/articles/faq-customising.Rmd b/vignettes/articles/faq-customising.Rmd index 0112d64627..e6d59ab2a3 100644 --- a/vignettes/articles/faq-customising.Rmd +++ b/vignettes/articles/faq-customising.Rmd @@ -23,7 +23,7 @@ knitr::opts_chunk$set( fig.asp = 0.618, fig.width = 6, out.width = "80%" - ) +) ``` ## Legends @@ -98,7 +98,7 @@ ggplot(mpg, aes(x = hwy, y = cty, color = drv)) + theme( legend.position = "bottom", legend.spacing.x = unit(1.0, "cm") - ) + ) ``` For vertical legends changing `legend.spacing.y` changes the space between the legend title and the keys, but not between the keys, e.g. see the large space between the legend title and keys. @@ -126,7 +126,7 @@ ggplot(mpg, aes(x = hwy, y = cty, color = drv)) + theme( legend.key.size = unit(1.5, "cm"), legend.key = element_rect(color = NA, fill = NA) - ) + ) ``` Note that the legend title is no longer aligned with the keys with this approach. @@ -172,7 +172,7 @@ ggplot(mpg, aes(x = hwy, y = cty, color = drv)) + labels = c("4" = "4-wheel drive", "f" = "Front-wheel drive", "r" = "Rear-wheel drive") - ) + ) ``` diff --git a/vignettes/articles/faq-faceting.Rmd b/vignettes/articles/faq-faceting.Rmd index bb7112edbb..7e27dead2d 100644 --- a/vignettes/articles/faq-faceting.Rmd +++ b/vignettes/articles/faq-faceting.Rmd @@ -21,7 +21,8 @@ knitr::opts_chunk$set( comment = "#>", fig.asp = 0.618, fig.width = 6, - out.width = "80%") + out.width = "80%" +) ``` ## Panes @@ -322,11 +323,13 @@ With the following you can customize the facet labels first with `as_labeller()` #| the left of each panel. The two y-axes have different ranges." ggplot(df, aes(x = year, y = price)) + geom_smooth() + - facet_wrap(~ country, ncol = 1, scales = "free_y", - labeller = as_labeller( - c(US = "US Dollars (USD)", Japan = "Japanese Yens (JPY)")), - strip.position = "left" - ) + + facet_wrap( + ~ country, ncol = 1, scales = "free_y", + strip.position = "left", + labeller = as_labeller( + c(US = "US Dollars (USD)", Japan = "Japanese Yens (JPY)") + ) + ) + scale_x_continuous(breaks = 2011:2020) + labs(y = NULL) + theme(strip.background = element_blank(), strip.placement = "outside") diff --git a/vignettes/articles/faq-reordering.Rmd b/vignettes/articles/faq-reordering.Rmd index d820c7a50e..e9bfa61958 100644 --- a/vignettes/articles/faq-reordering.Rmd +++ b/vignettes/articles/faq-reordering.Rmd @@ -25,7 +25,7 @@ knitr::opts_chunk$set( fig.asp = 0.618, fig.width = 6, out.width = "80%" - ) +) ``` ## Bar plots diff --git a/vignettes/extending-ggplot2.Rmd b/vignettes/extending-ggplot2.Rmd index adac6896ea..fb883f7360 100644 --- a/vignettes/extending-ggplot2.Rmd +++ b/vignettes/extending-ggplot2.Rmd @@ -514,9 +514,10 @@ Sometimes you just want to make a small modification to an existing geom. In thi #| gallon, for 234 cars. The convex hull of all the points is marked by a #| polygon with no fill." GeomPolygonHollow <- ggproto("GeomPolygonHollow", GeomPolygon, - default_aes = aes(colour = "black", fill = NA, linewidth = 0.5, linetype = 1, - alpha = NA) + default_aes = aes( + colour = "black", fill = NA, linewidth = 0.5, linetype = 1, alpha = NA ) +) geom_chull <- function(mapping = NULL, data = NULL, position = "identity", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...) { @@ -718,15 +719,19 @@ render <- function(panels, layout, x_scales, y_scales, ranges, coord, data, if (params$horizontal) { # Put panels in matrix and convert to a gtable panels <- matrix(panels, ncol = 2) - panel_table <- gtable::gtable_matrix("layout", panels, - widths = unit(c(1, 1), "null"), heights = unit(1, "null"), clip = "on") + panel_table <- gtable::gtable_matrix( + "layout", panels, + widths = unit(c(1, 1), "null"), heights = unit(1, "null"), clip = "on" + ) # Add spacing according to theme panel_spacing <- calc_element("panel.spacing.x", theme) panel_table <- gtable::gtable_add_col_space(panel_table, panel_spacing) } else { panels <- matrix(panels, ncol = 1) - panel_table <- gtable::gtable_matrix("layout", panels, - widths = unit(1, "null"), heights = unit(c(1, 1), "null"), clip = "on") + panel_table <- gtable::gtable_matrix( + "layout", panels, + widths = unit(1, "null"), heights = unit(c(1, 1), "null"), clip = "on" + ) panel_spacing <- if (is.null(theme$panel.spacing.y)) { theme$panel.spacing } else { @@ -738,43 +743,50 @@ render <- function(panels, layout, x_scales, y_scales, ranges, coord, data, panel_table$layout$name <- paste0("panel-", c(1, 2)) # Construct the axes - axes <- render_axes(ranges[1], ranges[1], coord, theme, - transpose = TRUE) + axes <- render_axes(ranges[1], ranges[1], coord, theme, transpose = TRUE) # Add axes around each panel panel_pos_h <- panel_cols(panel_table)$l panel_pos_v <- panel_rows(panel_table)$t axis_width_l <- unit(grid::convertWidth( - grid::grobWidth(axes$y$left[[1]]), "cm", TRUE), "cm") + grid::grobWidth(axes$y$left[[1]]), "cm", TRUE + ), "cm") axis_width_r <- unit(grid::convertWidth( - grid::grobWidth(axes$y$right[[1]]), "cm", TRUE), "cm") + grid::grobWidth(axes$y$right[[1]]), "cm", TRUE + ), "cm") ## We do it reverse so we don't change the position of panels when we add axes for (i in rev(panel_pos_h)) { panel_table <- gtable::gtable_add_cols(panel_table, axis_width_r, i) - panel_table <- gtable::gtable_add_grob(panel_table, - rep(axes$y$right, length(panel_pos_v)), t = panel_pos_v, l = i + 1, - clip = "off") + panel_table <- gtable::gtable_add_grob( + panel_table, rep(axes$y$right, length(panel_pos_v)), + t = panel_pos_v, l = i + 1, clip = "off" + ) panel_table <- gtable::gtable_add_cols(panel_table, axis_width_l, i - 1) - panel_table <- gtable::gtable_add_grob(panel_table, - rep(axes$y$left, length(panel_pos_v)), t = panel_pos_v, l = i, - clip = "off") + panel_table <- gtable::gtable_add_grob( + panel_table, rep(axes$y$left, length(panel_pos_v)), + t = panel_pos_v, l = i, clip = "off" + ) } ## Recalculate as gtable has changed panel_pos_h <- panel_cols(panel_table)$l panel_pos_v <- panel_rows(panel_table)$t axis_height_t <- unit(grid::convertHeight( - grid::grobHeight(axes$x$top[[1]]), "cm", TRUE), "cm") + grid::grobHeight(axes$x$top[[1]]), "cm", TRUE + ), "cm") axis_height_b <- unit(grid::convertHeight( - grid::grobHeight(axes$x$bottom[[1]]), "cm", TRUE), "cm") + grid::grobHeight(axes$x$bottom[[1]]), "cm", TRUE + ), "cm") for (i in rev(panel_pos_v)) { panel_table <- gtable::gtable_add_rows(panel_table, axis_height_b, i) - panel_table <- gtable::gtable_add_grob(panel_table, - rep(axes$x$bottom, length(panel_pos_h)), t = i + 1, l = panel_pos_h, - clip = "off") + panel_table <- gtable::gtable_add_grob( + panel_table, rep(axes$x$bottom, length(panel_pos_h)), + t = i + 1, l = panel_pos_h, clip = "off" + ) panel_table <- gtable::gtable_add_rows(panel_table, axis_height_t, i - 1) - panel_table <- gtable::gtable_add_grob(panel_table, - rep(axes$x$top, length(panel_pos_h)), t = i, l = panel_pos_h, - clip = "off") + panel_table <- gtable::gtable_add_grob( + panel_table, rep(axes$x$top, length(panel_pos_h)), + t = i, l = panel_pos_h, clip = "off" + ) } panel_table } @@ -898,15 +910,19 @@ FacetTrans <- ggproto("FacetTrans", Facet, if (params$horizontal) { # Put panels in matrix and convert to a gtable panels <- matrix(panels, ncol = 2) - panel_table <- gtable::gtable_matrix("layout", panels, - widths = unit(c(1, 1), "null"), heights = unit(1, "null"), clip = "on") + panel_table <- gtable::gtable_matrix( + "layout", panels, + widths = unit(c(1, 1), "null"), heights = unit(1, "null"), clip = "on" + ) # Add spacing according to theme panel_spacing <- calc_element("panel.spacing.x", theme) panel_table <- gtable::gtable_add_col_space(panel_table, panel_spacing) } else { panels <- matrix(panels, ncol = 1) - panel_table <- gtable::gtable_matrix("layout", panels, - widths = unit(1, "null"), heights = unit(c(1, 1), "null"), clip = "on") + panel_table <- gtable::gtable_matrix( + "layout", panels, + widths = unit(1, "null"), heights = unit(c(1, 1), "null"), clip = "on" + ) panel_spacing <- calc_element("panel.spacing.y", theme) panel_table <- gtable::gtable_add_row_space(panel_table, panel_spacing) } @@ -914,14 +930,12 @@ FacetTrans <- ggproto("FacetTrans", Facet, panel_table$layout$name <- paste0("panel-", c(1, 2)) # Construct the axes - axes <- render_axes(ranges[1], ranges, coord, theme, - transpose = TRUE) + axes <- render_axes(ranges[1], ranges, coord, theme, transpose = TRUE) # Add axes around each panel grobWidths <- function(x) { unit(vapply(x, function(x) { - grid::convertWidth( - grid::grobWidth(x), "cm", TRUE) + grid::convertWidth(grid::grobWidth(x), "cm", TRUE) }, numeric(1)), "cm") } panel_pos_h <- panel_cols(panel_table)$l @@ -932,61 +946,76 @@ FacetTrans <- ggproto("FacetTrans", Facet, if (params$horizontal) { for (i in rev(seq_along(panel_pos_h))) { panel_table <- gtable::gtable_add_cols(panel_table, axis_width_r[i], panel_pos_h[i]) - panel_table <- gtable::gtable_add_grob(panel_table, - axes$y$right[i], t = panel_pos_v, l = panel_pos_h[i] + 1, - clip = "off") + panel_table <- gtable::gtable_add_grob( + panel_table, axes$y$right[i], + t = panel_pos_v, l = panel_pos_h[i] + 1, clip = "off" + ) panel_table <- gtable::gtable_add_cols(panel_table, axis_width_l[i], panel_pos_h[i] - 1) - panel_table <- gtable::gtable_add_grob(panel_table, - axes$y$left[i], t = panel_pos_v, l = panel_pos_h[i], - clip = "off") + panel_table <- gtable::gtable_add_grob( + panel_table, axes$y$left[i], + t = panel_pos_v, l = panel_pos_h[i], clip = "off" + ) } } else { - panel_table <- gtable::gtable_add_cols(panel_table, axis_width_r[1], panel_pos_h) - panel_table <- gtable::gtable_add_grob(panel_table, - axes$y$right, t = panel_pos_v, l = panel_pos_h + 1, - clip = "off") - panel_table <- gtable::gtable_add_cols(panel_table, axis_width_l[1], panel_pos_h - 1) - panel_table <- gtable::gtable_add_grob(panel_table, - axes$y$left, t = panel_pos_v, l = panel_pos_h, - clip = "off") - } + panel_table <- gtable::gtable_add_cols(panel_table, axis_width_r[1], panel_pos_h) + panel_table <- gtable::gtable_add_grob( + panel_table, axes$y$right, + t = panel_pos_v, l = panel_pos_h + 1, clip = "off" + ) + panel_table <- gtable::gtable_add_cols(panel_table, axis_width_l[1], panel_pos_h - 1) + panel_table <- gtable::gtable_add_grob( + panel_table, axes$y$left, + t = panel_pos_v, l = panel_pos_h, clip = "off" + ) + } ## Recalculate as gtable has changed panel_pos_h <- panel_cols(panel_table)$l panel_pos_v <- panel_rows(panel_table)$t axis_height_t <- unit(grid::convertHeight( - grid::grobHeight(axes$x$top[[1]]), "cm", TRUE), "cm") + grid::grobHeight(axes$x$top[[1]]), "cm", TRUE + ), "cm") axis_height_b <- unit(grid::convertHeight( - grid::grobHeight(axes$x$bottom[[1]]), "cm", TRUE), "cm") + grid::grobHeight(axes$x$bottom[[1]]), "cm", TRUE + ), "cm") for (i in rev(panel_pos_v)) { panel_table <- gtable::gtable_add_rows(panel_table, axis_height_b, i) - panel_table <- gtable::gtable_add_grob(panel_table, - rep(axes$x$bottom, length(panel_pos_h)), t = i + 1, l = panel_pos_h, - clip = "off") + panel_table <- gtable::gtable_add_grob( + panel_table, rep(axes$x$bottom, length(panel_pos_h)), + t = i + 1, l = panel_pos_h, clip = "off" + ) panel_table <- gtable::gtable_add_rows(panel_table, axis_height_t, i - 1) - panel_table <- gtable::gtable_add_grob(panel_table, - rep(axes$x$top, length(panel_pos_h)), t = i, l = panel_pos_h, - clip = "off") + panel_table <- gtable::gtable_add_grob( + panel_table, rep(axes$x$top, length(panel_pos_h)), + t = i, l = panel_pos_h, clip = "off" + ) } # Add strips strips <- render_strips( x = data.frame(name = c("Original", paste0("Transformed (", params$trans$name, ")"))), - labeller = label_value, theme = theme) + labeller = label_value, theme = theme + ) panel_pos_h <- panel_cols(panel_table)$l panel_pos_v <- panel_rows(panel_table)$t strip_height <- unit(grid::convertHeight( - grid::grobHeight(strips$x$top[[1]]), "cm", TRUE), "cm") + grid::grobHeight(strips$x$top[[1]]), + "cm", TRUE + ), "cm") for (i in rev(seq_along(panel_pos_v))) { panel_table <- gtable::gtable_add_rows(panel_table, strip_height, panel_pos_v[i] - 1) if (params$horizontal) { - panel_table <- gtable::gtable_add_grob(panel_table, strips$x$top, - t = panel_pos_v[i], l = panel_pos_h, clip = "off") + panel_table <- gtable::gtable_add_grob( + panel_table, strips$x$top, + t = panel_pos_v[i], l = panel_pos_h, clip = "off" + ) } else { - panel_table <- gtable::gtable_add_grob(panel_table, strips$x$top[i], - t = panel_pos_v[i], l = panel_pos_h, clip = "off") + panel_table <- gtable::gtable_add_grob( + panel_table, strips$x$top[i], + t = panel_pos_v[i], l = panel_pos_h, clip = "off" + ) } } @@ -1006,7 +1035,7 @@ Enough talk - lets see if our new and powerful faceting extension works: #| titled 'original' and the right panel is titled 'transformed (sqrt)'. On the #| right panel, the miles per gallon are displayed on a square root #| transformed scale." -ggplot(mtcars, aes(x = hp, y = mpg)) + geom_point() + facet_trans('sqrt') +ggplot(mtcars, aes(x = hp, y = mpg)) + geom_point() + facet_trans("sqrt") ``` ## Extending existing facet function @@ -1018,11 +1047,14 @@ As the rendering part of a facet class is often the difficult development step, #| the price of about 10.000 diamonds in every panel. The panels are titled 1 #| to 9 and show different points, but are visually similar." -facet_bootstrap <- function(n = 9, prop = 0.2, nrow = NULL, ncol = NULL, - scales = "fixed", shrink = TRUE, strip.position = "top") { +facet_bootstrap <- function( + n = 9, prop = 0.2, nrow = NULL, ncol = NULL, + scales = "fixed", shrink = TRUE, strip.position = "top") { - facet <- facet_wrap(~.bootstrap, nrow = nrow, ncol = ncol, scales = scales, - shrink = shrink, strip.position = strip.position) + facet <- facet_wrap( + ~.bootstrap, nrow = nrow, ncol = ncol, scales = scales, + shrink = shrink, strip.position = strip.position + ) facet$params$n <- n facet$params$prop <- prop ggproto(NULL, FacetBootstrap, diff --git a/vignettes/profiling.Rmd b/vignettes/profiling.Rmd index a0a77340df..f6e4984052 100644 --- a/vignettes/profiling.Rmd +++ b/vignettes/profiling.Rmd @@ -34,7 +34,7 @@ profile ``` ```{r, eval=FALSE, include=FALSE} -saveRDS(profile, file.path('profilings', paste0(packageVersion('ggplot2'), '.rds'))) +saveRDS(profile, file.path("profilings", paste0(packageVersion("ggplot2"), ".rds"))) ``` In general, a minimal plot is used so that profiles are focused on low-level,