Search code examples
stata

Reordering panels by another variable in twoway, by() graphs


Suppose I make the following chart showing the weight of 9 pigs over time:

webuse pig
tw line weight week if inrange(id,1,9), by(id) subtitle(, nospan)

enter image description here

Is it possible to reorder the panels by another variable while retaining the original label? I can imagine defining another variable that is sorted the right way and then labeling it with the right id, but curious if there is a less clunky way of achieving that.


Solution

  • I think you are right: you need a new ordering variable. Positively, you can order on any criterion of choice. Watch out for ties on the variable used to order, which can always broken by referring to the original identifier. Here we sort on final weights, by default smallest first. (For largest first, negate the weight variable.)

    webuse pig, clear 
    keep if id <= 9 
    bysort id (week) : gen last = weight[_N]
    egen newid = group(last id)
    bysort newid : gen toshow = strofreal(id) + " (" + strofreal(last, "%2.1f") + ")"
    * search labmask           for download links 
    labmask newid , values(toshow)
    set scheme s1color 
    line weight week, by(newid, note("")) sort xla(1/9)
    

    Short papers discussing the principles here are already in train for publication in the Stata Journal in 2021.