1

I am using plotly to make my survival curves interactive. All is working well except the legend is displaying the name of each strata in the following fashion (item_name,1).

I want to get rid of the brackets and the ",1". Normally when I plot the figures in ggplot it shows just: item_name

My code is:

km_curve <- ggsurvplot(fit, 
                   data = dataset, 
                   censor = FALSE,
                   conf.int = TRUE, 
                   risk.table = TRUE,
                   xlab = "Time since Hospital Discharge (years)",  
                   ylab = "Proportion of patients alive", 
                   palette = c("red","orange","yellow","green","blue","brown","pink","black"),
                   legend.title = "Diagnosis",
                   legend.labs = c("Cardiac (Non-surgical)","Cardiac (Surgical)","Gastrointestinal","Neurological","Other","Respiratory","Sepsis","Trauma"))

curve <- km_curve$plot + scale_y_continuous(breaks = seq(0, 1, .25), labels = scales::percent) + 
scale_x_continuous( breaks = seq(0,10,1), expand = c(0, 0))
p <- curve + theme(legend.title = element_text(size = 8), legend.text = element_text(size = 
8),legend.position = "bottom") + coord_cartesian(xlim = c(0,10))
g <- ggplotly(p)
g

Does anyone know how to manually tell plotly what you want the legend text to say?

  • 1
    Please provide dummy data using the function `dput` and the result of KM survival curve plot for the above code. I guess groups in your dataset defined as the fashion (item_name,1)? try renaming them and re-plotting. – Huy Nguyen Aug 08 '20 at 11:52
  • The variables are just named like "male" or "female" for example. No numbers there. I unfortunately can't save the data as it is highly sensitive and I'm not comfortable enough with dummy data. Just wasn't sure if someone knew a way to manually alter legends in plotly – Zakary Doherty Aug 08 '20 at 13:21

1 Answers1

1

The issue is the same as in Strange formatting of legend in ggplotly in R

A similar solution should apply in your case:

Add this to your code after p <- curve + theme(...) should fix it:


p <- ggplotly(p)
for (i in 1:length(p$x$data)){
  if (!is.null(p$x$data[[i]]$name)){
    p$x$data[[i]]$name =  gsub("\\(","",strsplit(p$x$data[[i]]$name,",")[[1]][1])
  }
}
p
user12728748
  • 8,106
  • 2
  • 9
  • 14