【问题标题】:Date problems plotting time series with ggplot2 from .csv file with individual columns for year month使用 .csv 文件中的 ggplot2 绘制时间序列的日期问题,其中包含年月的单独列
【发布时间】:2019-04-17 14:46:15
【问题描述】:

我正在开展一个针对水文建模数据的数据分析项目。我已将结果导出为 .csv 格式并作为数据框 (Out_1) 集成到 R 中。之后我选择了一些我需要的变量,如下所示。

Out_1 <- read.csv("Outlets_1.csv",header = TRUE)
Out_1s <- select(Out_1,SUB,YEAR,MON,AREAkm2,EVAPcms,FLOW_OUTcms,SED_OUTtons,YYYYMM)
str(Out_1s)
'data.frame':   480 obs. of  8 variables:
 $ SUB        : int  19 19 19 19 19 19 19 19 19 19 ...
 $ YEAR       : int  1983 1983 1983 1983 1983 1983 1983 1983 1983 1983 ...
 $ MON        : int  1 2 3 4 5 6 7 8 9 10 ...
 $ AREAkm2    : int  1025 1025 1025 1025 1025 1025 1025 1025 1025 1025 ...
 $ EVAPcms    : num  0.00601 0.00928 0.01696 0.01764 0.02615 ...
 $ FLOW_OUTcms: num  2.31 2.84 3.16 18.49 34.42 ...
 $ SED_OUTtons: num  215 308 416 3994 11440 ...
 $ YYYYMM     : int  198301 198302 198303 198304 198305 198306 198307 198308 198309 198310 ...


typeof(Out_1s$YEAR)
[1] "integer"
typeof(Out_1s$MON)
[1] "integer"
typeof(Out_1s$YYYYMM)
[1] "integer"

我真正尝试做的是基于组合 Out_1s.YEAR 和 Out_1s.MON 列或将 Out_1s.YYYYMM 变量标识为 YYYY-MM 或 MM-YYYY,使用 ggplot2 创建图形摘要。

Out_1s$Date <- NA
typeof(Out_1s$Date)
[1] "character"    

Out_1s$Date <- paste(Out_1s$YEAR,Out_1s$MON, sep = "-")
as.Date.character(Out_1s$Date, "%Y-%m")

graph1 <- ggplot(Out_1s, aes(Date, FLOW_OUTcms ))
graph1 + geom_line()

而结果实际上并不是预期的。

【问题讨论】:

标签: r csv ggplot2 tidyr


【解决方案1】:

这里有两个问题。

  • 首先,Date 对象是年、月和日。要修复在粘贴语句中添加“01”。

    Out_1s$Date <- paste(Out_1s$YEAR,Out_1s$MON, "01", sep = "-")
    

    在您的情况下,由于日期不包括一天,as.Date 函数将返回一系列 NAs

  • 其次,需要将as.Date 函数的结果重新分配回原始列。

    Out_1s$Date <- as.Date.character(Out_1s$Date, "%Y-%m-%d")
    

【讨论】:

  • 问题已解决不知道必须只包含 %d 才能使系统正常工作!非常感谢!!!
猜你喜欢
  • 2019-04-23
  • 2018-04-21
  • 1970-01-01
  • 1970-01-01
  • 2015-07-10
  • 2019-06-26
  • 2023-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多