Search code examples
stata

Custom ordering of variables in the legend of a bar chart


How do I create a stacked bar chart in Stata (v 15.1) in which the legend displays the variables in the same order as they are stacked in the chart?

The bars are stacked in this order:

variable 4, variable 3, variable 2, variable 1

However, the legend is in this order:

variable 1, variable 2, variable 3, variable 4

I would like the order of the variables in the bars to match the order in the legend.

Current code:

graph bar (asis) supplier customer employee enviro, over(year, lab(angle(90))) stack ///
legend(lab(1 "suppliers") lab(2 "customers") lab(3 "employees") lab(4 "environment")) ///
ti("Articles returned from Factiva search") ///
note("Search term: 'corporate social responsibility' AND '<stakeholder name>'", /// 
size(vsmall)) scheme(plotplainblind)

Solution

  • Please always provide a Minimal, Complete, and Verifiable example with your question.

    Here is a toy example adapted from the relevant Stata manual:

    clear
    
    input var4 var3 var2 var1
    var4 var3 var2 var1
    27.9 21.7 46.1 46.2
    end
    
    graph bar (asis) var4 var3 var2 var1, legend(rows(1)) name(graph1, replace)
    
    graph bar (asis) var4 var3 var2 var1, legend(rows(1) order(4 3 2 1)) name(graph2, replace)
    

    For more information type help legend_options from Stata's command prompt.