簡體   English   中英

用 R 中的 ggplot 按周繪圖

[英]Plotting by week with ggplot in R

我有以下數據:

set.seed(123)
timeseq <- as.Date(Sys.time() + cumsum(runif(1000)*86400))
data <- rnorm(1000)
df <- data.frame(timeseq,data)

我想知道是否有人有關於如何按周匯總data的方法。 我試圖做的是繪制一個時間序列 ggplot,所以如果我可以跳過這一步並讓 ggplot 處理它,那就更好了。 一整天都被困在這個問題上。

另一種使用 dplyr 按周手動聚合的方法。

library(dplyr)
df$weeks <- cut(df[,"timeseq"], breaks="week")
agg <- df %>% group_by(weeks) %>% summarise(agg=sum(data))
ggplot(agg, aes(as.Date(weeks), agg)) + geom_point() + scale_x_date() +
    ylab("Aggregated by Week") + xlab("Week") + geom_line()

在此處輸入圖片說明

您還可以使用scale_x_date()函數的breaks參數聚合日期美學。

ggplot(df, aes(x = timeseq, y = data)) +
    stat_summary(fun.y = sum, geom = "line") +
    scale_x_date(labels = date_format("%Y-%m-%d"),
                 breaks = "1 week")

要獲得星期,我們可以使用lubridate庫,使用floor_date函數,如下所示:

library(lubridate)
df$week <- floor_date(df$timeseq, "week")

我們可以使用ggplot通過做一個統計摘要來繪制數據(可能有更好的方法?),它看起來像這樣:

stat_sum_single <- function(fun, geom="point", ...) {
  stat_summary(fun.y=fun, colour="red", geom=geom, size = 3, ...)
}

ggplot(df, aes(x=floor_date(timeseq, "week"), y=data)) + 
  stat_sum_single(sum, geom="line") + 
  xlab("week")

這將有輸出:

在此處輸入圖片說明

我想在使用包@chappers想法擴大lubridate ,但在一個完全管道的方式。

library(dplyr)
library(ggplot2)
library(lubridate)
set.seed(123)
data.frame(
  timeseq = as.Date(Sys.time() + cumsum(runif(1000) * 86400)),
  data = rnorm(1000)
) %>%
  mutate(timeseq = floor_date(timeseq, unit = "week")) %>%
  group_by(timeseq) %>%
  summarise(data = sum(data)) %>%
  ggplot() +
  geom_line(aes(x = timeseq, y = data))

如果您已經將data.frame行存儲為對象,請用df替換它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM