I cannot get geom_boxplot to display both of my groups (Location) for each Date in a time series.
Example Data:
set.seed(321)
dat <- data.frame(matrix(ncol = 3, nrow = 18))
colnames(dat)[1:3] <- c("Date","Location","Value")
dat$Value <- round(rnorm(18, 100,50),0)
dat$Location <- rep(c("Location 1","Location 2"), each = 9)
st <- as.Date("2022-05-15")
en <- as.Date("2022-07-15")
dat$Date <- rep(seq.Date(st,en,by = '1 month'),6)
str(dat)
This shows each group (Location) however it does not provide a boxplot for each Date
library(ggplot2)
ggplot(dat, aes(x = Date, y = Value, fill = Location)) +
geom_boxplot() +
scale_x_date(date_labels = "%b %Y")
This provides a boxplot for each date but it does not show each group
ggplot(dat, aes(x = Date, y = Value, fill = Location)) +
geom_boxplot(aes(group = Date)) +
scale_x_date(date_labels = "%b %Y")
The ideal figure would have a boxplot for each Date and each Location
>Solution :
You can use interaction(Date, Location) to get the type of plot you’re after:
ggplot(dat, aes(x = Date, y = Value, fill = Location, group = interaction(Date, Location))) +
geom_boxplot() +
scale_x_date(date_labels = "%b %Y")
