R语言 如何平滑ggplot中的线条?

soat7uwm  于 2023-01-15  发布在  其他
关注(0)|答案(2)|浏览(188)

我想重现下图,但线条要更平滑:

使得这些线类似于下图:

到目前为止,我已经尝试了以下方法,但我只得到了趋势,而不是平滑两个序列:

plot_fig4 <- ggplot(fig4, aes(x=dias))+
  geom_line(aes(y=complete_preds_means), color="#9a6584", size=0.5)+
  geom_line(aes(y=contrafact), colour="#000000", size=0.5) + 
  geom_line(aes(y=complete_preds_means), method = "lm", formula=y~spline(x,21))+
  geom_ribbon(aes(ymin=complete_preds_lower, ymax=complete_preds_upper), fill="#9a6584", alpha=0.2)

我的数据:

structure(list(dias = structure(c(19052, 19053, 19054, 19055, 
19056, 19057, 19058, 19059, 19060, 19061, 19062, 19063, 19064, 
19065, 19066, 19067, 19068, 19069, 19070, 19071), class = "Date"), 
    complete_preds_means = c(341.07434, 381.59167, 455.47815, 
    485.05597, 527.60876, 562.63965, 602.48975, 624.663, 626.5637, 
    527.2239, 420.71643, 389.30804, 378.74396, 366.61548, 361.36566, 
    363.37253, 319.31824, 314.39688, 303.60342, 294.8934), contrafact = c(364.5, 
    358.89, 466.64, 470.11, 464.25, 487.27, 591.2, 715.33, 628.02, 
    505.98, 402.9, 316.81, 323.35, 358.61, 354.26, 369.5, 317.01, 
    336.5, 285.33, 270.91), complete_preds_lower = c(320.6368042, 
    361.7870895, 432.4487762, 461.2275833, 503.2255051, 535.7108551, 
    576.3850006, 597.9762146, 601.4407013, 504.0448837, 398.7777023, 
    368.0046799, 356.3603165, 345.5847885, 339.9679932, 342.7514801, 
    298.3247482, 293.4419693, 282.5286865, 275.4635284), complete_preds_upper = c(359.9897186, 
    402.5708664, 477.4746765, 508.7775711, 550.3326447, 587.6521027, 
    628.5320251, 649.9691833, 649.4831665, 547.9886108, 442.046402, 
    410.8121475, 399.0208908, 389.8615128, 387.4929993, 386.2935928, 
    340.140834, 336.3622116, 324.793483, 315.4606934)), row.names = c(NA, 
-20L), class = c("tbl_df", "tbl", "data.frame"))
jjhzyzn0

jjhzyzn01#

像这样?

df %>% 
  pivot_longer(-dias) %>%  
  ggplot() + 
  aes(x = dias, y = value, col = name) + 
  geom_smooth(se = FALSE)

8e2ybdfx

8e2ybdfx2#

您可以使用函数smooth,参数如下
为每列添加一个geom_smooth(...)行。
如果您需要一个系列的区间置信度,请将“se = FALSE”切换为True。

> ggplot()+   geom_smooth(data=data, aes(x=dias,
> y=complete_preds_means),   method = loess, se=FALSE)

相关问题