Home > Enterprise >  Create subplots with ggplot2
Create subplots with ggplot2

Time:04-30

So I need to work with the hflights package and make subplots of every single weekday to show the delay of the airplanes (cancelled flights excluded). The problem is I'm not able to reproduce both x- and y-axis (x: month & y: delay in in min). I tried to use facet_wrap and facet_grid, but I'm not familiar to those function, because of not using ggplot2 that often.

CodePudding user response:

The plot will be clearer if you name the months and weekdays, arrange them in the correct order, and use a logarithmic scale on the y axis. You can use facet_grid to create subplots for each weekday.

library(hflights)
library(tidyverse)

weekday <- c('Sunday', 'Monday', 'Tuesday', 'Wednesday', 
             'Thursday', 'Friday', 'Saturday')

hflights %>% 
  mutate(WeekDay = factor(weekday[DayOfWeek], weekday),
         Month = factor(month.abb[Month], month.abb)) %>%
  filter(Cancelled == 0) %>%
  ggplot(aes(Month, DepDelay))  
  geom_boxplot()  
  scale_y_log10()  
  facet_wrap(.~WeekDay)  
  labs(x = 'Month', y = 'Departure delay (log scale)')

enter image description here

To get a single line going through each panel, you need to have an average for each unique combination of month and day. The simplest way to get this is via geom_smooth

hflights %>% 
  mutate(WeekDay = factor(weekday[DayOfWeek], weekday),
         Month = factor(month.abb[Month], month.abb)) %>%
  filter(Cancelled == 0) %>%
  ggplot(aes(Month, DepDelay, group = WeekDay))  
  geom_smooth(se = FALSE, color = 'black')  
  facet_wrap(.~WeekDay)  
  labs(x = 'Month', y = 'Departure delay (log scale)')

enter image description here

Though you can also summarize the data yourself and use geom_line

hflights %>% 
  filter(Cancelled == 0) %>%
  mutate(WeekDay = factor(weekday[DayOfWeek], weekday),
         Month = factor(month.abb[Month], month.abb)) %>%
  group_by(Month, WeekDay) %>%
  summarize(Delay = mean(DepDelay)) %>%
  ggplot(aes(Month, Delay, group = WeekDay))  
  geom_line(color = 'black')  
  facet_wrap(.~WeekDay)  
  labs(x = 'Month', y = 'Departure delay (log scale)')

enter image description here

CodePudding user response:

now since you didn't post the code let's assume you have saved a plot that plots everything in one plot under a.

a   facet_grid(rows = vars(weekday))

("weekday" is the column name where the weekdays are in, replace it if they are named diffrently)

If this isn't what you were searching for, it would be great if you could post some code...

CodePudding user response:

Suppose you want to show the ArrDelay,

hflights %>% 
  filter(Cancelled!=1) %>% 
  ggplot(aes(x=as.factor(Month), y=mean(ArrDelay,na.rm=T))) 
  geom_col() 
  labs(x='Month',y='Mean arrival Delay') 
  facet_wrap(~DayOfWeek)
  • Related