R语言 在尝试创建甘特图时

xiozqbni  于 2023-02-27  发布在  其他
关注(0)|答案(2)|浏览(113)

我正在尝试使用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的对象。
这让我很困惑,因为开始和结束是POSIX。

biswetbf

biswetbf1#

以下是我的建议:

# 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)

brgchamk

brgchamk2#

您的问题是您分配了x = Phase。虽然StartFinishPOSIXct,但绘图试图将字符变量Map到日期-时间轴,结果失败。
要获得您正在寻找的样式,您可以执行以下操作:

ggplot(data = within(phase_summary, Phase <- factor(Phase, rev(Phase))),
       aes(y = Phase, xmin = Starts, xmax = Finishes, group = Phase)) +
  geom_linerange(size = 5, color = "steelblue") +
  geom_text(aes(y = "Phase 4", label = Phase, 
                x = Starts + (Finishes - Starts)/2), nudge_y = -0.5) +
  scale_x_datetime(date_labels = "%b %d\n%Y", expand = c(0.1, 0),
                   breaks = seq(as.POSIXct("2021-01-01"), 
                                by = "month", len = 12), name = "Phases") +
  labs(title = "Project Timeline") +
  theme_bw() +
  theme(axis.ticks.y = element_blank(),
        axis.text.y = element_blank(),
        axis.title.y = element_blank())

相关问题