繁体   English   中英

r - 绘制甘特图,其中一个类别中存在多个时期

[英]r - plotting gantt chart where multiple periods exist within one category

我从另一篇文章中借用了示例数据并进行了修改以适合我的情况。 在甘特图中添加阴影以描绘周末

我绘制甘特图的问题是我的数据在类别中包含多个时期。 在下面的示例中,我为“撰写介绍”添加了两个句点,并为“撰写结果”添加了一个句点。

另外,我想为符合条件的特定时期着色。 在这里,如果某个时期的任何部分落在 5 月或 8 月,我都会标记它。

似乎在一个类别中最多有两个时期工作正常。 但是当有三个时期时,它们会合并为一个时期?!

我的真实数据集要复杂得多,其中一个类别有时会超过 10 个周期,并且具有非常明确的标记标准。

我不确定如何解决这个问题。

在此处输入图片说明


require(reshape2)
require(ggplot2)


# Create a list of tasks name strings.
tasks <- c("Write introduction", "Parse citation data",
           "Construct data timeline",
           "Write methods", "Model formulation", 
           "Model selection", "Write results", "Write discussion",
           "Write abstract and editing",
           
           "Write introduction", "Write introduction", "Write results")

# Compile dataframe of task names, and respective start and end dates.
dfr <- data.frame(
  name = factor(tasks, levels = tasks[1:9]),
  start.date = as.Date(c("2018-04-09", "2018-04-09", "2018-04-16",
                         "2018-04-30", "2018-04-16", "2018-05-21",
                         "2018-06-04", "2018-07-02", "2018-07-30",
                         
                         "2018-05-15", "2018-06-03", "2018-07-25"
                         )),
  end.date = as.Date(c("2018-04-30", "2018-04-20", "2018-05-18",
                       "2018-06-01", "2018-05-18", "2018-06-01",
                       "2018-06-29", "2018-07-27", "2018-08-31",
                       
                       "2018-05-29", "2018-06-20", "2018-08-15")),
  flag = c(0, 0, 1, 
           1, 1, 1,
           0, 0, 1, 
           1, 0, 1)
)

# Merge start and end dates into durations.
mdfr <- melt(dfr, measure.vars = c("start.date", "end.date"))



# gannt chart

ggplot(mdfr) +
  
  geom_line(aes(value, name, colour = as.factor(flag)), size = 4) +
  labs(title = "Project gantt chart",
       x = NULL,
       y = NULL) +
  theme_minimal() 

我通过跳过melt并使用geom_linerange而不是geom_line来解决它

ggplot(dfr) +
  geom_linerange(aes(y = name, 
                     xmin = start.date,
                     xmax = end.date,
                     colour = as.factor(flag)),
                 
                 size = I(5)) +
  theme_minimal()

不过,最好知道为什么它不能与 geom_line 一起使用。 如果有人可以帮助我,我将不胜感激!

在此处输入图片说明

如果您为每对开始/结束日期保留一个标识符, geom_line方法应该可以工作,并将其指定为分组变量,以便 ggplot 知道哪些坐标属于同一行:

dfr$row.id <- seq(1, nrow(dfr)) # use row id to identify each original row uniquely
mdfr <- melt(dfr, measure.vars = c("start.date", "end.date"))

ggplot(mdfr,
       aes(x = value, y = name, colour = factor(flag), group = row.id)) + # add group aesthetic
  geom_line(size = 4) +
  labs(title = "Project gantt chart",
       x = NULL,
       y = NULL) +
  theme_minimal() 

阴谋

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM