How to smooth the curve of a line plot in ggplot?

I have created a line graph using ggplot. But his ribs are not smooth. How can i do this?

enter image description here

I tried using functions geom_smooth()

and stat_summary()

, but I got no results. Errors are shown.

Here's my code for the linear path:

df <- data.frame(A=c(2,3,4,5,6,7,3,7,8,9,2),B=c(3,7,8,9,2,1,2,3,4,5,6),C=c(1,1,1,2,2,1,1,1,1,2,2))
go <- ggplot(df, aes(x=A, y=B, colour = C), pch = 17) +geom_point() 
go + geom_path(data = rbind(cbind(tail(df, -1), grp = 1:(nrow(df)-1)),  
                          cbind(head(df, -1), grp = 2:nrow(df)-1)),
             aes(group = interaction(grp)))

      

+3


source to share


1 answer


A couple of options using smoothing splines and a Bezier curve

plot(df[,1:2])
xspline(df[,1:2], shape=-0.2, lwd=2)  # play with the shape parameter

library(bezier)
res <- bezier(seq(0, 1, len=100), df[,1:2], deg=nrow(df)-1)
points(res, type="l", col="green", lwd=2)

      

enter image description here



or in ggplot2

## Get points
ps <- data.frame(xspline(df[,1:2], shape=-0.2, lwd=2, draw=F))

## Add to your plot
go <- ggplot(df, aes(x=A, y=B, colour = factor(C)), pch = 17) +
  geom_point(size=5) +
  geom_path(data=ps, aes(x, y), col=1)

      

enter image description here

+4


source







All Articles