Error in `levels<-`(`*tmp*`, value = as.character(levels)) : factor level [3] is duplicated

1.5k views Asked by At

I'm trying to plot faceted survival curves with autoplot but the combination of covariates and facetting them duplicates levels within the factors

library(survival)
library(ggfortify)
fit <- survfit( Surv(time, status) ~ inst + sex,
                 data = lung )

autoplot(fit, facets = TRUE)


Error in `levels<-`(`*tmp*`, value = as.character(levels)) : 
  factor level [3] is duplicated

Has anyone successfully plotted faceted survival curves with autoplot? I tried survminer but the plot looks horrific with the covariates taking up most of the plot area.

1

There are 1 answers

0
Allan Cameron On BEST ANSWER

I think you should look again at ggsurvplot, since autoplot.survfit doesn't seem to like having more than one independent factor variable (whether you facet or not).

The ggsurvplot function returns a ggplot object, so you don't need to settle for the default options. You can add scales and styling as you see fit. To take your example, we could do:

library(survival)
library(ggfortify)
library(survminer)

fit <- survfit( Surv(time, status) ~ inst + sex,
                 data = lung )

p <- ggsurvplot(fit, facet.by = "inst", conf.int = TRUE) + 
  theme(strip.background = element_blank(),
        axis.line.x = element_line())

p$facet <- facet_wrap(.~inst, ncol = 3, nrow = 6, scales = "free")

p

enter image description here