Home > Software design >  Is it possible to make a gantt chart in ggplot with multiple time intervals on the same chart?
Is it possible to make a gantt chart in ggplot with multiple time intervals on the same chart?

Time:12-15

I am trying to create a gantt chart in R where I can have the timeline of Actual Start and Actual Finish vs. Proposed Start and Proposed Finish on the same chart as a comparison. So the y-axis would say "Warehouse" twice and then the x-axis would have the segement for each time interval.

Below is the code I used to attempt this, but it clearly doesn't work.

As always, I appreciate any and all assistance. Thank you.

library(tidyverse)


project_data <- tibble(
  Project_Name = c("Warehouse"),
  Proposed_Start = c("05-01-2022"),
  Proposed_Finish = c("12-01-2022"),
  Actual_Start = c("07-01-2022"),
  Actual_Finish = c("12-31-2022")
)


project_data %>%
      ggplot()  
        aes(x = Proposed_Start, xend = Proposed_Finish,
            y = Project_Name, yend = Project_Name,
            color = "green")  
        geom_segment(size = 8)  
        aes(x = Actual_Start, xend = Actual_Finish,
            y = Project_Name, yend = Project_Name,
            color = "red")  
        geom_segment(size = 8)  
        labs(title = "Comparing Project Proposed and Actual Dates",
             x = "Start and Finish Dates",
             y = "Project Name")

CodePudding user response:

You can use pivot_longer, which will put your start dates in one column, your finish dates in a different column, and create a column to label the rows as "Proposed" and "Actual". You can dodge the lines so they are both visible at the same point on the y axis. This is easier if you switch to geom_linerange. After pivoting, you only need a single geom layer, since you can map the Proposed/Actual column to colour.

This should work for multiple projects in the same plot.

project_data %>%
  pivot_longer(-1, names_sep = "_", names_to = c("Type", ".value")) %>%
  ggplot(aes(xmin = Start, xmax = Finish, color = Type,
             y = Project_Name))  
  geom_linerange(size = 8, position = position_dodge(width = 0.5))  
  labs(title = "Comparing Project Proposed and Actual Dates",
       x = "Start and Finish Dates",
       y = "Project Name")  
  scale_colour_manual(values = c("orange", "deepskyblue4"))  
  theme_minimal(base_size = 16)

enter image description here

  • Related