tags: ggplot2::geom_linerange ggplot2::sec.axis r
library(tidyverse)

sample.data <- data.frame(AESEQ=c(4:1)
                          ,AETERM=c("Tearing", "Grittiness", "eyelid itchiness","Eyelid margin  crusting")
                          ,AESTDTC=c("2022-02-06","2022-02-06","2022-02-06","2022-01-16")
                          ,AESTDY=c(25, 25, 25, 4)
                          ,AEENDTC=c("2022-02-12","2022-03-12","2022-02-12","2022-01-22")
                          ,AEENDY=c(31,59,31,10)
                          ,SUBJID=rep("023-302", 4)
)

SUBJID <- unique(sample.data$SUBJID)

sample.data <- sample.data |> 
  mutate(AESTDTC = as.Date(AESTDTC), 
         AEENDTC = as.Date(AEENDTC),
         AETERM = factor(AETERM, levels=c("Eyelid margin  crusting", 
                                          "eyelid itchiness",
                                          "Tearing",
                                          "Grittiness")))

sample.data |> 
  ggplot(aes(xmin = AESTDTC, xmax=AEENDTC, y=SUBJID)) +
  geom_linerange(aes(color = AETERM), linewidth=5, position = position_dodge(width = .5)) +
  scale_x_date(name = "Start and end dates", 
               breaks = unique(c(sample.data$AESTDTC, sample.data$AEENDTC)),
               sec.axis = dup_axis(
               labels = unique(c(sample.data$AESTDY, sample.data$AEENDY)),
               name = "Study day")
               ) +
  labs(title = paste0("Adverse events of subject ", SUBJID), 
       y = NULL) +
  theme_minimal() +
  theme(axis.text.x.top = element_text(color="red"),
        axis.text.x.bottom = element_text(angle = -25),
        legend.position = "top")

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Created on 2023-06-02 with reprex v2.0.2