如何在ggplot中平滑曲线折线图?

4 r ggplot2

我已经使用ggplot制作了折线图。但是它的边​​缘不光滑。我怎样才能做到这一点?

在此处输入图片说明

我尝试使用geom_smooth()stat_summary()函数,但没有得到结果。其显示错误。

这是我的行路径代码:

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)))
Run Code Online (Sandbox Code Playgroud)

pic*_*ick 5

几个选项,使用平滑样条和贝塞尔曲线

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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

或在 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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明