Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Sort by (total) bar height of stacked bar chart

    Basic question but I'm struggling. Title basically says it all. How do you order a stacked bar chart by the total heights of the bars?

    Basic example:

    Code:
    sysuse auto, clear
    gen category = mod(_n,3)
    replace category = 3 in 3/6
    graph hbar (count), over(foreign) over(category) asyvars stack

  • #2
    Code:
    graph hbar (count), over(foreign) over(category, sort(1)) asyvars stack

    Comment


    • #3
      This sorts by the first category of, in this case, foreign. Not the bar total. (Realize now that my example doesn't demonstrate this well.)

      Comment


      • #4
        Install labmask from the Stata Journal, by Nick Cox and sort the categories by frequency, create groups and label these by their category names.

        Code:
        search labmask
        Code:
        sysuse auto, clear
        gen category = mod(_n,3)
        replace category = 3 in 3/6
        bys category: gen count=_N
        egen total= group(count category)
        labmask total, val(category)
        graph hbar (count), over(foreign) over(total) asyvars stack

        Comment


        • #5
          Thanks again Andrew, appreciate it. This works! Seems odd to me that there isn't a more direct way of doing this using the graph syntax, but this workaround is great.

          Comment


          • #6
            Here's a way to do it a little more directly. The logic is really the same as that of Andrew Musau.


            Code:
            sysuse auto, clear
            gen category = mod(_n,3)
            replace category = 3 in 3/6
            
            myaxis total = category, sort(count)
            graph hbar (count), over(foreign) over(total) asyvars stack
            https://www.statalist.org/forums/for...e-or-graph-use explains about myaxis -- on which also see Stata Journal 21(3) (in press at the time of writing).

            As for why this isn't easier: I think the logic of
            graph hbar is that stacking follows calculations, and not the other way round. Coding could be otherwise, but it isn't.

            Comment

            Working...
            X