首页 > 解决方案 > 如何以时间单位将时间序列数据绘制为箱线图?

问题描述

我有以下测试时间序列数据。我想绘制一个每日/每周/每月的箱线图。但事实并非如此。谁能告诉我如何解决这个问题?

library(ggplot2)
library(dplyr)
data <- data.frame(
  day = rep(as.Date("2017-06-14") - 0:364, 100),
  value = unlist(replicate(100, list(rnorm(365) + seq(-140, 224)^2 / 10000)))
)

p = ggplot(data, aes(group=day, y=value)) + geom_boxplot() + scale_x_date(date_breaks = "1 week", date_labels = "%W")

标签: rggplot2

解决方案


我们可以使用ceiling_datefrom lubridate,并将其用于geom_boxplot

library(dplyr)
library(ggplot2)
library(lubridate)
data  %>% 
    mutate(week = ceiling_date(day, "week")) %>%
    ggplot(aes(group = week, y = value)) + 
    geom_boxplot() + 
    scale_x_date(date_breaks = "1 week", date_labels = "%W")

或者它可能是

data  %>%
      mutate(week = format(day, "%W")) %>%
      ggplot(aes(x = week, y = value, fill = factor(week))) + 
        geom_boxplot() + 
        theme_bw() + 
        theme(legend.position = "none",
           axis.text.x = element_text(angle = 90,  hjust=1))

在此处输入图像描述


推荐阅读