Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get geom_boxplot to change colors for groups in a time series?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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")

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading