Friday, October 28, 2011

Stata: curve labels for sts graph

I'm plotting KM curves in Stata using

sts graph, by(iGroup)

and here is the plot that I get:
Note that the default curve labels in the legend are of the type "varname=label" for each group. Clearly, this isn't the desired labeling because there is no need for the "varname=" part.  I didn't find much on help on the web regarding how to deal with this (except this post which is cumbersome, to say the least).  There also does not appear to be an option in sts graph or in legend() to change this behavior. Also, it's not the behavior of other plot types (e.g. graph bar age, over(iGroup) labels everything with just the value label).

So here is my solution - it is to define the value labels using global macros:

global iGroup1 "Group -/-"
global iGroup2 "Group -/+"
global iGroup3 "Group +/+"
label def iGroup 1 "$iGroup1" 2 "$iGroup2" 3 "$iGroup3", modify
label val iGroup iGroup
stset DFS, fail(Relapse)
sts graph, by(iGroup) legend(label(1 "$iGroup1") label(2 "$iGroup2") label(3 "$iGroup3"))

And voilà!

Any thoughts?


  1. I have the exact same problem. When I use your code some of my problem is solved, but my only probloem is the DFS command, I can not find out what that is and what I should replace it with in my dataset?

    Lene, Denmark

    1. Lene - this particular post is about plotting Kaplan-Meier survival estimates. "DFS" is the variable name for the time to event (in this case DFS=disease free survival). "Relapse" is a censoring indicator. If your data aren't survival data, you don't need to use the "stset" command.

  2. Thank you, thank you! I was just beating my head against the desk trying all sorts of -legend- options to deal with this. It might be worth posting on statalist, since as you mention the default is contrary to all other plot types.

  3. A big, big thankyou from me too! This works great and saves a lot of time with re-formatting legends on survival curves. Agree it would be worth posting elsewhere as it took me a while to find this gem!!
    Thanks for sharing

  4. Although having said that I can't get it to work great with the gwood far managed to adapt to label the CI legend labels ok but it won't pick up the survival curve legend labels...

  5. You don't really need to establish all of those global macros--you can just use the legend(label()) function to do what you wanted.

    Like so:

    sts graph, haz by(b497) legend(label(2 "Turned 65 Before 1997") label(1 "Turned 65 After 1997"))

    Thanks for the post though! Got me where I needed to go.


Subscribe via email

Enter your email address:

Delivered by FeedBurner


google analytics