Home > database >  How to fill area under a curve created by geom_xspline
How to fill area under a curve created by geom_xspline

Time:03-02

For the follow data df and plot, I hope to smooth the line, especially for the sharp corners parts marked by the blue rectangles in the figure below:

df <- structure(list(date = c("2022-2-1", "2022-2-2", "2022-2-3", "2022-2-4", 
"2022-2-5", "2022-2-6", "2022-2-7", "2022-2-8", "2022-2-9", "2022-2-10", 
"2022-2-11", "2022-2-12", "2022-2-13", "2022-2-14", "2022-2-15", 
"2022-2-16", "2022-2-17"), pct_change = c(4, 4, 4.04, 4.04, 4.04, 
4.44, 4.88, 4.62, 4.8, 5.2, 4.7, 5.06, 4.56, 4.8, 4.32, 4.02, 
4.01)), class = "data.frame", row.names = c(NA, -17L))

df1 <- df %>% 
  mutate_at(vars(-date), funs(./100))
df1 %>% 
  ggplot(aes(x=as.POSIXct(date), y=pct_change))   
  geom_line(size=1, alpha=0.7, color='red')  
  geom_hline(yintercept=c(min(df1$pct_change), max(df1$pct_change)), linetype='solid', col='black')

enter image description here

With ggalt::geom_xspline(spline_shape=0.3, size=1, alpha=0.7, color='red'), I get the smoothed line, but the filled area is not perfect (as you see, it filled the area under the original curve plotted by geom_line(size=1, alpha=0.7, color='red').

library(ggalt)
df1 %>% 
  ggplot(aes(x=as.POSIXct(date), y=pct_change))   
  # geom_line(size=1, alpha=0.7, color='red')  
  geom_xspline(spline_shape=0.3, size=1, alpha=0.7, color='red')  
  geom_ribbon(aes(ymin = min(pct_change), ymax = pct_change), fill = 'red', alpha=0.3, position = "identity")  
  # ggforce::stat_bspline(geom = "area", alpha = 0.3, color='red')  
  geom_hline(yintercept=c(min(df1$pct_change), max(df1$pct_change)), linetype='solid', col='black')

enter image description here

How do I fill the area under a curve such as one created by geom_xspline() or we have alternative solution to this? Thanks for your help at advance.

CodePudding user response:

Here's an alternative using stat_smooth() with geom = "area" instead of geom_xspline(), and using coord_cartesian to set plot limits:

library(tidyverse)

df1 %>% 
  ggplot(aes(x=as.POSIXct(date), y=pct_change))   
  stat_smooth(
    geom = "area", 
    size = 1,
    fill = "red", 
    color = "red", 
    alpha = 0.3, 
    span = .3
  )  
  coord_cartesian(ylim = c(.04, .0525), expand = FALSE)

Created on 2022-03-01 by the reprex package (v2.0.1)

  • Related