|
| 1 | +#' Jitter-dodge points to align them with a boxplot including fill aesthetic |
| 2 | +#' |
| 3 | +#' @family position adjustments |
| 4 | +#' @param width degree of jitter in x direction. Defaults to 40\% of the |
| 5 | +#' resolution of the data. |
| 6 | +#' @param height degree of jitter in y direction. Defaults to 40\% of the |
| 7 | +#' resolution of the data |
| 8 | +#' @export |
| 9 | +#' @examples |
| 10 | +#' dsub <- diamonds[ sample(1:nrow(diamonds), 1000), ] |
| 11 | +#' ggplot(dsub, aes(x=cut, y=carat, fill=clarity)) + |
| 12 | +#' geom_boxplot(outlier.size=0) + |
| 13 | +#' geom_point( pch=21, position=position_jitterdodge() ) |
| 14 | +position_jitterdodge <- function (width = NULL, height = NULL) { |
| 15 | + PositionJitterDodge$new(width = width, height = height) |
| 16 | +} |
| 17 | + |
| 18 | +#' @rdname position_jitterdodge |
| 19 | +#' @export |
| 20 | +position_jd <- position_jitterdodge |
| 21 | + |
| 22 | +PositionJitterDodge <- proto(Position, { |
| 23 | + objname <- "jitterdodge" |
| 24 | + |
| 25 | + adjust <- function(., data) { |
| 26 | + |
| 27 | + if (empty(data)) return(data.frame()) |
| 28 | + check_required_aesthetics(c("x", "y", "fill"), names(data), "position_jitterdodge") |
| 29 | + |
| 30 | + ## Workaround to avoid this warning: |
| 31 | + ## ymax not defined: adjusting position using y instead |
| 32 | + if (!("ymax" %in% names(data))) { |
| 33 | + data$ymax <- data$y |
| 34 | + } |
| 35 | + |
| 36 | + ## Adjust the x transformation based on the number of 'fill' variables |
| 37 | + nfill <- length( levels(data$fill) ) |
| 38 | + |
| 39 | + if (is.null(.$width)) .$width <- resolution(data$x, zero = FALSE) * 0.4 |
| 40 | + if (is.null(.$height)) .$height <- resolution(data$y, zero = FALSE) * 0.4 |
| 41 | + |
| 42 | + trans_x <- NULL |
| 43 | + trans_y <- NULL |
| 44 | + if(.$width > 0) { |
| 45 | + trans_x <- function(x) jitter(x, amount = .$width / (nfill + 2)) |
| 46 | + } |
| 47 | + if(.$height > 0) { |
| 48 | + trans_y <- function(x) jitter(x, amount = .$height) |
| 49 | + } |
| 50 | + |
| 51 | + ## dodge, then jitter |
| 52 | + data <- collide(data, 0.75, .$my_name(), pos_dodge, check.width = FALSE) |
| 53 | + transform_position(data, trans_x, trans_y) |
| 54 | + } |
| 55 | + |
| 56 | +}) |
0 commit comments