program denscomp
version 10.0
syntax varname(numeric) [if] [in], by(varname) at(varname numeric)
marksample touse
quietly levelsof `by' if `touse', local(K)
foreach k of local K {
    kdensity `varlist' if `by'==`k' & `touse', gen(xvals`k' fx`k') at(`at') nograph
    local yvars "`yvars' fx`k'"
}
graph twoway connected `yvars' `at' ///
, title("`varlist' by `by'") ytitle("Density") xtitle("Log (Income)") ///
  legend(label(1 "Men") label(2 "Women"))
end