program denscomp
version 9
syntax varname(numeric) [if] [in], by(varname) at(varname numeric) ///
  [TItle(string asis) YTItle(string asis) XTItle(string asis) * ]
marksample touse

// Store levels of By-Variable
quietly levelsof `by' if `touse', local(K)

// Calculate Kernel-Densities
local i 1
foreach k of local K {
    tempvar fx`k'
    kdensity `varlist' if `by'==`k' & `touse', gen(`fx`k'') at(`at') nodraw
    local yvars "`yvars' `fx`k''"
    local label: label (`by') `k'
    local leglab `" `leglab' lab(`i++' `"`label'"') "'
}

// Graph-Defaults
local title = cond(`"`title'"' == `""', `"`varlist' by `by'"', `"`title'"')
local ytitle = cond(`"`ytitle'"' == `""', `"Density"', `"`ytitle'"')
local xtitle = cond(`"`xtitle'"' == `""', `"`varname'"', `"`xtitle'"')

// Display the Graph
graph twoway connected `yvars' `at' ///
, title(`title') ytitle(`ytitle') xtitle(`xtitle') ///
legend(`leglab') `options'
end