library(ggplot2)
Exercise 3.1: Convex hull Stat
- Create a new stat called
stat_chull that returns the convex hull of a set of points
- The default geom for this new stat can be
GeomPolygon so when stat_chull() is added to a scatter plot, it will draw a border around all points
# fill the XXX in the code below
StatChull <- ggproto("StatChull", Stat,
compute_group = function(data, scales) {
data[chull(data$x, data$y), , drop = FALSE]
},
required_aes = XXX)
stat_chull <- function(mapping = NULL, data = NULL, geom = XXX,
position = "identity", na.rm = FALSE, show.legend = NA,
inherit.aes = TRUE, ...) {
layer(
stat = XXX, data = data, mapping = mapping, geom = geom,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, ...)
)
}
ggplot(cars, aes(speed, dist)) +
geom_point() +
stat_chull(fill = "transparent", color = "black")

Exercise 3.2: geom_point from scratch
- Code your own
geom_point called geom_simple_point
# fill the XXX in the code below
GeomSimplePoint <- ggproto("GeomSimplePoint", Geom,
required_aes = XXX
default_aes = aes(shape = 19, colour = "black"),
draw_panel = function(data, panel_params, coord) {
coords <- coord$transform(data, panel_params)
grid::pointsGrob(
coords$x, XXX,
pch = coords$shape,
gp = grid::gpar(col = coords$colour)
)
}
)
geom_simple_point <- function(mapping = NULL, data = NULL, stat = "identity",
position = "identity", na.rm = FALSE, show.legend = NA,
inherit.aes = TRUE, ...) {
layer(
geom = XXX, mapping = mapping, data = data, stat = stat,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, ...)
)
}
ggplot(cars, aes(speed, dist)) +
geom_simple_point()
