r - ggplot2 geom_line() and smoothing -
i trying create ggplot2 smoothed line graph looks more this
source: http://www.esrl.noaa.gov/psd/enso/mei/
and less this:
source: https://dl.dropboxusercontent.com/u/16400709/stackoverflow/rplot02.png
my data available on dropbox.
having looked @ previous posts used code below:
#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)
what think need reduce amount of smoothing taking place, have yet figure out how achieve this.
d4s<-sma(d4$mei,n=8) plot.ts(d4s)
sma() works cant work ggplot hints appreciated!
be aware mei index 2-month period, it's got smoothing built in. assuming using mei data noaa esrl publishes, should able create same plot.
first of need system set up, you'll working timezeones:
# set things ---- working.dir = file.path('/code/r/stackoverflow/') setwd(working.dir) sys.setenv(tz='gmt')
now, download data , read in
d.in <- read.csv("mei.txt")
the next step dates formatted properly.
d.in$date <- as.posixct(d.in$date, format = "%d/%m/%y", tz = "gmt")
and because need figure out things cross x-axis, we'll have work in decimal dates. use epoch value:
d <- data.frame(x = as.numeric(format(d.in$date, '%s')), y = d.in$mei)
now can figure out zero-crossings. we'll use beroe's example 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) }))
and tack on end of initial data:
d2 <- rbind(d,rx)
now convert dates:
d2$date <- as.posixct(d2$x, origin = "1960-01-01", format = "%s", tz = "gmt")
now can plot:
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")
and gives this:
now, need smooth this?
Comments
Post a Comment