Search code examples
graphbar-chartstatatwo-way

Is there a command for moving bars in a twoway bar plot from the back to the front?


Using a twoway bar in Stata, I want to represent the values of two variables for each year. Anyways, if the bar variable shown in the front for a given year has a value greater than the one in the back, it is not possible to see the other variable's value in the graph, as it is covered.

As I don't want to use transparency options, is there a way to tell Stata something like "for each year, the lowest value should be shown as the bar in front"?

I cannot share my data but I can share the command I was using:

twoway bar Apples year, col(cranberry) lc(black) || ///
bar Melons year, col(forest_green) lc(black) ||,  ///
 legend(label(1 "Schools") label(2 "Churches"))   ///
ytitle("Apples/Melons count")

Solution

  • If you can't share your data, that's fine, but then the obligation is to invent data or use other data available in Stata.

    What you ask can be done, although as running this example will show, the result can still be puzzling if values of your two (or more) variables are ever equal or close.

    webuse grunfeld, clear
    separate invest, by(company) veryshortlabel 
    local opts barw(0.8) fcolor(none)
    
    twoway bar invest1 year if invest1 >= invest2, lcolor(red) `opts' ///
    || bar invest2 year if invest2 >= invest1, lcolor(blue) `opts'     ///
    || bar invest1 year if invest1 < invest2, lcolor(red) `opts'      ///
    || bar invest2 year if invest2 < invest1, lcolor(blue) `opts' legend(order(1 2)) ///
    ytitle(Investment)
    

    There are other choices here:

    1. Transparency would widely be regarded as the solution of choice.

    2. Offset bars relative to each other: see here

    3. Line charts!