R语言两组Kaplan-Meier生存曲线异常,未显示分组曲线求助
Hi there! Let's work through why your KM curves aren't showing up as two distinct lines for your sex groups. Here are the most common issues and fixes to try out:
Check if
sexis recognized as a categorical variable
Ifsexis stored as a numeric/integer column instead of a factor,survfitmight not treat it as a grouping variable. First, confirm its data type with:str(consult3$sex)If it’s not a factor, convert it explicitly (you can adjust labels to match your study’s definitions):
consult3$sex <- factor(consult3$sex, levels = c(1, 2), labels = c("Sex Group 1", "Sex Group 2")) # Re-run the survival fit after conversion test3 <- survfit(Surv(wave, con3) ~ sex, data = consult3)Verify both sex groups have valid event/censorship data
It’s possible one group has no events (allcon3 = 0) or all subjects experienced the event (allcon3 = 1), which could make the curve overlap or fail to render separately. Check the distribution with a cross-tab:table(consult3$sex, consult3$con3)Make sure each group has a mix of events and censored observations.
Confirm your
survfitoutput includes two groups
Before plotting, check if the survival model actually generated results for both sex groups by running:summary(test3)Look for sections labeled "Stratum" – you should see separate entries for
sex=1andsex=2. If only one stratum exists, double-check thatconsult3$sexhas two distinct values with:unique(consult3$sex)Fix color mapping in
ggsurvplot
Your currentcolor = "#2E9FDF"sets a single color for all curves, so even if two lines exist, they’ll look identical. Instead, map color to the strata to get distinct colors:ggsurvplot(test3, color = "strata", # Automatically uses different colors per group risk.table = TRUE, risk.table.y.text.col = TRUE) # Or specify custom colors for each group: ggsurvplot(test3, color = c("#2E9FDF", "#E7B800"), # One color per sex group risk.table = TRUE, risk.table.y.text.col = TRUE)
Try these steps one by one – chances are one of them will get your two curves displaying properly!
内容的提问来源于stack exchange,提问作者Ellen Heidinger

