Search code examples
rggplot2tooltipsurvival-analysisggiraph

Error while adding tooltip to ggsurvplot using ggsurvplot


I am trying to add tooltip to a ggsurvplot. I am using ggiraph to display the plot. I have added a minimal example of what I am trying to do below. If I don't add any xlim in ggsurvplot my code seems to work. The following is the code that works:

library(survminer)
library(survival)
library(ggiraph)

fit<- survfit(Surv(time, status) ~ sex, data = lung )
g <- ggsurvplot(fit, data = lung)   
tooltip <- paste0("Time:", g$plot$data$time, "<br/>", "Survival Prob:", g$plot$data$surv)
x <- g$plot+geom_point_interactive(aes(tooltip = tooltip))
ggiraph(print(x), zoom_max = 5)

Now I want to limit the x-axis values so I add the parameter xlim = c(0, 800) to ggsurvplot as shown below:

library(survminer)
library(survival)
library(ggiraph)

fit<- survfit(Surv(time, status) ~ sex, data = lung )
g <- ggsurvplot(fit, data = lung, xlim = c(0,800))  
tooltip <- paste0("Time:", g$plot$data$time, "<br/>", "Survival Prob:", g$plot$data$surv)
x <- g$plot+geom_point_interactive(aes(tooltip = tooltip))
ggiraph(print(x), zoom_max = 5)

This gives me the following error:

Error: length(ids) == length(str) is not TRUE

How can I fix this error?


Solution

  • That's an issue with ggiraph. Adding an xlim is triggering clipping, some points will not be drawn, but the tooltip variable is not clipped; I will try to solve that.

    The workaround is to filter the data before sending them to geom_point_interactive:

    library(survminer)
    library(survival)
    library(ggiraph)
    
    
    fit<- survfit(Surv(time, status) ~ sex, data = lung )
    g <- ggsurvplot(fit, data = lung, xlim = c(0,800))  
    
    data_ <- g$plot$data
    data_ <- base::transform(data_, tooltip = sprintf("Time: %.0f<br/>Survival Prob: %.3f", time, surv) )
    data_ <- data_[data_$time < 800, ]
    
    x <- g$plot + geom_point_interactive(data = data_, aes(time, surv, tooltip = tooltip))
    ggiraph(print(x), zoom_max = 5)