R - 找不到绘制最接近局部最大值的直线的方法(méthode de la bande)



我正在开发一个用R和shiny分析时间序列的应用程序,我想绘制一个特定的图形来帮助选择加法或乘法模型:1

我想绘制我的时间序列,但也要分别绘制最接近每个周期的最大值和最小值的两条线。

这是我想画的图形的链接:https://i.imgsafe.org/fdb95a34f9.png

目前这是我的代码,我叫我的函数plot_band:

plot_band <- function(Xt, period){
  # Create an index 
  index <- 1:lenght(Xt) 
  # Create the vector period which value is the period the point belong to 
  periods <- index%/%period + 1
  # Create a dataframe
  df <- data.frame(xt= Xt,periods = as.factor(periods))
  # FInd the minimums and maximums 
  mins <- df[df$xt == ave(df$xt, df$period, FUN=min), ]
  maxs <- df[df$xt == ave(df$xt, df$period, FUN=max), ]
  # Regression with lm
  mins_reg <- lm(mins$xt ~ mins$index)
  maxs_reg <- lm(maxs$xt ~ maxs$index)
  #And I don't know how to plot everything
  my_graph <- ggplot(data=df,

另一个问题是,xt是在一个ts格式,当它在参数中给出,我不知道如何得到真正的索引,而不是索引N

我终于找到了这个问题的解决方案,它可能不是更好,但这里是:

plot_bande <- function(xt,period){
begin <- start(xt)[1]
end <- end(xt)[1]
freq <- frequency(xt)
idx <- seq(begin,end,freq)
periods <- idx %/% period + 1 - idx[1] %/% period
df <- data.frame(data=xt,period=periods, idx=idx)
df$period <- as.factor(df$period)
min <- df[df$data == ave(df$data, df$period, FUN=min), ]
max <- df[df$data == ave(df$data, df$period, FUN=max), ]
reg_min <- lm(min$data ~ min$idx)
reg_max <- lm(max$data ~ max$idx)
a_min <- coef(reg_min)[1]
b_min <- coef(reg_min)[2]
a_max <- coef(reg_max)[1]
b_max <- coef(reg_max)[2]
plot(df$data)
abline(a=a_min,b=b_min,col='blue')
abline(a=a_max,b=b_max,col='red')
legend('topleft', legend=c('Minimum values', 'Maximum values'),col=c('blue','red'), lty=1)

}

你们可以看到我得到的关于太阳黑子的图表。年份数据集和12年的周期,点击此链接

相关内容

最新更新