首页 > 解决方案 > 在哪里以及如何在 ggplot 中应用过滤器

问题描述

我有一组名为“剧院”的数据

我用这段代码准备了所有数据的箱线图:

数据中有一个名为“部门”的列,该列中的数据设置为“住院患者”或“日间病例”。我想创建两个箱线图,一个仅使用 Inpatient 行,一个仅使用 Day case 行,我想使用过滤器...

非常感谢你能帮助一个菜鸟解决他的第一个问题。

我试图将其标记到上述代码的末尾,但出现错误,我还在每一行代码之前尝试了过滤器,认为代码的层次结构可能是一个因素(???)

   ggplot(data = theatre) +
   (mapping = aes( x = speciality_groups, y = process_time, fill = 
   speciality_groups)) +
   geom_boxplot() + labs(x = "Sector", fill = "sector") +
   theme_minimal() + 
   theme(axis.text.x=element_text (angle =45, hjust =1))'

尝试使用:

   filter(theatre, sector == "Inpatient")

我收到以下错误:

ggplot(data = theatre) + (mapping = aes(x = speciality_groups, : 二元运算符的非数字参数另外:警告消息:不兼容的方法 ("+.gg"、"Ops.data.frame") “+”

标签: rggplot2

解决方案


在使用 ggplot2 之前创建一个变量

library(tidyverse)

theatre_inpatient <- theatre %>%
filter(sector == "Inpatient")

theatre_inpatient_boxplot <- theatre_inpatient %>%
   ggplot(., aes(x = speciality_groups, y = process_time, fill = 
   speciality_groups)) +
   geom_boxplot() + labs(x = "Sector", fill = "sector") +
   theme_minimal() + 
   theme(axis.text.x=element_text (angle =45, hjust =1))

然后你可以用“Day case”做同样的事情

另一种方法是使用 facet_grid

library(tidyverse)

ggplot(theatre, aes(x = speciality_groups, y = process_time, fill = 
   speciality_groups)) +
   geom_boxplot() + labs(x = "Sector", fill = "sector") +
   theme_minimal() + 
   theme(axis.text.x=element_text (angle =45, hjust =1)) +
   facet_grid(. ~ sector)

推荐阅读