2

I'd like to plot Kaplan-Meier (survival) curves with pgfplots from output generated in Mathematica.

A typical output table would look something like this:

211 1

253 1

307 1

344 0

365 0

365 1

383 0

383 1

391 0 ...

the first column contains event dates; the second is the censoring data.

Is there a package, or built-in way of plotting the resulting survival curve, including censoring marks?

5

This is possible to do in PGFPlots using a couple of column definition.

Let's assume you have the following data table (taken from the example on the German Wikipedia) in a file called data.txt:

Days Event
10 0
12 1
22 0
29 1
31 1
36 0
38 0
50 0
60 0
61 1
70 1
88 0
99 0
110 0
140 0

You can read the data using

\pgfplotstableread{data.txt}\rawdata

Then you can add a dummy data row to make sure the plot begins at t=0:

\pgfplotstableread{
Days Event
0 1
}\datatable

\pgfplotstablevertcat{\datatable}{\rawdata}

Using this, you can calculate the number of survivors minus the censored cases, and the survival rate using:

\def\initialn{15} % Initial number of cases
\pgfplotstablecreatecol[expr accum={\pgfmathaccuma-1}{\initialn+2}]{n}{\datatable}
\pgfplotstablecreatecol[expr accum={\pgfmathaccuma*(\thisrow{n}-\thisrow{Event})/(\thisrow{n})}{(\initialn+1)/\initialn}]{s}{\datatable}

This can then be plotted like this:

\begin{tikzpicture}
\begin{axis}[xmin=0, ymin=0]
\addplot [no markers, const plot, red] table [y=s] {\datatable};
\addplot [only marks, mark=+] table [y expr={(\thisrow{Event}==0 ? \thisrow{s} : inf )}] {\datatable};
\end{axis}
\end{tikzpicture}


Complete example:

\documentclass[11pt,a4paper]{article}
\usepackage{pgfplots, pgfplotstable, filecontents}

\begin{filecontents*}{data.txt}
Days Event
10 0
12 1
22 0
29 1
31 1
36 0
38 0
50 0
60 0
61 1
70 1
88 0
99 0
110 0
140 0
\end{filecontents*}

\begin{document}
\pgfplotstableread{data.txt}\rawdata

\pgfplotstableread{
Days Event
0 1
}\datatable

\pgfplotstablevertcat{\datatable}{\rawdata}

\def\initialn{15}
\pgfplotstablecreatecol[expr accum={\pgfmathaccuma-1}{\initialn+2}]{n}{\datatable}
\pgfplotstablecreatecol[expr accum={\pgfmathaccuma*(\thisrow{n}-\thisrow{Event})/(\thisrow{n})}{(\initialn+1)/\initialn}]{s}{\datatable}

\pgfplotstabletypeset{\datatable}

\begin{tikzpicture}
\begin{axis}[xmin=0, ymin=0]
\addplot [no markers, const plot, red] table [y=s] {\datatable};
\addplot [only marks, mark=+] table [y expr={(\thisrow{Event}==0 ? \thisrow{s} : inf )}] {\datatable};
\end{axis}
\end{tikzpicture}
\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.