1
votes

Problem Description

I am trying to make a swimmerplot in R using ggplot. However, I encounter a problem when I would like to have 'empty' space between two stacked bars of the plot: the bars are arranged next to one another.

Code & Sample data

I have the following sample data:

# Sample data
df <- read.table(text="patient start keytreat duration
                 sub-1    0   treat1  3
                 sub-1    8   treat2  2
                 sub-1    13  treat3  1.5
                 sub-2    0   treat1  4.5
                 sub-3    0   treat1  4
                 sub-3    4   treat2  8
                 sub-3    13.5  treat3  2", header=TRUE)

When I use the following code to generate a swimmerplot, I end up with a swimmerplot of 3 subjects. Subject 2 received only 1 treatment (treatment 1), so this displays correctly.

However, subject 1 received 3 treatments: treatment 1 from time point 0 up to time point 3, then nothing from 3 to 8, then treatment 2 from 8 until 10 etc...

The data is plotted in a way, that in patient 1 and 3 all treatments are consecutive instead of with 'empty' intervals in-between.

# Plot: bars
bars <- map(unique(df$patient)
            , ~geom_bar(stat = "identity", position = "stack", width = 0.6,
                        , data = df %>% filter(patient == .x)))



# Create plot
ggplot(data = df, aes(x = patient,
                      y = duration,
                      fill = reorder(keytreat,-start))) + 
  bars +
  guides(fill=guide_legend("ordering")) + 
  coord_flip() 

Question

How do I include empty spaces between two non-consecutive treatments in this swimmerplot?

1

1 Answers

1
votes

I don't think geom_bar is the right geom in this case. It's really meant for showing frequencies or counts and you can't explicitly control their start or end coordinates.

geom_segment is probably what you want:

library(tidyverse)

# Sample data
df <- read.table(text="patient start keytreat duration
                 sub-1    0   treat1  3
                 sub-1    8   treat2  2
                 sub-1    13  treat3  1.5
                 sub-2    0   treat1  4.5
                 sub-3    0   treat1  4
                 sub-3    4   treat2  8
                 sub-3    13.5  treat3  2", header=TRUE)

# Add end of treatment
df_wrangled <- df %>%
  mutate(end = start + duration)

ggplot(df_wrangled) +
  geom_segment(
    aes(x = patient, xend = patient, y = start, yend = end, color = keytreat),
    size = 8
  ) +
  coord_flip()

Created on 2019-03-29 by the reprex package (v0.2.1)