ggplot2 geom_line()和平滑

时间:2014-08-18 16:11:34

标签: r ggplot2 smoothing linegraph

我正在尝试创建一个看起来更像这样的GGPLOT2平滑线图

enter image description here

来源:http://www.esrl.noaa.gov/psd/enso/mei/

而不是这样:

enter image description here

来源:https://dl.dropboxusercontent.com/u/16400709/StackOverflow/Rplot02.png

我的数据是available on dropbox

看了以前的帖子,我使用了下面的代码:

#MEI Line Graph

d4 <- read.csv("https://dl.dropboxusercontent.com/u/16400709/StackOverflow/Data_MEI.csv")
head(d4,n=20)

MEI<-ggplot(d4,aes(x=d4$Date, y=d4$MEI,group=1))+geom_line()

MEI+stat_smooth(method ="auto",level=0.95)

我认为我需要的是减少发生的平滑量,但我还没弄明白如何实现这一点。

d4s<-SMA(d4$MEI,n=8)
plot.ts(d4s)

SMA()运行良好,但我无法使用ggplot 任何提示将不胜感激!

1 个答案:

答案 0 :(得分:10)

请注意MEI索引是2个月的时间段,所以它已经内置了一些平滑功能。假设您正在使用NOAA ESRL发布的MEI数据,您应该能够创建相同的情节。 / p>

首先,您需要设置系统,因为您将使用timezeones:

# set things up  ----
working.dir = file.path('/code/R/StackOverflow/')
setwd(working.dir)
Sys.setenv(TZ='GMT')

现在,下载您的数据并在

中阅读
d.in <- read.csv("MEI.txt")

下一步是正确格式化日期。

d.in$Date <- as.POSIXct(d.in$Date,
                        format = "%d/%m/%Y", 
                        tz = "GMT")

因为我们需要弄清楚事物穿过x轴的位置,所以我们必须在十进制日期工作。使用Epoch值:

d <- data.frame(x = as.numeric(format(d.in$Date,
                                      '%s')),
                y = d.in$MEI)

现在我们可以找出过零点。我们将使用Beroe's example for that

rx <- do.call("rbind",
              sapply(1:(nrow(d)-1), function(i){
                f <- lm(x~y, d[i:(i+1),])
                if (f$qr$rank < 2) return(NULL)
                r <- predict(f, newdata=data.frame(y=0))
                if(d[i,]$x < r & r < d[i+1,]$x)
                  return(data.frame(x=r,y=0))
                else return(NULL)
              }))

并在初始数据的最后添加:

d2 <- rbind(d,rx)

现在转换回日期:

d2$date <- as.POSIXct(d2$x,
                      origin = "1960-01-01",
                      format = "%s",
                      tz = "GMT")

现在我们可以做这个情节:

require(ggplot2)
ggplot(d2,aes(x = date,
              y = y)) + 
  geom_area(data=subset(d2, y<=0), fill="blue") + 
  geom_area(data=subset(d2, y>=0), fill="red") + 
  scale_y_continuous(name = "MEI")

这给你这个:

enter image description here

现在,你真的需要顺利解决这个问题吗?

相关问题