Intro

This notebook accompanies the article at http://crosstab.io/articles/survival-plots. Please see the article for text explanations of each section.

Lifelines survival curve with Matplotlib

In [1]:
from lifelines.datasets import load_dd
from lifelines import KaplanMeierFitter
import matplotlib.pyplot as plt
In [2]:
data = load_dd()
data[['ctryname', 'ehead', 'duration', 'observed']].sample(5, random_state=19)
Out[2]:
ctryname ehead duration observed
1022 Mauritania Mustapha Ould Salek 1 1
1565 Switzerland Ruth Dreifuss 1 1
763 Ireland Eamon de Valera 2 1
1722 United States of America Bill Clinton 8 1
1416 Somalia Abdirizak Hussain 3 1
In [3]:
kmf = KaplanMeierFitter()
kmf.fit(durations=data['duration'], event_observed=data['observed'])

kmf.plot_survival_function()
plt.savefig("matplotlib_survival.png", dpi=500, bbox_inches='tight')

Plotly survival curve, with confidence band

In [4]:
import plotly.graph_objs as go
In [5]:
fig = go.Figure()

fig.add_trace(go.Scatter(
    x=kmf.survival_function_.index, y=kmf.survival_function_['KM_estimate'],
    line=dict(shape='hv', width=3, color='rgb(31, 119, 180)'),
))