首页 > 解决方案 > 如何使用日期 yy/mm/dd hh:mm:ss 制作绘图数据?

问题描述

我有一组数据需要用 R 绘制。我需要制作点图形,其值作为 y 轴,日期和时间作为 y。但首先我想在一个日期(例如 2018.10.29 10:10:12 - 2018.10.29 23:59:01)和接下来的大约一周然后一个月等进行绘图。我也有数据框和 file.csv作为我的数据源。我的数据有 2 种日期格式,也许我必须更改日期格式,以便日期格式为一种格式。请你帮助我好吗?我是 R 的新手,我尝试学习它。谢谢您的帮助。

下面是一个简短的数据示例:

ID  Date    Location    CO2 Temp    Hum Light   Soil    Soil2                                                   
1   10/29/2018 12:11    EE_agri8    557.8357    23.90000    45.00000    41.0000 99.55399    99.67636    
2   10/29/2018 12:12    EE_agri8    557.8357    23.90000    45.50000    41.0000 99.55399    99.67636    
3   10/29/2018 12:11    EE_agri8    557.8357    25.84484    70.24592    508.5654    99.55399    99.67636    
4   2018-10-29 12:13:16 EE_agri8    557.8357    25.84484    70.24592    508.5654    73.07000    99.67636    
5   2018-10-29 16:57:35 EE_agri8    557.8357    25.84484    70.24592    508.5654    99.55399    99.67636    
6   10/29/2018 12:12    EE_agri8    557.8357    25.84484    70.24592    508.5654    99.55399    99.67636    23.8600 24.0549
7   10/29/2018 12:13    EE_agri8    557.8357    24.00000    45.40000    41.0000 99.55399    99.67636    
8   2018-10-29 12:14:20 EE_agri8    557.8357    25.84484    70.24592    508.5654    72.15000    99.67636    
9   2018-10-29 17:01:04 EE_agri8    557.8357    25.84484    70.24592    508.5654    99.55399    99.67636    
10  10/30/2018 12:12    EE_agri8    557.8357    25.84484    70.24592    508.5654    99.55399    99.67636    
11  10/30/2018 12:14    EE_agri8    557.8357    24.20000    45.40000    41.0000 99.55399    99.67636    
12  2018-10-30 12:15:23 EE_agri8    557.8357    25.84484    70.24592    508.5654    72.84000    99.67636    
13  2018-10-30 17:02:14 EE_agri8    557.8357    25.84484    70.24592    508.5654    99.55399    99.67636    
14  10/31/2018 12:13    EE_agri8    557.8357    25.84484    70.24592    508.5654    99.55399    99.67636

标签: rdatetimeplot

解决方案


您可以使用parsedate尝试检测日期格式的函数,然后进行一些争论,您可以facet_grid在 ggplot2 中使用将数据分解为所需的分组:

library(dplyr)
library(parsedate)

# Parse dates
(df <- df %>%
    mutate(Date = parse_date(Date),
           time = format(Date, "%H:%M:%S"), # Strips date from Date
           day = format(Date, "%Y/%m/%d"), # strips time from Date
           month = format(Date, "%Y/%m"), # format by year/month
           week = strftime(Date, format = "%V") # finds the week of year the date falls into
           ))

# By Day
df %>%
  ggplot(aes(x = time, y = Soil)) +
  geom_point() +
  facet_grid(day~.)

# By Week
df %>%
  ggplot(aes(x = Date, y = Soil)) +
  geom_point() +
  facet_grid(week~.)

# By Month
df %>%
  ggplot(aes(x = Date, y = Soil)) +
  geom_point() +
  facet_grid(month~.)

推荐阅读