r - 如何以时间单位将时间序列数据绘制为箱线图?
问题描述
我有以下测试时间序列数据。我想绘制一个每日/每周/每月的箱线图。但事实并非如此。谁能告诉我如何解决这个问题?
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")
解决方案
我们可以使用ceiling_date
from 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))
推荐阅读
- r - 在 R 中模拟数据以防止计划不周
- twitter-bootstrap - 引导导航栏切换器汉堡按钮没有响应点击
- javascript - 将颜色更改为开尔文
- function - Julia 结构内的函数属性性能不佳
- mysql - mysql 查询将返回用户每月和每周创建的帖子的平均值
- css - 相对于父元素垂直定位元素,但相对于视口水平定位
- javascript - 不确定如何使用 express-zip 将多个文件下载为 zip 文件
- html - 无法为 Angular Material 中的下拉菜单设置默认值
- python - 使用服务帐户返回密钥错误的 Google API
- c++ - 一个 ”?” 在字符串之前