0

对于后面的数据df和绘图,我希望能够平滑线条,尤其是下图中蓝色矩形标记的尖角部分:

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

在此处输入图像描述

使用ggalt::geom_xspline(spline_shape=0.3, size=1, alpha=0.7, color='red'),我得到了平滑线,但填充区域并不完美(如您所见,它填充了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')

在此处输入图像描述

如何填充曲线下的区域,例如由创建的曲线geom_xspline()或我们有替代解决方案?提前感谢您的帮助。

4

1 回答 1

1

stat_smooth()这是使用withgeom = "area"而不是geom_xspline()和 usingcoord_cartesian设置绘图限制的替代方法:

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)

reprex 包创建于 2022-03-01 (v2.0.1)

于 2022-03-02T03:03:04.763 回答