Skip to content

Instantly share code, notes, and snippets.

@steveharoz
Last active February 16, 2022 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steveharoz/c7ed54a3786962054ddc00879630b8ce to your computer and use it in GitHub Desktop.
Save steveharoz/c7ed54a3786962054ddc00879630b8ce to your computer and use it in GitHub Desktop.
Endpoint stat for ggplot
StatEndpoint <- ggproto("StatEndpoint", Stat,
compute_group = function(data, scales) {
# sort by x so indexing is meaningful
data = arrange(data, x)
# grab only the first and last row
data[c(1,nrow(data)),]
},
required_aes = c("x", "y")
)
stat_endpoint <- function(mapping = NULL, data = NULL, geom = "point",
position = "identity", na.rm = FALSE, show.legend = NA,
inherit.aes = TRUE, ...) {
layer(
stat = StatEndpoint, data = data, mapping = mapping, geom = geom,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, ...)
)
}
geom_line_with_endpoint <- function(..., line.params = list(), endpoint.params = list()) {
params <- list(...)
line.params <- modifyList(params, line.params)
endpoint.params <- modifyList(params, endpoint.params)
line <- do.call("geom_line", modifyList(
list(),
line.params)
)
endpoints <- do.call("stat_endpoint", modifyList(
list(size = 5), # our defaults
endpoint.params)
)
list(line, endpoints)
}
# Create data
tibble(
g = rep(c('A','B'), each = 50),
z = rnorm(length(g))
) |>
group_by(g) |>
mutate(
y = cumsum(z),
x = row_number() + g %in% 'B' # offset a bit
) %>%
ungroup() -> tbl
tbl |>
ggplot(aes(x=x,y=y,group=g,color=g)) +
geom_line_with_endpoint()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment