0

I want to create grouped boxplots by filtering data in one column by years < 1993 and years > 1993

library(tidyverse)
library(data.table)

months <- c(7,7,7,7,7,8,8,8,8,8)
years <- c(1991,1992,1993,1994,1995,1991,1992,1993,1994,1995)
values <- c(12.1,11.5,12.0,12.4,12.2,11.8,11.4,12.2,11.8,12.0)

dt <- data.table(month=months,year=years,value=values)

aug_dt_lessthan1993 <- dt %>% 
  filter(month==8,year<1993)

aug_dt_greaterthan1993 <- dt %>% 
  filter(month==8,year>1993)

p <- ggplot(aug_dt_lessthan1993, aes(x=1,y=value,fill=))

Can I use fill for this?

Is there an easy way keep all the data in one data.table? And create grouped boxplots by filtering the years variable?

1
  • 2
    Consider adding the package dependencies to the beginning of your code snippet to make your question reproducible. Commented Nov 4, 2019 at 23:53

1 Answer 1

2

It seems like you want the year grouped by a condition?

library(tidyverse)
library(data.table)

months <- c(7,7,7,7,7,8,8,8,8,8)
years <- c(1991,1992,1993,1994,1995,1991,1992,1993,1994,1995)
values <- c(12.1,11.5,12.0,12.4,12.2,11.8,11.4,12.2,11.8,12.0)

dt <- data.table(month=months,year=years,value=values)

MONTH=8
YEAR=1993

dt %>% 
  # Apply filter for month
  filter(
    month == MONTH
  ) %>% 
  # Tag year based on your condition
  mutate(year_group = ifelse(year > YEAR, "After 1993", "Before 1993")) %>% 
  # Create plot
  ggplot(aes(y=value, x=1, fill=year_group)) +
  geom_boxplot()

This code produces the following plot: Plot

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.