How to Create a Gantt Chart in R Using ggplot2

Creating a gantt chart in R using ggplot2

A gantt chart is a type of chart that shows the start and end times of various events.

This tutorial explains how to create a gantt chart in R using the package ggplot2.

Creating a Gantt Chart in R Using ggplot2

Suppose we have the following dataset that shows the start and end times for the shifts of four different workers at a store:

#create data frame
data <- data.frame(name = c('Bob', 'Greg', 'Mike', 'Andy'), 
start = c(4, 7, 12, 16),
end = c(12, 11, 8, 22),
shift_type = c('early', 'mid_day', 'mid_day', 'late')
)
data

#  name start end shift_type
#1 Bob      4  12      early
#2 Greg     7  11    mid_day
#3 Mike    12   8    mid_day
#4 Andy    16  22       late

In order to create a gantt chart using ggplot2 that visualizes the start and end times for each worker, we can use the following code:

#install (if not already installed) and load ggplot2
if(!require(ggplot2)){install.packages('ggplot2')}

#create gantt chart that visualizes start and end time for each worker
ggplot(data, aes(x=start, xend=end, y=name, yend=name, color=shift_type)) +
  geom_segment()

This produces the following gantt chart:

Gantt chart example in R using ggplot2

With a couple tweaks to the layout, we can make this gantt chart look much better:

ggplot(data, aes(x=start, xend=end, y=name, yend=name, color=shift_type)) +
  theme_bw()+ #use ggplot theme with black gridlines and white background
  geom_segment(size=8) + #increase line width of segments in the chart
  labs(title='Worker Schedule', x='Time', y='Worker Name')

This produces the following chart:

In addition, if you would like to define the exact colors to be used in the chart, you can use the following code:

ggplot(data, aes(x=start, xend=end, y=name, yend=name, color=shift_type)) +
  theme_bw()+ #use ggplot theme with black gridlines and white background
  geom_segment(size=8) + #increase line width of segments in the chart
  labs(title='Worker Schedule', x='Time', y='Worker Name') +
  scale_colour_manual(values = c('pink', 'purple', 'blue'))

This produces the following chart with colors pink, purple, and blue to represent the different shift types:

Gantt Chart in R with custom colors in ggplot2

Leave a Reply

Your email address will not be published. Required fields are marked *