geom_area 图的平滑数据

eme*_*hex 5 r ggplot2 tidyverse

我有看起来像这样的数据:

df <- tibble(
    x = 1:20,
    y = c(4, 4, 2, 1, 8, 3, 4, 2, 8, 2, 2, 2, 2, 6, 1, 7, 8, 9, 9, 2)
)
Run Code Online (Sandbox Code Playgroud)

图形化,它看起来像这样:

df %>% 
    ggplot(aes(x, y)) + 
    geom_area()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

但图表真的很刺耳。我如何将锯齿状边缘平滑成这样的:

在此处输入图片说明

谢谢!

eme*_*hex 8

扩展 Axeman 的评论:可以通过span参数控制平滑。

示例 1:

df %>% 
    ggplot(aes(x, y)) + 
    # original, delete if desired
    geom_area(alpha = 1/2) + 
    stat_smooth(
        geom = 'area', method = 'loess', span = 1/3,
        alpha = 1/2, fill = "red") + 
    labs(title = "Smooth with `span = 1/3`")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

示例 2:

df %>% 
    ggplot(aes(x, y)) + 
    geom_area(alpha = 1/2) + 
    # original, delete if desired
    stat_smooth(
        geom = 'area', method = 'loess', span = 7/10,
        alpha = 1/2, fill = "blue") + 
    labs(title = "Smooth with `span = 7/10`")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明