graphstata

Clustered stacked bar chart


I finally managed to create a clustered stacked bar in Stata (after a lot of trial and error). Here's the code I used and the output:

clear
 
input time_period scenario s str2 cid 
3 1 4.013453 "fw" 
4 1 4.064307 "fw" 
5 1 4.370211 "fw" 
3 1 19.20553 "he" 
4 1 22.62123 "he" 
5 1 25.16719 "he" 
3 2 6.894791 "fw" 
4 2 6.960844 "fw" 
5 2 9.851804 "fw" 
3 2 14.96675 "he" 
4 2 18.20208 "he" 
5 2 17.93641 "he" 
end
 

gr bar (asis) s, over(cid) over(scenario, label(nolabel) gap(0))
over(time_period) stack ytitle("Total wealth")
graphregion(color(white)) legend(rows(1) cols(2) order(1 "FW" 2 "HE")
ring(1) position(6)) b1title("Period") bar(1, fcolor("0 114 189"))
bar(2, fcolor("217 83 25")) plotregion(lcolor(black))

enter image description here

Now is there any way I can make the bars on the left have a different color than the bars on the right? (ideally slightly more transparent)


Solution

  • You want in effect four different colours.

    clear
    
    input time_period scenario s str2 cid 
    3 1 4.013453 "fw" 
    4 1 4.064307 "fw" 
    5 1 4.370211 "fw" 
    3 1 19.20553 "he" 
    4 1 22.62123 "he" 
    5 1 25.16719 "he" 
    3 2 6.894791 "fw" 
    4 2 6.960844 "fw" 
    5 2 9.851804 "fw" 
    3 2 14.96675 "he" 
    4 2 18.20208 "he" 
    5 2 17.93641 "he" 
    end
    
    
    gr bar (asis) s, over(cid) over(scenario, label(nolabel) gap(0))   ///
    over(time_period) stack ytitle("Total wealth")                     ///
    graphregion(color(white)) legend(rows(1) cols(2) order(1 "FW" 2 "HE") ///
    ring(1) position(6)) b1title("Period") bar(1, fcolor("0 114 189")) /// 
    bar(2, fcolor("217 83 25")) plotregion(lcolor(black)) name(G1, replace)
    
    reshape wide s, i(time_period scenario) j(cid) string 
    gen timeL = time_period - 0.15 
    gen timeR = time_period + 0.15 
    
    gen S = sfw + she 
    
    local lc lc(black)
    
    twoway bar sfw timeL if scenario == 1, barw(0.3) base(0) fcolor("0 114 189%50") `lc' ///
    || rbar sfw S timeL if scenario == 1, barw(0.3) fcolor("217 83 25%50") `lc' ///
    || bar sfw timeR if scenario == 2, barw(0.3) base(0) fcolor("0 114 189") `lc'  ///
    || rbar sfw S timeR if scenario == 2, barw(0.3) fcolor("217 83 25") `lc' /// 
    ytitle(Total wealth) yla(0(10)30) xla(3/5, noticks) xtitle(Period) /// 
    legend(order(- "Scenario 1:" 2 "HE" 1 "FW" - "  Scenario 2:" 4 "HE" 3 "FW" ) pos(6) row(1)) /// 
    name(G2, replace)
    

    enter image description here