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
CodePudding user response:
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")
CodePudding user response:
Another option is to use facet_wrap
:
library(ggplot2)
dat %>%
mutate(Date_wrap = format(as.Date(Date), "%Y-%m")) %>%
ggplot(aes (y = Value, fill = Location))
geom_boxplot()
facet_wrap(~ Date_wrap, scales = "free", strip.position = "bottom")
theme_minimal()
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())