Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Helper stat for geom_area() #4850

Closed
hadley opened this issue May 17, 2022 · 3 comments · Fixed by #4889
Closed

Helper stat for geom_area() #4850

hadley opened this issue May 17, 2022 · 3 comments · Fixed by #4889

Comments

@hadley
Copy link
Member

hadley commented May 17, 2022

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)

@yutannihilation
Copy link
Member

I too feel geom_area() really needs something like this.

A related (but a bit different) issue was #2883, and here's my attempt at that time: https://gist.github.com/yutannihilation/2d3851adc874a02f42914f1655329c71 (it seems this won't work now)

@teunbrand
Copy link
Collaborator

Also spotted in the wild today: https://stackoverflow.com/q/72663399

@thomasp85
Copy link
Member

yeah, I feel we have discussed this before and I'm in favour too... I have a hard time believing this has any drawbacks at all

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants