【问题标题】:Subsetting timeseries data子集时间序列数据
【发布时间】:2016-09-06 00:14:20
【问题描述】:
ggplot(Price.data['2000-01/2015-12'],aes(x=Demand,y=Price))+geom_point()+geom_smooth(method=lm)

indexClass(Price.data)
[1] "Date"

如何仅绘制 2010-2014 年的 3 月、4 月和 6 月数据?

 head(Price.data)
        Dry_Gas_Y Power_Gas_Y Price_Gas_Y
1990-01-01  52.16720    5.469179        2.39
1990-02-01  51.45287    5.470755        1.90
1990-03-01  49.29829    6.908609        1.55
1990-04-01  48.29243    7.721371        1.49
1990-05-01  47.25959    9.154057        1.47
1990-06-01  47.48744   11.525595        1.47

【问题讨论】:

  • 你能提供一个可重现的例子吗?还是您的数据集样本?特别是,我们需要您的date 列的格式

标签: r ggplot2 time-series subset xts


【解决方案1】:

您可以使用data.table,这可能是最快的解决方案

library(data.table)   


# convert your dataset into a data.table
  setDT(df)

# If necessary, get date column into date format
#  df[ , Date := as.Date(df$Date, "%m-%d-%y") ] 

# Create separate columns for year and month
  df[, year := year(Date)][, month := month(Date)]

# filter dataset
  df <- df[ month %in% c(3,4,6) & year %in% c(2009:2014), ]
  #  subset(df, month %in% c(3,4,6) & year %in% c(2009:2014) ) # you could also use a simple subset, but this is likely to be slower

剧情

  ggplot(data=df, aes(x=Demand, y=Price)) + geom_point() + geom_smooth(method=lm)

【讨论】:

    【解决方案2】:
    library(tidyverse)
    
    Price.data %>% 
      mutate(year = as.numeric(format(Date, "%Y")),
             month = as.numeric(format(Date, "%m"))) %>%
      filter(year > 2009 & year < 2015, month == 3 | month == 4 | month ==6) %>%     
    ggplot(aes(Demand,Price))+geom_point()+geom_smooth(method=lm)
    

    【讨论】:

      【解决方案3】:

      从您的示例中,我没有看到具有列名的日期,并且看起来日期是行名。出于这个原因,本示例创建了一个“日期”列,然后是“月份”和“年份”列,供您过滤日期。

      library(lubridate)
      library(dplyr
      
      plot_months <- Price.data%>%
                     mutate(Date = row.names(.),
                            Month = month(Date),
                            Year = year(Date))%>%
                     filter(Month %in% c(3,4,6),
                            Year %in% c(2009:2014))
      
      ggplot(plot_months, aes(x=Demand,y=Price))+
             geom_point()+
             geom_smooth(method=lm)
      

      【讨论】:

        【解决方案4】:

        由于Price.data 是一个xts 对象,您可以使用.indexmon 函数来提取您想要绘制的月份。然后使用基于范围的子集来提取您想要的年份范围。

        请注意,.indexmon 返回从一月 = 0 开始的月份,就像 POSIXlt 对象的 $mon 元素一样。

        ggplot(Price.data[.indexmon(Price.data) %in% c(2, 3, 5)]['2010/2014'],
          aes(x=Dry_Gas_Y, y=Price_Gas_Y)) + geom_point() + geom_smooth(method=lm)
        

        【讨论】:

          猜你喜欢
          • 2021-05-20
          • 1970-01-01
          • 1970-01-01
          • 2017-07-04
          • 2016-09-10
          • 1970-01-01
          • 2021-06-17
          • 2014-03-08
          • 2018-01-23
          相关资源
          最近更新 更多