Home > front end >  Swimmer plot to follow pacients treatments using dates
Swimmer plot to follow pacients treatments using dates

Time:04-12

Been working on a project where I have a similar dataset as the one bellow, and for longitudinal analyses, I really wanted to do a swimmer plot to track pacients' medication consumption.

I can only find swimmer plots with numeric type values on the x-axis, nothing regarding actual dates.

swim_table = data.frame(id = c(1,1,1,2,2,2,3,3,3),
                        med = c("A", "B", "A", "C", "D", "E", "C", "E", "B"),
                        startDate = c(seq.Date(from = as.Date("2000/01/01"), to = as.Date("2000/03/02"), by = "1 month"),
                                      seq.Date(from = as.Date("2001/01/01"), to = as.Date("2001/03/01"), by = "1 month"),
                                      seq.Date(from = as.Date("2002/01/01"), to = as.Date("2002/03/01"), by = "1 month")),
                        endDate = c(seq.Date(from = as.Date("2001/01/01"), to = as.Date("2001/03/02"), by = "1 month"),
                                      seq.Date(from = as.Date("2002/01/01"), to = as.Date("2002/03/01"), by = "1 month"),
                                      seq.Date(from = as.Date("2003/01/01"), to = as.Date("2003/03/01"), by = "1 month")))

swimmer_plot(df=swimmer_graph_data,id='id',name_fill='med',col=1)  
  theme_bw()

swimmer_plot(df=swim_table ,id='id',name_fill="med",col=1,
             start = 'startDate', end = 'endDate',
             id_order = c('1', '2', '3'))  theme_bw()

I've tried to solve the error by doing (it has worked in the past)

swim_table$startDate = format(as.Date(swim_table$startDate, format="Y/%m/%d"),"%d/%m/%Y")

It still doesn't plot, and by doing

swim_table$endDate = format(as.Date(swim_table$endDate, format="Y/%m/%d"),"%d/%m/%Y")

I get an even more confusing error. Can anyone please take a look at this?

CodePudding user response:

Using dates does seem to break swimmer_plot. However, there is a way round it. Convert your dates to numbers using as.numeric, draw the plot, then change the axis labels from numbers back to dates.

library(ggplot2)
library(swimplot)

swim_table$startDate <- as.numeric(swim_table$startDate)
swim_table$endDate   <- as.numeric(swim_table$endDate)

swimmer_plot(df=swim_table ,id='id',name_fill="med",col=1,
             start = 'startDate', end = 'endDate',
             id_order = c('1', '2', '3'))   
  scale_y_continuous(labels = function(x) as.Date(as.numeric(x), origin = "1970-01-01"))  
  coord_flip(ylim = c(min(swim_table$startDate), max(swim_table$endDate)))  
  theme_bw()

Created on 2022-04-04 by the reprex package (v2.0.1)

  • Related