diff --git a/R/stat-waffle.R b/R/stat-waffle.R index ae539e7..82e6ebd 100644 --- a/R/stat-waffle.R +++ b/R/stat-waffle.R @@ -115,6 +115,7 @@ StatWaffle <- ggplot2::ggproto( x = seq_len((ceiling(sum(.x[["values"]]) / params$n_rows)))#, # stringsAsFactors = FALSE ) -> tdf + tdf <- snake_sort_grid(tdf) parts_vec <- c(parts_vec, rep(NA, nrow(tdf)-length(parts_vec))) colour_vec <- c(colour_vec, rep(NA, nrow(tdf)-length(colour_vec))) diff --git a/R/utils.r b/R/utils.r index 9430486..15cef42 100644 --- a/R/utils.r +++ b/R/utils.r @@ -88,6 +88,14 @@ insert_unit <- function (x, values, after = length(x)) { } +# order an expand.grid alternatingly, providing a better layout for waffle +snake_sort_grid <- function(grid){ + y <- grid[[1]] + x <- grid[[2]] + o <- order(x, ifelse(x%%2 > 0, y, -y)) + grid[o,] +} + # Name ggplot grid object # Convenience function to name grid objects # diff --git a/R/waffle.R b/R/waffle.R index 2436bb0..17f31f4 100644 --- a/R/waffle.R +++ b/R/waffle.R @@ -120,6 +120,9 @@ waffle <- function(parts, rows=10, keep=TRUE, xlab=NULL, title=NULL, colors=NA, # setup the data frame for geom_rect dat <- expand.grid(y = 1:rows, x = seq_len(pad + (ceiling(sum(parts) / rows)))) + # order the grid snake wise... + dat <- snake_sort_grid(dat) + # add NAs if needed to fill in the "rectangle" dat$value <- c(parts_vec, rep(NA, nrow(dat) - length(parts_vec)))