對于后面的資料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()或我們有替代解決方案?提前感謝您的幫助。
uj5u.com熱心網友回復:
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)

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/435707.html
上一篇:Laravel5.2中的獨特作業
