Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions R/geom-hex.R
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
GeomHex <- ggproto("GeomHex", Geom,
draw_group = function(self, data, panel_params, coord, lineend = "butt",
linejoin = "mitre", linemitre = 10) {
data <- fix_linewidth(data, snake_class(self))
if (empty(data)) {
return(zeroGrob())
}
data <- fix_linewidth(data, snake_class(self))

# Get hex sizes
if (!is.null(data$width)) {
Expand All @@ -25,13 +25,12 @@ GeomHex <- ggproto("GeomHex", Geom,
dy <- resolution(data$y, FALSE, TRUE) / sqrt(3) / 2 * 1.15
}

hexC <- hexbin::hexcoords(dx, dy, n = 1)

n <- nrow(data)
hexC <- hexbin::hexcoords(dx, dy, n = n)

hexdata <- data[rep(seq_len(n), each = 6), c("x", "y")]
hexdata$x <- rep.int(hexC$x, n) + hexdata$x
hexdata$y <- rep.int(hexC$y, n) + hexdata$y
hexdata <- vec_rep_each(data[c("x", "y", "radius")], times = 6L)
hexdata$x <- hexC$x * hexdata$radius + hexdata$x
hexdata$y <- hexC$y * hexdata$radius + hexdata$y

coords <- coord$transform(hexdata, panel_params)

Expand All @@ -58,6 +57,7 @@ GeomHex <- ggproto("GeomHex", Geom,
fill = from_theme(fill %||% col_mix(ink, paper)),
linewidth = from_theme(borderwidth),
linetype = from_theme(bordertype),
radius = 1,
alpha = NA
),

Expand Down Expand Up @@ -99,5 +99,8 @@ GeomHex <- ggproto("GeomHex", Geom,
#' # Or by specifying the width of the bins
#' d + geom_hex(binwidth = c(1, 1000))
#' d + geom_hex(binwidth = c(.1, 500))
#'
#' # The hexagons can be scaled by tuning the radius aesthetic
#' d + geom_hex(aes(radius = after_stat(ncount)))
#' }
geom_hex <- make_constructor(GeomHex, stat = 'binhex')
4 changes: 4 additions & 0 deletions man/geom_hex.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

60 changes: 60 additions & 0 deletions tests/testthat/_snaps/geom-hex/hexes-with-different-sizes.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
11 changes: 11 additions & 0 deletions tests/testthat/test-geom-hex.R
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@ test_that("bin size are picked up from stat", {
geom_hex(aes(x = x, y = y), binwidth = c(0.1, 0.1)) +
coord_cartesian(xlim = c(-1, 1), ylim = c(-1, 1))
)

expect_doppelganger(
"hexes with different sizes",
ggplot(data.frame(x = 1:3, y = 0, r = (1:3)/6)) +
geom_hex(
aes(x = x, y = y, radius = r),
stat = "identity"
) +
coord_cartesian(xlim = c(0, 4), y = c(-1, 1))
)

})

test_that("geom_hex works in non-linear coordinate systems", {
Expand Down