Caltech Home > Michael Ewens Homepage > Public Code & Data > Plot multiple kernel densities on one plot in Stata

# Plot multiple kernel densities on one plot in Stata

If you want to compare kernel density estimates across years for a particular variable, putting each estimate on one graph will make it easy. The process is fairly straightforward in Stata (and even easier in Matlab…). First, we start with the simple ‘kdensity‘ command

kdensity income if year == 1990 
Next, we append this command with the ‘addplot‘ function:

kdensity income if year == 1990, addplot(kdensity income if year == 1991) 
and we can add even more with the ‘||’ syntax:

kdensity income if year == 1990, addplot(kdensity income if year == 1991 || kdensity income if year == 1992)

If we could use the ‘by’ option, this process would be much cleaner. Finally, we add a legend:

kdensity income if year == 1990, addplot(kdensity income if year == 1991 || kdensity income if year == 1992) legend(ring(0) pos(2) label(1 "1990") label(2 "1991") label(3 "1992"))