stata

Stata: Sort legend to match sorting in bar graph


I want to plot the variable "change" across "sector" in Stata as a bar chart, using

graph bar change, over(sector, sort(1)) asyvars

The bars are plotted in ascending order of "change", as I want it. However, the legend is instead ordered according to sector (which is a numerical id, and the sector variable has value labels, so the legend shows the text in ascending order of sector id, not in ascending order of change).

Thus, the order of change and the legend do not match.

Is there a way to automatically --- that is, without manually recoding labels or order --- get the legend to sort in the same way as the bars do?

I tried replacing the sector variable with another variable that is in the right order:

sort change 
gen increasingorder=_n
graph bar change, over(increasingorder) asyvars

And while the orders of bars and legend now match, I do not have the value labels of "sector" any more, and there is no easy way to get them over (as "sector" contains a sector id whereas "increasingorder" contains the rank, so the mapping is different).


Solution

  • Let's discuss this in terms of a dataset every Stata user can call up.

    sysuse auto, clear
    graph bar mpg, over(rep78, sort(1)) asyvars
    myaxis newx=rep78, sort(mean mpg)
    graph bar mpg, over(newx, sort(1)) asyvars
    

    The myaxis command that does what you want is written up in this paper, which discusses the key principles in detail. As a community-contributed command it must be installed before you can use it.