Announcement

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

  • Graph Bar Stacked for Subset of Variables

    How can I stack only two variables in the bar graph. I would like to stack var1 and var2 and have var3 and var3 by itself. Here is the data example:

    year var1 var2 var3 var4
    2016 100 10 70 20
    2017 110 15 60 40
    2018 90 20 50 30

  • #2
    Code:
    clear 
    input year    var1    var2    var3    var4
    2016    100    10    70    20
    2017    110    15    60    40
    2018    90    20    50    30
    end 
    
    gen var12 = var1 + var2 
    
    gen year_l = year - 0.2 
    gen year_r = year + 0.2
    
    twoway bar var1 year_l, barw(0.4) || rbar var1 var12 year_l, barw(0.4)|| bar var3 year_r, barw(0.4) ///
    legend(order(1 "var1" 2 "var2" 3 "var3")) xla(2016/2018)

    Comment


    • #3
      Why do the bars start at 40 and not at zero? Is there a way to use bar graph and stack option? I tried it but didn't manage to get it work. Using rbar is quite difficult if I want to use more than three variables that shows you example or rearrange the order of the bars. I was not able to do that.
      Last edited by Trevor Andrew; 17 Apr 2024, 18:20.

      Comment


      • #4
        One thing at a time!

        1. You evidently need the extra option base(0) for your data example. Sorry; I didn't check the code all the way through to looking at the graph really carefully: hereabouts, my dinner was ready...

        So the code is better as

        Code:
        twoway bar var1 year_l, barw(0.4) base(0) || rbar var1 var12 year_l, barw(0.4)|| bar var3 year_r, barw(0.4) ///
        legend(order(1 "var1" 2 "var2" 3 "var3")) xla(2016/2018) yla(0(20)120)
        2. I don't see a way to use graph bar with options asyvars stack off-hand. I agree: I would have used such a solution had I seen one.

        3. You seem to be saying that your real need is more complicated. I believe that, but the principles to apply appear to be just the same unless you can spell out a specific new difficulty.

        Comment


        • #5
          I wanted to add more variables and change the location of the bars. But I managed to get it to work with your suggestions. Thanks Nick!

          Comment

          Working...
          X