Stacked bars

-graph bar- and -graph twoway bar- draw Stata (vertical) bar charts. -graph bar- draws bar charts over a categorical X variable and has more options than -graph twoway bar-, which draws bar charts with numerical X and Y values. Here, we use -graph bar- to draw stack bar graphs (figures 1 and 2).

In figure 1, we show the composition of Philippine exports according to the Leamer’s classification of tradeable goods at different time periods. The command to draw this graph is:

Figure 1

#delimit ;
graph bar (sum) value,
asyvars stack
legend(cols(3) size(vsmall))
ytitle(“Export Value” “(in million US$)”)
ylabel(, angle(0) format(%12.0gc))
#delimit cr

The (stat) option, (sum), adds up the export values for commodities that belong to a group for a specific year, as we have specified in our over() options. The (stat) option, which allows you to specify all stats options used by the command -collapse- (e.g. mean (default), count, max, etc.) is very convenient as it saves you from  constructing another dataset just to draw the graphs.

By typing “asyvars” and “stack”, we are specifying that the variable in the first over() option will be treated as Y-axis variables, and that these y-variables will be presented as stacked bars. Note that, with a long dataset,  the command:

graph bar value, over(leamer) asyvars

will draw the same graph as:

graph bar value_leamer1 value_leamer2 … value_leamer10

with a wide dataset.

The ordering of over() matters. In figure 2, we have interchanged the order of over(leamer) and over(year).

Figure 2

#delimit ;
graph bar (sum) value,
over(leamer, label(angle(90)))
asyvars stack
legend(cols(5) size(small) colfirst)
ytitle(“Export Share, %“)
ylabel(, angle(0) format(%10.0gc))
subtitle(by Leamer’s classification)
#delimit cr

By specifying “percentages” for figure 2, we are specifying that the share of value the total, instead of the absolute values, will be reported.

Also note how the legends in the 2 charts differ. The general option to control the legend for all Stata graphs is the option legend(legend options). In the examples above we have use the following legend options:

cols() //number of columns
size() //size of texts
colfirst //specifies that the order is top to bottom rather than left to right

For more legend options, type “help legend_option”.

3 Responses

  1. hi derya,

    yes, with gregorio impavido’s -mystack-. checkout this link from statalist:


  2. It is really a big help! thanks! I have question: is it possible to add a line graph to this bar with a second y-axis? Thanks!

  3. This is a big help! This is exactly what i am looking for. STATA help did not elaborate much on the options.


Leave a Reply