Search code examples
rggplot2annotate

R: swimplot package annotate


I have a swimmerplot builded with the swimplot package in R and want to annotate every bar with the factor/text from another variable of the data.frame which belongs to the respective id/patient.

I cannot share the data, but here's the piece of code I'm currently working on with the very last line being my failure to annotate (Best.response.1 is the name of the respective text-variable). "id" is the patient variable and "daysuntildeath" the time variable.

plot3 <- swimmer_plot(df=data ,id='id',end='daysuntildeath',
                      width=.85, name_fill="Drug.1", id_order="Drug.1") +
    scale_fill_manual(name="Drug.1", values = c("coral1", "lavenderblush4", "maroon4","springgreen3" , "springgreen4", "yellowgreen", "dodgerblue2"))
##################### adding symbols for censoring #############################
### censoring
plot4 <- plot3 + swimmer_points(df_points=
                      data,id='id',time='daysuntildeath',name_shape =
                      'event',size=2.5,fill='white',col='black')
p4_new = plot4 + scale_y_discrete(expand = c(0.15,0)) + labs(y = "Days until death") +
  geom_text(x = "id", y = "daysuntildeath", aes(label = "Best.response.1"), vjust = -0.2, colour = "black")

Edit: It is no option to rename the patient variables/tick marks. The id's must be visible, only adding an annotation would be possible.


Solution

  • To summarise the main points:

    • In the last line, geom_text uses the x and y arguments within the aes() function
    • Variable names are typically not quoted in standard ggplot2

    So the final line of code should read:

    p4_new = plot4 + scale_y_discrete(expand = c(0.15,0)) + 
       labs(y = "Days until death") +
       geom_text(aes(x = id, y = daysuntildeath, label = Best.response.1), 
                 vjust = -0.2, colour = "black")