ggplot 通过过滤一列中的数据来创建分组箱线图

ggplot create grouped boxplots by filtering data in one column

我想通过按年份 < 1993 和年份 > 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=))

我可以为此使用填充吗?

有没有一种简单的方法可以将所有数据保存在一个 data.table 中?并通过过滤年份变量创建分组箱线图?

您似乎想要按条件对年份进行分组?

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

此代码生成以下图: