我正在使用R绘制一些数据。

Date <- c("07/12/2012 05:00:00", "07/12/2012 06:00:00", "07/12/2012 07:00:00",
      "07/12/2012 08:00:00","07/12/2012 10:00:00","07/12/2012 11:00:00")
Date <- strptime(Date, "%d/%m/%Y %H:%M")
Counts <- c("0","3","10","6","5","4")
Counts <- as.numeric(Counts)
df1 <- data.frame(Date,Counts,stringsAsFactors = FALSE)
library(ggplot2)
g = ggplot(df1, aes(x=Date, y=Counts)) + geom_line(aes(group = 1))
g

我如何要求R在有时间间隔时不要将数据绘制为连​​续线?我通常每个小时都有一个数据点,但有时会出现中断(在上午8点至上午10点之间)。在这些点之间,我不想连接线。在R中这可能吗?

编辑

非常感谢您的答复。现在,我的数据间隔为10秒,我希望使用此数据进行相同的分析。
df <- structure(list(Date = c("11/12/2012", "11/12/2012", "11/12/2012",
                     "11/12/2012", "11/12/2012", "11/12/2012", "11/12/2012",
                     "11/12/2012", "11/12/2012", "11/12/2012", "11/12/2012"),
                     Time = c("20:16:00", "20:16:10", "20:16:20", "20:16:30",
                     "20:16:40", "20:16:50", "20:43:30", "20:43:40",
                     "20:43:50", "20:44:00", "20:44:10"),
                     Axis1 = c(181L, 14L, 65L, 79L, 137L, 104L, 7L, 0L, 0L,
                     14L, 0L),
                     Steps = c(13L, 1L, 6L, 3L, 8L, 4L, 1L, 0L, 0L, 0L, 0L)),
                .Names = c("Date", "Time", "Axis1", "Steps"),
                row.names = c(57337L, 57338L, 57339L, 57340L, 57341L, 57342L,
                57502L, 57503L, 57504L, 57505L, 57506L), class = "data.frame")

我认为我理解了代码在将“组”列添加到原始数据帧时的意图,但是我的问题围绕着我如何让R知道现在的数据间隔为10秒?当我应用第一行代码来确定数字是否连续或是否存在间隔时(例如idx
r [i1]-r [-length(r):-( length(r)-lag + 1L)]中的错误:
二进制运算符的非数字参数

在“时间”变量之后,是否需要添加“as.POSIXct”以确保正确识别时间?

最佳答案

您必须通过为要连接的那些点设置一个公共(public)值来设置group。在这里,您可以将前4个值设置为1,将后2个值设置为2。并保留它们作为因素。那是,

df1$grp <- factor(rep(1:2, c(4,2)))
g <- ggplot(df1, aes(x=Date, y=Counts)) + geom_line(aes(group = grp)) +
                     geom_point()

编辑:加载data.frame后,您可以使用以下代码自动生成grp列:
idx <- c(1, diff(df$Date))
i2 <- c(1,which(idx != 1), nrow(df)+1)
df1$grp <- rep(1:length(diff(i2)), diff(i2))

注意:添加geom_point()也是重要的,因为如果discontinuous range恰好是data.frame中的LAST条目,则不会绘制它(因为没有2点连接线)。在这种情况下,geom_point()将对其进行绘制。

举例来说,我将生成差距更大的数据:
# get a test data
set.seed(1234)
df <- data.frame(Date=seq(as.POSIXct("05:00", format="%H:%M"),
                as.POSIXct("23:00", format="%H:%M"), by="hours"))
df$Counts <- sample(19)
df <- df[-c(4,7,17,18),]

# generate the groups automatically and plot
idx <- c(1, diff(df$Date))
i2 <- c(1,which(idx != 1), nrow(df)+1)
df$grp <- rep(1:length(diff(i2)), diff(i2))
g <- ggplot(df, aes(x=Date, y=Counts)) + geom_line(aes(group = grp)) +
            geom_point()
g

编辑:对于您的新数据(假设它是df),
df$t <- strptime(paste(df$Date, df$Time), format="%d/%m/%Y %H:%M:%S")

idx <- c(10, diff(df$t))
i2 <- c(1,which(idx != 10), nrow(df)+1)
df$grp <- rep(1:length(diff(i2)), diff(i2))

现在使用aes(x=t, ...)进行绘图。

关于r - ggplot2中没有数据时换行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14821064/

10-12 17:59
查看更多