1

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?

SBista
  • 7,479
  • 1
  • 27
  • 58

1 Answers1

2

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)
David Gohel
  • 9,180
  • 2
  • 16
  • 34
  • Thank you for the amazing package and the answer. The problem with filtering the data before sending it to ggplot is that it messes up my survival analysis. Is there any other way to workaround it, maybe after the plot is generated? – SBista Apr 29 '17 at 14:50
  • @SBista I made a modification to filter after `ggsurvplot()` call. – David Gohel May 02 '17 at 20:27