r - 如何绘制异常值和原始序列?

标签 r plot

嗨,我想定义一个函数,它根据指定的日期范围返回离群值(定义如下)的图,并同时绘制原始序列(并在该上下文中考虑可能的比率) :

定义异常值:

  anomaly <- function(x)
               {   tt <- 1:length(x)  
                   resid <- residuals(loess(x ~ tt)) 
                   resid.q <- quantile(resid,prob=c(0.25,0.75)) 
                   iqr <- diff(resid.q) 
                   limits <- resid.q + 1.5*iqr*c(-1,1)  
                   score <- abs(pmin((resid-limits[1])/iqr,0) + pmax((resid -                   limits[2])/iqr,0)) 

                   return(score)
            }
   # defining dates
     dates <- as.POSIXct(seq(as.Date("2015-08-20"), as.Date("2015-10-08"), by = "days"))

一些数据:

     a<-runif(50, 5.0, 7.5)
     b<-runif(50, 4, 8)
     c<-runif(50, 1, 2)
     d<-runif(50, 3, 3.5)
     ca<-c/a
     cb<-c/b
     df<-data.frame(dates,a,b,c,d,ca,cb)

引入异常值

       df[49,4]<-0
       df[50,6]<-0

循环数据以查找异常

      new<-lapply(df[,2:7],anomaly)
       library(stringi) # binding list with differing rows
     # from list to data frame
       res <- as.data.frame((stri_list2matrix(new)))
     # rename columns
       colnames(res) <- names(new)
     # depends on dates at the beginning 
      res<-(cbind(dates,res[,1:6])) 
     # melt to plot
       library(reshape)
       library(reshape2)
       new <- melt(res , id.vars = 'dates', variable.name = 'series')

使用指定的日期范围定义绘图(过去 4 天):

       library(ggplot2)

       nrdays <- 4
       a.plot<-ggplot(subset(new, new$dates >= as.POSIXct(max(new$dates)- (nrdays*60*60*24))),
         aes(x=dates,y=value,colour=variable,group=variable)) + 
         geom_line() + 
         facet_grid(variable ~ ., scales = "free_y")+
         ylab("Outliers")+
         xlab("Date")

定义检查数据函数:

          check_data <- function(df) { 
          if(tail(df, 1) > 0) { # check only last date

            return(a.plot)

           # and the corresponding original series

        }
      }
        # check and plot data
          check_data(df)

我的问题是我有数百个特征,我只想绘制那些发生异常值的特征。正如您在图表中所看到的,我能够绘制出一个图,该图返回所有时间序列,包括具有异常值的序列,而不是仅发生异常值的序列。此外,我还想报告原始系列(包括 ratios,即,给定比率 ca 中的异常值,我想获得原始系列 ca 也是)...我该如何解决这个问题。所以输出可能如下所示:

including original series:

enter image description here

and the outlier as well:

enter image description here

最佳答案

您需要在子集中中指定您只需要离群值,即不等于 0 的值。 所以你可以替换

a.plot<-ggplot(subset(new, new$dates >= as.POSIXct(max(new$dates)- (nrdays*60*60*24)) &  new$variable %in% new$variable[!new$value %in% 0 & new$dates >= as.POSIXct(max(new$dates)- (nrdays*60*60*24))]),
           aes(x=dates,y=value,colour=variable,group=variable)) + 
  geom_line() + 
  facet_grid(variable ~ ., scales = "free_y")+
  ylab("Outliers")+
  xlab("Date")

这应该有帮助。你也可以清理一下它,这样它就更具可读性

另一种选择是将原始数据和异常值结合起来并将它们绘制在一起。首先创建一个 data.frame,然后将其子集并传递给 ggplot。 因此,在循环数据之后,您可以执行类似的操作

orig <- melt(df , id.vars = 'dates', variable.name = 'series')

data.df <- merge(new, orig, by = c("dates", "variable"))
colnames(data.df)[2:4] <- c("group","index", "original")
data.df$index <- as.numeric(as.character(data.df$index)) # replace factor with numeric

nrdays <- 4
data.subs <- subset(data.df, data.df$dates >= as.POSIXct(max(data.df$dates)- (nrdays*60*60*24)) & 
                  data.df$group %in% data.df$group[!data.df$index %in% 0 & data.df$dates >= as.POSIXct(max(data.df$dates)- (nrdays*60*60*24))])
data.subs <- melt(data.subs, id = c('dates', "group"))

a.plot<-ggplot(data.subs)+
  geom_line(aes(x=dates,y=value, colour = variable, group = variable))+
  facet_grid(group ~ ., scales = "free_y")+
  ylab("Outliers")+
  xlab("Date")

a.plot

enter image description here

关于r - 如何绘制异常值和原始序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33496013/

相关文章:

r - 混合模型的 R 和 SAS 中的 AIC 计算不匹配

r - 从 R 脚本调用 plot() 并在输出文件中获取图形?

plot - 如何在 ILNumerics 中有效地绘制大表面(例如 1000x1000)?

python - 如何在 Subplot 中绘制带有注释的多个 Seaborn Jointplot

matlab - 更改绘图透明度

r - 在 ggplot2 中绘制一组曲线的 “Average ” 曲线

r - 从 R 中的每个组中选择不同数量的元素

轴标签与表达式的 R 对齐

r - 为什么环境的 `object.size`小于环境中对象的 `object.size`?

python - 如何在 Matplotlib 极坐标图中添加楔形扇区