To create a density heat map in Stata you need four commands – spgrid, spkde, grmap, and mylabels. The grmap command is native to Stata.
You can download the three non-native commands from the SSC within Stata using the following commands:
ssc install spgrid
ssc install spkde
ssc install mylabels
To generate this graph in Stata, use the following commands:
sysuse auto, clear
summarize price mpg
clonevar x = mpg
clonevar y = price
replace x = (x-0) / (50-0)
replace y = (y-0) / (20000-0)
mylabels 0(10)50, myscale((@-0) / (50-0)) local(XLAB)
mylabels 0(5000)20000, myscale((@-0) / (20000-0)) local(YLAB)
keep x y
save xy.dta, replace
spgrid, shape(hexagonal) xdim(100) xrange(0 1) yrange(0 1) dots replace cells("2D-GridCells.dta") points("2D-GridPoints.dta")
spkde using "2D-GridPoints.dta", xcoord(x) ycoord(y) bandwidth(fbw) fbw(0.1) dots saving("2D-Kde.dta", replace)
use "2D-Kde.dta", clear
recode lambda (.=0)
grmap lambda using "2D-GridCells.dta", id(spgrid\_id) clnum(20) fcolor(Rainbow) ocolor(none ..) legend(off) point(data("xy.dta") x(x) y(y)) freestyle aspectratio(1) xtitle(" " "Mileage (mpg)") xlab( `XLAB') ytitle(" " "Price ({c S|}US)") ylab(`YLAB', angle(0))