John Bowyer
John Bowyer

Reputation: 1503

How to use facet_grid with a gantt chart R with ggplot2

I have a basic gantt chart with the following code

require("tidyverse")

task0 <- c('Strategy 1', 'Strategy 1', '2017-04-01', '2020-04-01',0, "Strategy")
task1 <- c('Strategy 1', 'Collect data', '2017-04-01', '2018-04-01',1, "In Progress")
task2 <- c('Strategy 1', 'Clean data', '2018-04-01', '2018-06-01', 1, "Completed")
task3 <- c('Strategy 1', 'Analyse data', '2018-06-01', '2019-04-01',1, "Discontinued")
task4 <- c('Strategy 1', 'Write report', '2019-04-01', '2020-04-01', 1, "Planned")
task10 <- c('Strategy 2', 'Strategy 2', '2017-04-01', '2020-04-01',0, "Strategy")
task11 <- c('Strategy 2', 'Collect data again', '2017-04-01', '2018-04-01',1, "In Progress")
task12 <- c('Strategy 2', 'Clean data again', '2018-04-01', '2018-06-01', 1, "Completed")
task13 <- c('Strategy 2', 'Analyse data again', '2018-06-01', '2019-04-01',1, "Discontinued")
task14 <- c('Strategy 2', 'Write report again', '2019-04-01', '2020-04-01', 1, "Planned")

dataset <- as.data.frame(rbind(task0, task1, task2, task3, task4,task10, task11, task12, task13, task14))
names(dataset) <- c('StrategyName', 'Activity', 'Start', 'End', 'ActivitySort', "Status")


dataset <-  as_tibble(dataset)
dataset <-  dataset  %>% mutate(StartSort = as.Date(Start, "%Y-%m-%d" ))
dataset <-  dataset %>% arrange(desc(StrategyName), desc(ActivitySort), desc(StartSort),Activity,  End)

acts <- c("Strategy", "Completed","In Progress", "Discontinued","Planned")
actcols <- c("#000000","#548235", "#2E75B6", "#BF9000", "#7030A0")
els <-unique(dataset$Activity)

g.gantt <- gather(dataset, "state", "date", 3:4) %>% mutate(date = as.Date(date, "%Y-%m-%d" ), Status=factor(Status, acts[length(acts):1]), Activity=factor(Activity, els))

plot <- ggplot(g.gantt, aes(x = date, y = Activity, color = Status, group=Activity)) +
  geom_line(size = 5) +
  scale_color_manual(values=actcols, name="Status",  breaks = acts, limits = acts) +
  labs(x="Project year", y=NULL, title="Activity timeline")

plot + theme(axis.text.y = element_text(hjust = 0))

That produces the following chart:

enter image description here

I would like to make the chart more readable by using facet_grid and adding the following code

+ facet_grid(rows = vars(StrategyName))

Unfortunately this produces the following chart with every activity repeated for every strategy.

enter image description here

How can I facet and remove the blank/duplicated rows in each facet?

Upvotes: 3

Views: 652

Answers (1)

John Bowyer
John Bowyer

Reputation: 1503

The following code seems to have addressed the duplication problem.

+ facet_grid(rows = vars(StrategyName),  scales="free")

Upvotes: 2

Related Questions