Something like this?
sysuse auto, clear
xtile cat_mpg = mpg, nq(4)
foreach var of varlist rep cat {
qui {
count if `var' != .
local total =r(N)
egen count = count(`var') if `var' !=., by(`var')
gen percent = string(round((count/`total')*100,.1)) + "%)"
replace percent = "("+percent
gen count2= count+.5
gen rep1 = `var' - .2
gen rep2 = `var' + .1
}
twoway bar count `var', barw(0.7) || ///
scatter count2 rep1, mlabel(count) mlabpos(0) ///
ms(none) mlabcolor(black) || ///
scatter count2 rep2, mlabel(percent) mlabpos(0) ///
ms(none) legend(off) mlabcolor(black) ///
name(gr_`var',replace)
drop count* percent rep?
}
See also:
http://www.stata.com/support/faqs/data/percentvars.html
Scott
On Tue, Nov 24, 2009 at 9:06 AM, Adam Collins <[email protected]> wrote:
> Hello,
>
> I have a series of categorical variables. For each one, I would like to create a quick bar graph that displays the count (frequency) of each category, but also the percentage.
>
> For example, if it was an "hbar" graph, it might look something like this:
>
> __________
> | 10
> __________|(33.3%)
> _________________
> | 16
> _________________|(53.3%)
> ____
> | 4
> ____|(13.3%)
>
>
> I intend to use a "foreach" loop to iterate through the list of categorical variables, so I am looking for a solution that can be automated for each variable in my list. I don't mind if the solution uses catplot or hbar or something else.
*
* For searches and help try:
* http://www.stata.com/help.cgi?search
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/