pythonplotlifelinesrisk-analysis

how to change color of censor tick and truncate KM curve if number at risk is < 5 using lifelines library?


Is it possible to change the colour of the censor tag in lifelines? The code-chunk that I used was

kmf.plot_survival_function(
    show_censors=True,
    censor_styles={'ms': 5, 'marker': '|'},
    at_risk_counts=True,
    ci_show=False
)

And how to truncate when the number at risk falls below a certain limit?


Solution

  • The underlying class that is used in lifelines for drawing the markers is matplotlib.lines.Line2D, and censor_styles is passed to that class as kwargs when you call plot_survival_function.

    You can use the property markeredgecolor (or mec) with a color code and it'll change the marker color.

    Here's an example based on the KMF sample code from lifelines's documentation.

    from lifelines import KaplanMeierFitter
    from lifelines.datasets import load_waltons
    waltons = load_waltons()
    
    kmf = KaplanMeierFitter(label="waltons_data")
    kmf.fit(waltons['T'], waltons['E'])
    
    kmf.plot_survival_function(
        show_censors=True,
        censor_styles={'ms': 20, 'marker': '|', 'markeredgecolor': '#ff0000'}, 
        color='#abc3f0',
        at_risk_counts=True,
        ci_show=True
    )
    

    And the resulting image with my red markers:

    sample with red markers