'How to plot time series data as boxplot in a time unit?
I have the following test time-series data. I'd like to plot a daily/weekly/monthly boxplot. But it doesn't do so. How can I fix the problem?
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")
Solution 1:[1]
We can use ceiling_date from lubridate, and use that in 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")
Or it could be
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))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

