我正在try 使用ggplot2来创建甘特图.

    library(ggplot2)
    
    # Create an example dataframe with date-time values
    phase_summary <- data.frame(
      Phase = c("Phase 1", "Phase 2", "Phase 3", "Phase 4"),
      Starts = as.POSIXct(c("2021-01-01 09:00:00", "2021-02-01 12:30:00", "2021-03-01 10:15:00", "2021-04-01 08:45:00")),
      Finishes = as.POSIXct(c("2021-01-31 16:00:00", "2021-02-28 17:30:00", "2021-03-31 14:45:00", "2021-04-30 13:15:00"))
    )
    
    # Create a Gantt chart
    ggplot(data = phase_summary, aes(x = Phase, y = 1, yend = 1, xmin = Starts, xmax = Finishes)) +
      geom_linerange(size = 5, color = "steelblue") +
      scale_y_continuous(breaks = 1, labels = "") +
      scale_x_datetime(date_labels = "%b %d\n%Y", expand = c(0.1, 0)) +
      labs(title = "Project Timeline",
           x = "Phases",
           y = "") +
      theme_bw()

我收到以下错误:

错误:无效输入:TIME_TRANS处理POSIXct类的对象 只有这样.

这让我很困惑,因为开始和结束都是POSIXct

推荐答案

以下是我的建议:

# Create an example dataframe with date-time values
phase_summary <- data.frame(
  Phase = c("Phase 1", "Phase 2", "Phase 3", "Phase 4"),
  Starts = as.POSIXct(c("2021-01-01 09:00:00", "2021-02-01 12:30:00", "2021-03-01 10:15:00", "2021-04-01 08:45:00")),
  Finishes = as.POSIXct(c("2021-01-31 16:00:00", "2021-02-28 17:30:00", "2021-03-31 14:45:00", "2021-04-30 13:15:00"))
)

# Create a Gantt chart
ggplot(data = phase_summary, aes(x = Starts, xend=Finishes,y = Phase, yend = Phase, color=Phase)) +
  scale_x_datetime(date_labels = "%b %d\n%Y", expand = c(0.1, 0))+
  labs(title = "Project Timeline",
       x = "Time",
       y = "Phase") +
  theme_bw() + geom_segment(size=8) 

enter image description here

R相关问答推荐

无法在我的情节中表现出显着的差异

如何在ggplot 2线性图的每个方面显示每个组的误差条?

根据选中三个复选框中的一个或两个来调整绘图

使用case_match()和char数组重新编码值

如何将旋转后的NetCDF转换回正常的纬度/经度网格,并使用R?

Ggplot2中的重复注记

可以替代与NSE一起使用的‘any_of()’吗?

用约翰逊分布进行均值比较

无法定义沿边轨迹的 colored颜色 渐变(与值无关)

R中有约束的优化问题:如何用复数和对数效益函数解决问题?

TreeNode打印 twig 并为其上色

如何使用For-R循环在向量中找到一系列数字

自动STAT_SUMMARY统计与手动标准误差之间的差异

使用R将简单的JSON解析为嵌套框架

如何在使用Alpha时让geom_curve在箭头中显示恒定透明度

有没有办法将基于每个值中出现的两个关键字或短语的字符串向量重新编码为具有这两个值的新向量?

R仅当存在列时才发生变异

GOGPLATE geom_boxploy色彩疯狂

根据向量对列表元素进行排序

R:水平旋转图