每天在每次观察中绘制一个点

时间:2016-03-22 22:44:48

标签: r ggplot2 lubridate

我的数据有2个变量,一个时间戳和一个组。像这样:

df.plot <- structure(list(Timestamp = structure(c(1441814593, 1441818193, 
                                                  1441821398, 1441821449, 1441828375, 1441837436, 1441843661, 1441873127, 
                                                  1441885583, 1441966341, 1441985621, 1442048926, 1442321691, 1442329081, 
                                                  1442349761, 1442408140, 1442417679, 1442508871, 1442513339, 1442514010, 
                                                  1442525088, 1442562304, 1442564744, 1442569290, 1442569482, 1442571416, 
                                                  1442606687), tzone = "UTC", class = c("POSIXct", "POSIXt")), 
                          group = c("A", "B", "B", "B", "B", "B", "B", "A", "B", "A", 
                                    "B", "A", "A", "A", "B", "B", "B", "B", "A", "B", "B", "A", 
                                    "A", "A", "A", "B", "A")), class = "data.frame", .Names = c("Timestamp", 
                                                                                                "group"), row.names = c(NA, -27L))

时间戳有第二个,但我只想使用日期。也就是说,将2015-09-09 16:03:13转换为2015-09-09。

对于每个日期,我想画一个点。如果我必须在同一天进行观察,我想在彼此之上绘制一个点。另外,我想使用facet作为group变量。

我能够做类似于我想要的事情:

ggplot(df.plot, aes(x=Timestamp)) + 
  geom_dotplot(method="histodot") + 
  facet_grid(group ~ .)

如何告诉ggplot只使用日期,如何更改y轴的比例以显示计数?

2 个答案:

答案 0 :(得分:3)

date创建Timestamp列,并按常规绘制

df.plot$date <- as.Date(df.plot$Timestamp, format="%Y-%m-%d %H:%M:%s")

ggplot(data=df.plot, aes(x=date)) +
    geom_dotplot(method="histodot") + ylim(0,7) +
    facet_wrap(~group)

当然,您实际上不必创建新变量,您可以通过ggplot调用

完成所有操作
ggplot(data=df.plot, aes(x=as.Date(Timestamp))) +
    geom_dotplot(method="histodot") + ylim(0,7) +
    facet_wrap(~group)

为了向您提供您的计数,您可以修改数据以包含“计数”数据。变量(使用您喜欢的任何方法,dplyrdata.table等。)

我在这里使用data.table

library(data.table)
setDT(df.plot)

df.plot[, date := as.Date(Timestamp)]
df.plot[, nCount := seq(1:.N), by=.(date, group)]

ggplot(data=df.plot, aes(x=date, y=nCount)) +
    geom_point() +
    facet_wrap(~group)

答案 1 :(得分:2)

ggplot(df.plot, aes(x=as.Date(Timestamp))) + 
  geom_dotplot(binwidth=1) +
  coord_fixed(ratio=1) + 
  ylim(0,7) +
  facet_grid(group ~ .) 

enter image description here