在 ggplot 中应用过滤器的位置和方式

cli*_*b8b 5 r ggplot2

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

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

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

如果您能帮助菜鸟解决他的第一个问题,非常感谢。

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

   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))'
Run Code Online (Sandbox Code Playgroud)

尝试使用:

   filter(theatre, sector == "Inpatient")
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

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

KKW*_*KKW 1

使用 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))
Run Code Online (Sandbox Code Playgroud)

然后你可以用“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)
Run Code Online (Sandbox Code Playgroud)

  • 您可以直接在ggplot2中使用它 ggplot(data = Theater %&gt;% filter(sector == "InPatient"), aes(x = professional_groups, y = process_time, fill = professional_groups)) + geom_boxplot() + labs(x = "扇区”,填充=“扇区”)+ theme_minimal()+ theme(axis.text.x = element_text(角度= 45,hjust = 1)) (7认同)