Skip to content

Helper stat for geom_area() #4850

Closed
@hadley

Description

@hadley

I realised it would be pretty easy for us to automatically handle non-aligned data. Sketch of approach below

library(ggplot2)

df <- tibble::tribble(
  ~g, ~x, ~y,
  "a", 1, 2,
  "a", 3, 5,
  "a", 5, 1,
  "b", 2, 3,
  "b", 4, 6,
  "b", 6, 7
)
ggplot(df, aes(x, y, colour = g)) + geom_line()

ggplot(df, aes(x, y, fill = g)) + geom_area()

all_x <- sort(unique(df$x))

completed <- df |> 
  split(df$g) |> 
  lapply(function(grp) {
    y_fun <- approxfun(grp$x, grp$y, yleft = 0, yright = 0)
    
    data.frame(
      g = grp$g[[1]],
      x = all_x,
      y = y_fun(all_x))
  }) |> 
  dplyr::bind_rows()

ggplot(completed, aes(x, y, fill = g)) + geom_area()

Created on 2022-05-17 by the reprex package (v2.0.1)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions