gpt4 book ai didi

r - ggplot2 geom_line() 和平滑

转载 作者:行者123 更新时间:2023-12-01 19:29:30 25 4
gpt4 key购买 nike

我正在尝试创建一个看起来更像这样的 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 一起使用任何提示将不胜感激!

最佳答案

请注意,MEI 指数的周期为 2 个月,因此它已经内置了一些平滑功能。假设您正在使用 NOAA ESRL 发布的 MEI 数据,您应该能够创建相同的绘图。

首先,您需要设置系统,因为您将使用 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

现在,你真的需要平滑这个吗?

关于r - ggplot2 geom_line() 和平滑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25367607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com