2015-09-08 49 views
2

如何平滑线条边缘?我可以这样做我的线情节:用样条线连接点

data <- data.frame(x=1:10, y=c(22,23,21,25,23,24,20,27,22,24)) 
ggplot(data, aes(x,y)) + 
    geom_line(colour='forestgreen') 

但是,我不喜欢锋利的边缘。有没有办法通过这些点绘制线条以便线条平滑?

回答

3

这是做这件事:

library(ggplot2) 
library(splines) 
library(gridExtra) 

dat <- data.frame(x=1:10, y=c(22,23,21,25,23,24,20,27,22,24)) 

plot.new() # have to do this unfortunately 
res <- xspline(dat$x, dat$y, -0.25, draw=FALSE) 

gg1 <- ggplot(dat, aes(x,y)) + 
    geom_line(colour='forestgreen') + 
    geom_point() 

gg2 <- ggplot(data=data.frame(x=res$x, y=res$y), aes(x, y)) + 
    geom_point(data=dat, aes(x, y), size=1) + 
    geom_line(color="blue") 

grid.arrange(gg1, gg2, ncol=1) 

enter image description here

这是使用xspline做插值。查看函数,看看调整-0.25参数(范围是-11)会做什么。

+0

它的工作原理。现在我只需要找出处理缺失值的方法。我在各个地方都有许多缺失值的时间系列。我想我只需要将时间序列分成不同的块,以便它们不包含缺失值并计算每个块的样条曲线。谢谢您的帮助! – Nso

+0

如果您愿意使用ggplot2的github/devtools版本,我也将其封装到一个包https://github.com/hrbrmstr/gggaldu中(以上pkg将会有更多ggplot2扩展) – hrbrmstr

+0

使https: //github.com/hrbrmstr/ggalt(新名称) – hrbrmstr