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

我想通过按 1993年的年份过滤一列中的数据来创建分组箱形图。

library(tidyverse)
library(data.table)

months <- c(7,7,8,8)
years <- c(1991,1992,1993,1994,1995,1991,1995)
values <- c(12.1,11.5,12.0,12.4,12.2,11.8,11.4,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中?并通过过滤Years变量来创建分组的箱线图?

ldf2771 回答:ggplot通过在一列中过滤数据来创建分组的箱线图

您似乎想按条件将年份分组?

library(tidyverse)
library(data.table)

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

此代码产生以下图: Plot

本文链接:https://www.f2er.com/3163625.html

大家都在问