如何使 geom_path 在连接的散点图中平滑?

Bru*_*oto 1 r ggplot2 geom

我想做一个这样的图表:

具有平滑路径的绘图

geom_path()只是将点连接起来,没有任何变换。

我知道可以通过样条变换来管理它,但我只是想要一个像curvature = 0.1让它变得简单的论点。

All*_*ron 8

用样条线做到这一点确实不是很难。您可以使用一个简单的函数来代替包:

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)
}
Run Code Online (Sandbox Code Playgroud)

这允许:

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")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


使用的数据

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")
Run Code Online (Sandbox Code Playgroud)