在R中绘制数据与时间的关系

时间:2012-04-13 18:44:52

标签: r datetime plot ggplot2

我有一个数据框,其中一列为日期/时间(内部存储为数字),其他列为数字/整数,我想根据日期/时间绘制数据。

使用以下内容填充数据框中的日期/时间。

as.POSIXct(strptime(time, '%H:%M:%S %p %m/%d/%Y',tz='GMT')) 

class(table$time)numeric

  1. 如何绘制x轴中的数据并以某种格式显示为可读日期时间。
  2. 如何绘制行的子集而不是所有行Ex:dateTime1dateTime2之间的行,其中dateTime1dateTime2是以特定格式给出的日期。

2 个答案:

答案 0 :(得分:10)

您还可以使用ggplot2,更具体地说geom_pointgeom_line(请注意我使用@plannapus中的示例数据):

require(ggplot2)
theme_set(theme_bw()) # Change the theme to my preference
ggplot(aes(x = time, y = variable), data = data) + geom_point()

enter image description here

或使用线几何:

ggplot(aes(x = time, y = variable), data = data) + geom_line()

enter image description here

ggplot2自动识别x轴的数据类型是日期,并相应地绘制轴。

答案 1 :(得分:7)

这是一些虚拟数据:

data <- structure(list(time = structure(c(1338361200, 1338390000, 1338445800, 1338476400, 1338532200, 1338562800, 1338618600, 1338647400, 1338791400, 1338822000), class = c("POSIXct", "POSIXt"), tzone = ""), variable = c(168L, 193L, 193L, 201L, 206L, 200L, 218L, 205L, 211L, 230L)), .Names = c("time", "variable"), row.names = c(NA, -10L), class = "data.frame")
data
              time variable
1  2012-05-30 09:00:00      168
2  2012-05-30 17:00:00      193
3  2012-05-31 08:30:00      193
4  2012-05-31 17:00:00      201
5  2012-06-01 08:30:00      206
6  2012-06-01 17:00:00      200
7  2012-06-02 08:30:00      218
8  2012-06-02 16:30:00      205
9  2012-06-04 08:30:00      211
10 2012-06-04 17:00:00      230

要在轴上显示日期和时间,您可以使用函数axis.POSIXct

plot(data, xaxt="n")
axis.POSIXct(side=1, at=cut(data$time, "days"), format="%m/%d") 

您可以使用at控制滴答的位置(对于常规函数axis,除了此处将提供类POSIXct的对象)并控制它们与{{1}一起出现的方式}。

就子集化而言,只要您的dateTime1和dateTime2对象也是POSIXct对象,您就可以像执行任何其他类型的子集一样进行。

format