【问题标题】:Gantt charts with R [closed]带有 R 的甘特图 [关闭]
【发布时间】:2010-08-23 18:06:02
【问题描述】:

有人用 R 创建了Gantt chart 吗? 如果可能的话,我正在寻找一些复杂的东西(看起来或多或少像this)。

附:我可以没有依赖箭头。

【问题讨论】:

    标签: r charts gantt-chart


    【解决方案1】:

    现在有一些优雅的方法可以在 R 中生成甘特图。

    使用坎德拉

    library(candela)
    
    data <- list(
        list(name='Do this', level=1, start=0, end=5),
        list(name='This part 1', level=2, start=0, end=3),
        list(name='This part 2', level=2, start=3, end=5),
        list(name='Then that', level=1, start=5, end=15),
        list(name='That part 1', level=2, start=5, end=10),
        list(name='That part 2', level=2, start=10, end=15))
    
    candela('GanttChart',
        data=data, label='name',
        start='start', end='end', level='level',
        width=700, height=200)
    

    使用 DiagrammeR

    library(DiagrammeR)
    
    mermaid("
    gantt
    dateFormat  YYYY-MM-DD
    title A Very Nice Gantt Diagram
    
    section Basic Tasks
    This is completed             :done,          first_1,    2014-01-06, 2014-01-08
    This is active                :active,        first_2,    2014-01-09, 3d
    Do this later                 :               first_3,    after first_2, 5d
    Do this after that            :               first_4,    after first_3, 5d
    
    section Important Things
    Completed, critical task      :crit, done,    import_1,   2014-01-06,24h
    Also done, also critical      :crit, done,    import_2,   after import_1, 2d
    Doing this important task now :crit, active,  import_3,   after import_2, 3d
    Next critical task            :crit,          import_4,   after import_3, 5d
    
    section The Extras
    First extras                  :active,        extras_1,   after import_4,  3d
    Second helping                :               extras_2,   after extras_1, 20h
    More of the extras            :               extras_3,   after extras_1, 48h
    ")
    

    DiagrammeR GitHub 上查找此示例以及更多内容


    如果您的数据存储在data.frame 中,您可以通过将其转换为正确的格式来创建要传递给mermaid() 的字符串。

    考虑以下几点:

    df <- data.frame(task = c("task1", "task2", "task3"),
                     status = c("done", "active", "crit"),
                     pos = c("first_1", "first_2", "first_3"),
                     start = c("2014-01-06", "2014-01-09", "after first_2"),
                     end = c("2014-01-08", "3d", "5d"))
    
    #   task status     pos         start        end
    #1 task1   done first_1    2014-01-06 2014-01-08
    #2 task2 active first_2    2014-01-09         3d
    #3 task3   crit first_3 after first_2         5d
    

    使用dplyrtidyr(或任何您喜欢的数据处理资源):

    library(tidyr)
    library(dplyr)
    
    mermaid(
      paste0(
        # mermaid "header", each component separated with "\n" (line break)
        "gantt", "\n", 
        "dateFormat  YYYY-MM-DD", "\n", 
        "title A Very Nice Gantt Diagram", "\n",
        # unite the first two columns (task & status) and separate them with ":"
        # then, unite the other columns and separate them with ","
        # this will create the required mermaid "body"
        paste(df %>%
                unite(i, task, status, sep = ":") %>%
                unite(j, i, pos, start, end, sep = ",") %>%
                .$j, 
              collapse = "\n"
        ), "\n"
      )
    )
    

    正如 @GeorgeDontas 在 cmets 中提到的,有一个 little hack 可以允许将 x 轴的标签更改为日期而不是“w.01,w.02”。

    假设您将上述美人鱼图保存在m,请执行以下操作:

    m$x$config = list(ganttConfig = list(
      axisFormatter = list(list(
        "%b %d, %Y" 
        ,htmlwidgets::JS(
          'function(d){ return d.getDay() == 1 }' 
        )
      ))
    ))
    

    这给出了:


    使用 timevis

    来自timevisGitHub

    timevis 可让您创建丰富且完全交互的时间线 R 中的可视化。时间线可以包含在 Shiny 应用程序和 R 中 markdown 文档,或从 R 控制台和 RStudio Viewer 查看。

    library(timevis)
    
    data <- data.frame(
      id      = 1:4,
      content = c("Item one"  , "Item two"  ,"Ranged item", "Item four"),
      start   = c("2016-01-10", "2016-01-11", "2016-01-20", "2016-02-14 15:00:00"),
      end     = c(NA          ,           NA, "2016-02-04", NA)
    )
    
    timevis(data)
    

    这给出了:


    使用情节

    我偶然发现了这个post 提供了另一种使用plotly 的方法。这是一个例子:

    library(plotly)
    
    df <- read.csv("https://cdn.rawgit.com/plotly/datasets/master/GanttChart-updated.csv", 
                   stringsAsFactors = F)
    
    df$Start  <- as.Date(df$Start, format = "%m/%d/%Y")
    client    <- "Sample Client"
    cols      <- RColorBrewer::brewer.pal(length(unique(df$Resource)), name = "Set3")
    df$color  <- factor(df$Resource, labels = cols)
    
    p <- plot_ly()
    for(i in 1:(nrow(df) - 1)){
      p <- add_trace(p,
                     x = c(df$Start[i], df$Start[i] + df$Duration[i]), 
                     y = c(i, i), 
                     mode = "lines",
                     line = list(color = df$color[i], width = 20),
                     showlegend = F,
                     hoverinfo = "text",
                     text = paste("Task: ", df$Task[i], "<br>",
                                  "Duration: ", df$Duration[i], "days<br>",
                                  "Resource: ", df$Resource[i]),
                     evaluate = T
      )
    }
    
    p
    

    这给出了:

    然后您可以添加其他信息和注释、自定义字体和颜色等(详见博文)

    【讨论】:

    • 确实不错。然而,在我看来,使用存储在数据框中的数据自动创建传递给美人鱼的字符串似乎相当困难。
    • 是否可以将日期显示为 x 轴标签,而不是“w.01”、“w.02”等?
    • 覆盖甘特图以允许自定义日期轴而不是 0-52 周刻度:github.com/rich-iannone/DiagrammeR/issues/77
    • 该代码在 Rstudio 中使用 DiagrameR 和 Mermaid 完美运行,但在 PowerBI 中使用它时出现错误错误消息:未创建图像。 R 代码没有产生任何视觉效果。确保您的 R 脚本生成到 R 默认设备的绘图。任何想法任何人都感谢佩迪
    • timevisR 中的解决方案看起来很酷很简单。 :-)
    【解决方案2】:

    一个简单的ggplot2甘特图。

    首先,我们创建一些数据。

    library(reshape2)
    library(ggplot2)
    
    tasks <- c("Review literature", "Mung data", "Stats analysis", "Write Report")
    dfr <- data.frame(
      name        = factor(tasks, levels = tasks),
      start.date  = as.Date(c("2010-08-24", "2010-10-01", "2010-11-01", "2011-02-14")),
      end.date    = as.Date(c("2010-10-31", "2010-12-14", "2011-02-28", "2011-04-30")),
      is.critical = c(TRUE, FALSE, FALSE, TRUE)
    )
    mdfr <- melt(dfr, measure.vars = c("start.date", "end.date"))
    

    现在画出情节。

    ggplot(mdfr, aes(value, name, colour = is.critical)) + 
      geom_line(size = 6) +
      xlab(NULL) + 
      ylab(NULL)
    

    【讨论】:

    • 我只能创建一些数据两次 :-)
    • @gd047:这需要双手捂脸。白痴问题现已修正。
    • 这很好,但我主要寻找的是一种为每个任务显示多个栏的方法(如您在我给出的示例中所见),例如一个用于基线,一个用于实际任务持续时间。有没有办法做这样的事情?
    【解决方案3】:

    我知道,这是一个非常老的问题,但也许值得留在这里 - 对我找到的这个问题的答案不满意 - 几个月前,我制作了一个用于制作基于 ggplot2 的甘特图的基本包:ganttrify(更多详细信息在包的自述文件中)。

    示例输出:

    【讨论】:

    • 这是一个很棒的包,感谢您提供它!
    • 看起来不错,到目前为止安装不合作。将跟进并使其发挥作用。
    【解决方案4】:

    考虑使用package projmanr(2017 年 8 月 23 日在 CRAN 上发布的 0.1.0 版)。

    library(projmanr)
    
    # Use raw example data
    (data <- taskdata1)
    

    taskdata1:

      id name duration pred
    1  1   T1        3     
    2  2   T2        4    1
    3  3   T3        2    1
    4  4   T4        5    2
    5  5   T5        1    3
    6  6   T6        2    3
    7  7   T7        4 4,5 
    8  8   T8        3  6,7
    

    现在开始准备甘特图:

    # Create a gantt chart using the raw data
    gantt(data)
    

    # Create a second gantt chart using the processed data
    res <- critical_path(data)
    gantt(res)
    

    # Use raw example data
    data <- taskdata1
    # Create a network diagram chart using the raw data
    network_diagram(data)
    

    # Create a second network diagram using the processed data
    res <- critical_path(data)
    network_diagram(res)
    

    【讨论】:

    • 这是一个很棒的包推荐。谢谢。
    【解决方案5】:

    试试这个:

    install.packages("plotrix")
    library(plotrix)
    ?gantt.chart
    

    【讨论】:

      【解决方案6】:

      plan支持创建燃尽图和甘特图 图表并包含plot.gantt 函数。见this R Graphical Manual page

      另请参阅如何使用 Plotly 的 R API GANTT CHARTS IN R USING PLOTLY 在 R 中制作。

      【讨论】:

      【解决方案7】:

      您可以使用GoogleVis package

      datTL <- data.frame(Position=c(rep("President", 3), rep("Vice", 3)),
                          Name=c("Washington", "Adams", "Jefferson",
                                 "Adams", "Jefferson", "Burr"),
                          start=as.Date(x=rep(c("1789-03-29", "1797-02-03", 
                                                "1801-02-03"),2)),
                          end=as.Date(x=rep(c("1797-02-03", "1801-02-03", 
                                              "1809-02-03"),2)))
      
      Timeline <- gvisTimeline(data=datTL, 
                               rowlabel="Name",
                               barlabel="Position",
                               start="start", 
                               end="end",
                               options=list(timeline="{groupByRowLabel:false}",
                                            backgroundColor='#ffd', 
                                            height=350,
                                            colors="['#cbb69d', '#603913', '#c69c6e']"))
      plot(Timeline)
      

      来源:https://cran.r-project.org/web/packages/googleVis/vignettes/googleVis_examples.html

      【讨论】:

        【解决方案8】:

        对我来说,Gvistimeline 是执行此操作的最佳工具,但它所需的在线连接对我没有用。因此我创建了一个名为vistime 的包,它使用plotly(类似于@Steven Beaupré 的答案),因此您可以放大等:

        https://github.com/shosaco/vistime

        vistime:使用 plotly.js 创建交互式时间线或甘特图。这 图表可以包含在闪亮的应用程序中并通过 plotly_build().

        install.packages("vistime")    
        library("vistime")  
        
        dat <- data.frame(Position=c(rep("President", 3), rep("Vice", 3)),
                      Name = c("Washington", "Adams", "Jefferson", "Adams", "Jefferson", "Burr"),
                      start = rep(c("1789-03-29", "1797-02-03", "1801-02-03"), 2),
                      end = rep(c("1797-02-03", "1801-02-03", "1809-02-03"), 2),
                      color = c('#cbb69d', '#603913', '#c69c6e'),
                      fontcolor = rep("white", 3))
        
        vistime(dat, events="Position", groups="Name", title="Presidents of the USA")
        

        【讨论】:

          【解决方案9】:

          我使用并修改了 Richie 的上述示例,效果很好。修改后的版本展示了他的模型如何转化为摄取 CSV 数据而不是手动提供的文本项。

          注意:Richie 的回答没有表明上面/下面的代码需要 2 个包( reshapeggplot2 )才能工作。

          rawschedule <- read.csv("sample.csv", header = TRUE) #modify the "sample.csv" to be the name of your file target. - Make sure you have headers of: Task, Start, Finish, Critical OR modify the below to reflect column count.
          tasks <- c(t(rawschedule["Task"]))
          dfr <- data.frame(
          name        = factor(tasks, levels = tasks),
          start.date  = c(rawschedule["Start"]),
          end.date    = c(rawschedule["Finish"]),
          is.critical = c(rawschedule["Critical"]))
          mdfr <- melt(dfr, measure.vars = c("Start", "Finish"))
          
          
          #generates the plot
          ggplot(mdfr, aes(as.Date(value, "%m/%d/%Y"), name, colour = Critical)) + 
          geom_line(size = 6) +
          xlab("Duration") + ylab("Tasks") +
          theme_bw()
          

          【讨论】:

            【解决方案10】:

            发现 ggplot 中的 geom_segment 很棒。从以前的解决方案中使用数据但不需要融化。

            library(ggplot2)
            
            tasks <- c("Review literature", "Mung data", "Stats analysis", "Write Report")
            dfr <- data.frame(
              name        = factor(tasks, levels = tasks),
              start.date  = as.Date(c("2010-08-24", "2010-10-01", "2010-11-01", "2011-02-14")),
              end.date    = as.Date(c("2010-10-31", "2010-12-14", "2011-02-28", "2011-04-30")),
              is.critical = c(TRUE, FALSE, FALSE, TRUE)
            )
            
            ggplot(dfr, aes(x =start.date, xend= end.date, y=name, yend = name, color=is.critical)) +
              geom_segment(size = 6) +
              xlab(NULL) + ylab(NULL)
            

            GantPlot

            【讨论】:

              【解决方案11】:

              PlotPrjNetworks 为项目管理提供有用的网络工具。

              library(PlotPrjNetworks)
              project1=data.frame(
              task=c("Market Research","Concept Development","Viability Test",
              "Preliminary Design","Process Design","Prototyping","Market Testing","Final Design",
              "Launching"),
              start=c("2015-07-05","2015-07-05","2015-08-05","2015-10-05","2015-10-05","2016-02-18",
              "2016-03-18","2016-05-18","2016-07-18"),
              end=c("2015-08-05","2015-08-05","2015-10-05","2016-01-05","2016-02-18","2016-03-18",
              "2016-05-18","2016-07-18","2016-09-18"))
              project2=data.frame(
              from=c(1,2,3,4,5,6,7,8),
              to=c(2,3,4,5,6,7,8,9),
              type=c("SS","FS","FS","SS","FS","FS","FS","FS"),
              delay=c(7,7,7,8,10,10,10,10))
              GanttChart(project1,project2)
              

              【讨论】:

              【解决方案12】:

              我想改进 ggplot-Answer,为每个任务添加几个条形图。

              首先生成一些数据(dfrP 是另一个答案的 data.frame,dfrR 是其他一些带有实现日期的 data.frame,mdfr 是符合以下 ggplot()-statement 的合并):

              library(reshape2)
              tasks <- c("Review literature", "Mung data", "Stats analysis", "Write Report")
              dfrP <- data.frame(
                name        = factor(tasks, levels = tasks),
                start.date  = as.Date(c("2010-08-24", "2010-10-01", "2010-11-01", "2011-02-14")),
                end.date    = as.Date(c("2010-10-31", "2010-12-14", "2011-02-28", "2011-04-30")),
                is.critical = c(TRUE, FALSE, FALSE, TRUE)
              )
              dfrR <- data.frame(
                name        = factor(tasks, levels = tasks),
                start.date  = as.Date(c("2010-08-22", "2010-10-10", "2010-11-01", NA)),
                end.date    = as.Date(c("2010-11-03", "2010-12-22", "2011-02-24", NA)),
                is.critical = c(TRUE, FALSE, FALSE,TRUE)
              )
              mdfr <- merge(data.frame(type="Plan", melt(dfrP, measure.vars = c("start.date", "end.date"))),
                data.frame(type="Real", melt(dfrR, measure.vars = c("start.date", "end.date"))), all=T)
              

              现在使用任务名称的构面来绘制这些数据:

              library(ggplot2)
              ggplot(mdfr, aes(x=value, y=type, color=is.critical))+
                geom_line(size=6)+
                facet_grid(name ~ .) +
                scale_y_discrete(limits=c("Real", "Plan")) +
                xlab(NULL) + ylab(NULL)
              

              如果没有 is.critical-information,您也可以使用 Plan/Real 作为颜色(我更喜欢),但我想使用另一个答案的 data.frame 以使其具有更好的可比性。

              【讨论】:

                【解决方案13】:

                【讨论】:

                  猜你喜欢
                  • 2020-02-12
                  • 1970-01-01
                  • 1970-01-01
                  • 2010-11-03
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2019-12-13
                  相关资源
                  最近更新 更多