Home > Back-end >  How can I smooth lines in ggplot?
How can I smooth lines in ggplot?

Time:01-12

I want to reproduce the following graph but with smoother lines:

enter image description here

Such that the lines are similar to the following graph:

enter image description here

So far, I've tried the following, but I only get a trend instead of smoothing the two series:

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)

My data:

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

CodePudding user response:

Like this?

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

enter image description here

CodePudding user response:

You can use the function smooth, with the folowing parameters

Add one geom_smooth(...) line for each of your columns.

If you want the interval confidence for one serie, you switch the "se = FALSE" to True.

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