where and how to apply a filter in a ggplot

Viewed 21049

I have a set of data called 'theatres'

I have prepared a box plot of all the data with this code:

There is a column in the data called 'sector' and the data within this column is set to either 'Inpatient' or 'Day case'. I'd like to create two boxplots, one with using only the Inpatient rows, and one with only the Day case rows, i thought to use a filter...

Many thanks if you can help a noob with his first ever question.

I have tried to tag this onto the end of the above code but i get an error, i have also tried the filter before each line of code thinking that the hierachy of the code might be a factor (???)

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

trying to use:

   filter(theatre, sector == "Inpatient")

I get the following er ror:

Error in ggplot(data = theatre) + (mapping = aes(x = speciality_groups, : non-numeric argument to binary operator In addition: Warning message: Incompatible methods ("+.gg", "Ops.data.frame") for "+"

1 Answers

Creating a variable before using 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))

Then you can do the same thing with "Day case"

The other way is to use 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)
Related