'Is there a R package to make ggplot2's geom_path() smoothed?

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.



Solution 1:[1]

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))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Allan Cameron