Stata Bar Graph with Counts Labelled on the Bars

We have written a small program that will allow you to generate a bar graph of means for one variable against categories in another variable. Each bar category on the X axis is labelled with the number of observations that fit into that category.

To create this graph in Stata, you first need to install or recreate our program. One way of doing this is to download the text file below, and then save it as “barlabels.ado” in your personal ado directory. The other option is to copy the program code into a new do-file in your Stata and run that do file to load the program into Stata.

The program code is also shown below:

capture program drop barlabels
program barlabels
syntax varname, over(varname)

sort `over'
quietly summarize `over'

local r1 = r(min)
local r2 = r(max)

graph bar `varlist', over(`over') blabel(bar, position(base) format(%9.1f) size(large) color(black))

local labelcount = 1

forvalues i = `r1'/`r2' {
	quietly count if `over' == `i'
	local label`i' = "N=`r(N)'"
	gr_edit plotregion1.barlabels[`labelcount'].text = {}
	gr_edit plotregion1.barlabels[`labelcount']._set_orientation vertical
	gr_edit plotregion1.barlabels[`labelcount'].text.Arrpush `"{bf: `label`i''}"'
	local ++ labelcount
}
end

To generate this graph in Stata, once you have the appropriate barlabels command loaded, use the following commands:

sysuse auto, clear
egen cutPrice = cut(price), group(10)
barlabels weight, over(cutPrice)