1

I would like to make a chart like this:

plot with smoothed path

But geom_path() just connects the points without any transformation.

I know that it's possible to manage it with spline transformations, but I just wanted an argument like curvature = 0.1 to make it simple.

tjebo
  • 21,977
  • 7
  • 58
  • 94
Bruno Mioto
  • 382
  • 1
  • 10

1 Answers1

8

It's really not terribly difficult to do this with splines. Instead of a package, you could have a simple function:

smooth_it <- function(x, y, n = 1000, method = "natural") 
{
  t <- seq_along(x)
  new_t <- seq(min(t), max(t), length.out = n)
  new_x <- spline(t, x, xout = new_t, method = method)$y
  new_y <- spline(t, y, xout = new_t, method = method)$y
  data.frame(t = new_t, x = new_x, y = new_y)
}

This allows:

ggplot(df, aes(x, y)) +
   geom_path(data = smooth_it(df$x, df$y), size = 1,
             aes(color = factor(LETTERS[floor(t / 4) + 1]),
                 group = factor(floor(t))),
             arrow = arrow(type = "closed", 
                           length = unit(4, "mm"), angle = 30)) +
   theme_light() +
   theme(legend.position = "none")

enter image description here


Data used

set.seed(6)

df <- data.frame(x = runif(12), 
                 y = runif(12), 
                 group = rep(c("A", "B", "C"), each = 4))
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • can you try to do this with ggforce? I tried with no success – Mossa May 12 '22 at 19:14
  • 1
    No, it uses b splines where there points act as control points, rather than points on the path. I have a couple of different smoothing algorithms I considered adding as stat layers in the `geomtextpath` package - maybe I should include them in the next version. Surprisingly unusual use case though. – Allan Cameron May 12 '22 at 19:47
  • Yeah, but my groups are not symmetrical. Everything goes well, but not the groups :/ – Bruno Mioto May 13 '22 at 03:47
  • @BrunoMioto if you post some data I could show you how – Allan Cameron May 13 '22 at 07:23