2012-04-13 77 views
7

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

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

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

class(table$time)numeric

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

难道你有可能展示你的数据框的样子吗?我很难理解您的'时间'可以同时用数字和'%H:%M:%S%p%m /%d /%Y'两种形式表示。 – plannapus 2012-08-08 08:38:02

回答

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的对象)并控制它们将如何与format一起出现。

就子集问题而言,只要你的dateTime1和dateTime2对象也是POSIXct对象,你可以像做任何其他类型的子集一样做。

dateTime1 <- strptime("00:00 05/31/2012", format="%H:%M %m/%d/%Y") 
dateTime2 <- strptime("3 Jun 2012 05-30", format="%d %b %Y %H-%M") 
data[data$time < dateTime2 & data$time > dateTime1, ] 
       time variable 
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 
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轴的数据类型是日期,并相应地绘制轴。

+0

+1确实比我的方法更方便。如果需要,是否还有办法控制标签的格式或其位置? – plannapus 2012-08-08 09:32:52

+1

是的,您可以使用'scale_x_date'或'scale_x_datetime'来调整比例。查看他们的文档的一些例子。 – 2012-08-08 09:53:41