Announcement

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

  • How to sort multiple variables in a bar chart

    Hi all,

    I'm having trouble sorting this bar graph:

    Click image for larger version

Name:	Graph.png
Views:	1
Size:	15.3 KB
ID:	1714962


    for which I've used the following code:

    Code:
    graph hbar V1 V2 V3
    I want to sort the bars in descending order. Unfortunately, I've only found ways to use sort() when it's embedded in the over() command.
    However, since each bar represents the mean of a different variable, I can't use the over() command.

    I'm sure it's a very simply solution that I've just not managed to find yet - any help on this would be greatly appreciated!


    p.s. (I know the graph isn't pretty yet - I'm just interested in the conceptual solution of this problem before I modify the graph)

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input byte(V1 V2 V3)
    2 3 3
    4 3 2
    4 3 4
    3 1 1
    3 4 3
    2 2 1
    2 3 2
    3 3 2
    4 3 2
    4 4 4
    3 3 3
    3 4 3
    1 3 2
    3 3 3
    3 2 2
    1 2 4
    2 3 2
    3 4 3
    3 4 1
    2 1 3
    end
    label values V1 AH_Label
    label values V2 AH_Label
    label values V3 AH_Label
    label def AH_Label 1 "I do not agree", modify
    label def AH_Label 2 "2", modify
    label def AH_Label 3 "3", modify
    label def AH_Label 4 "I absolutely agree", modify
    Last edited by Nicholas Ruhfus; 25 May 2023, 11:04.

  • #2
    This works. It would be interesting to know a better way (other than using frames, which would be fine).

    Code:
    preserve 
    
    collapse V1 V2 V3
    gen id = 1 
    reshape long V, i(id) j(which) string 
    replace which = "V" + which 
    
    graph hbar V, over(which, sort(1) descending) ytitle(Mean)
    
    restore

    Comment


    • #3
      thank you so much, this code works! Much appreciated!

      Comment


      • #4
        Here is a version using frames.

        Code:
        frame put V*, into(WORK)  
        frame WORK { 
            collapse V1 V2 V3
            gen id = 1 
            reshape long V, i(id) j(which) string 
            replace which = "V" + which 
            graph hbar V, over(which, sort(1) descending) ytitle(Mean)
        }

        Comment

        Working...
        X