Creating a bar graph for categorical variables in Stata

We are familiar with bar graph, it is commonly used for data analysis. Instead of using bar graph for numerous variables, we can also use it for categorical variables. I have created a worked example using the auto.dta dataset:

There are many ways to create a bar graph for categorical variables. I used the below commands in a do file to create the above:

sysuse auto, clear
//creating some data
gen mpg1=mpg<30
recode mpg (1/25=1) (26/30=2) (31/50=3), gen(mpg2)
save graph, replace
list

capture erase graph1.dta
local z=1

foreach i of varlist for mpg1 mpg2 {
	use graph, clear
	keep `i'
	contract `i'
	egen total=total(_freq)
	replace _freq=_freq/total
	generate type=`z'
	capture append using graph1
	save graph1, replace
	local ++z
}

drop mp* for
bysort type : gen t1=_n

label define graph 1 cat1 2 cat2 3 cat3
label value type graph

graph bar (mean) _freq , over(t1,sort(_freq) ) over(type, ) showyvars ///
asyvar legend(off) nofill ytitle("Proportion") scheme(s2color)

You can always use Stata menu to create the graph.


You may find more useful information in the book A Visual Guide to Stata Graphics

67 views

© 2020 by Survey Design and Analysis Services. 

  • LinkedIn
  • Facebook
  • Twitter
  • YouTube