ggplot2 - 如何创建聚集时间轴?

Dir*_*ble 2 r ggplot2

您如何在R中创建下图?我想显示不同患者的不同治疗时间.

集群时间表

这里的模拟数据:

                       Start Day    Stop Day
Patient 1   Drug 1     1            3
            Drug 2     2            5
            Drug 3     3            8
Patient 2   Drug 1     2            4
            Drug 2     2            5
            Drug 3     1            6
Patient 3   Drug 1     4            7
            Drug 2     3            8
            Drug 3     5            6
Run Code Online (Sandbox Code Playgroud)

Mar*_*dri 5

您的图表可以geom_segment在ggplot2包中生成:

df <- structure(list(Patient = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 
3L, 3L, 3L), .Label = c("Patient1", "Patient2", "Patient3"), class = "factor"), 
    Drug = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("Drug1", 
    "Drug2", "Drug3"), class = "factor"), StartDay = c(1L, 2L, 
    3L, 2L, 2L, 1L, 4L, 3L, 5L), StopDay = c(3L, 5L, 8L, 4L, 
    5L, 6L, 7L, 8L, 6L)), .Names = c("Patient", "Drug", "StartDay", 
"StopDay"), class = "data.frame", row.names = c(NA, -9L))

df$Drug <- factor(df$Drug, levels(df$Drug)[c(3,2,1)])

library(ggplot2)
ggplot(data=df, aes(color=Drug))+
      geom_segment(aes(x=StartDay, xend=StopDay, y=Drug, yend=Drug),lwd=12)+
      facet_grid(Patient~.)+xlab("Days")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述