在R中根据时间绘制数据
我有一个数据帧,其中一列作为日期/时间(内部存储为数字),其他列作为数字/整数,我想根据日期/时间打印数据 数据框中的日期/时间是使用以下命令填充的在R中根据时间绘制数据,r,datetime,plot,ggplot2,R,Datetime,Plot,Ggplot2,我有一个数据帧,其中一列作为日期/时间(内部存储为数字),其他列作为数字/整数,我想根据日期/时间打印数据 数据框中的日期/时间是使用以下命令填充的 as.POSIXct(strptime(time, '%H:%M:%S %p %m/%d/%Y',tz='GMT')) 类(表$time)是数字的 如何以某种格式在x轴上打印和显示数据作为可读的日期时间 如何绘制行的子集而不是所有行,例如dateTime1和dateTime2之间的行,其中dateTime1和dateTime2是以特定格式给出的
as.POSIXct(strptime(time, '%H:%M:%S %p %m/%d/%Y',tz='GMT'))
类(表$time)
是数字的
dateTime1
和dateTime2
之间的行,其中dateTime1
和dateTime2
是以特定格式给出的日期李>
以下是一些虚拟数据:
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
您可以使用at
控制刻度落在何处(对于常规函数轴
,此处将提供POSIXct类对象除外),并控制它们如何以格式显示
就子集而言,只要您的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
dateTime1您还可以使用ggplot2
,更具体地说是geom_点
或geom_线
(请注意,我使用的示例数据来自@plannapus):
或使用直线几何图形:
ggplot(aes(x = time, y = variable), data = data) + geom_line()
ggplot2
自动识别x轴的数据类型是日期,并相应地绘制轴。是否可以显示数据框的外观?我很难理解你的时间如何既可以是数字的,又可以是“%H:%M:%S%p%M/%d/%Y”形式的。事实上+1比我的方便多了。如果需要,是否还有控制标签格式或其位置的方法?是的,您可以使用scale\u x\u date
或scale\u x\u datetime
调整比例。有关一些示例,请参见他们的文档。
require(ggplot2)
theme_set(theme_bw()) # Change the theme to my preference
ggplot(aes(x = time, y = variable), data = data) + geom_point()
ggplot(aes(x = time, y = variable), data = data) + geom_line()