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

时间:2017-07-21 19:29:05

标签: r ggplot2

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

Clustered Timeline

模拟数据:

                       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

1 个答案:

答案 0 :(得分: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")

enter image description here