绘制数据对中的R时刻(Plotting data against time in R)

2019-07-28 23:01发布

我有一列作为日期/时间(内部存储为数字)和其他列作为数字/整数的数据帧和我要绘制针对日期/时间数据。

在数据帧中的日期/时间使用下填充。

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

class(table$time)numeric

  1. 如何绘制,并显示在x轴的数据在某些格式读取日期时间。
  2. 如何绘制行而不是所有行的子集,例如:与行dateTime1dateTime2其中dateTime1dateTime2特定格式的日期给出。

Answer 1:

你也可以使用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()

或使用线几何:

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

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



Answer 2:

下面是一些虚拟的数据:

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


文章来源: Plotting data against time in R