Search

# Generating and graphing predictions in Stata

In this post, I will show you how to generate and graph predictions in Stata. Below is a worked example:

The dataset I used was automobile datase. The commands I used in a do-file are as below. I have also attached some explanations for each section:

```sysuse auto, clear

// estimate the model
reg price c.mpg##c.weight##c.weight i.foreign

// collect some information about mpg
sum mpg
local m = r(mean)
local sd = r(sd)

// we are going to change the data, so we preserve it first
preserve

// fix the other explanatory variables
// In this case we only look at US ("domestic") cars
replace foreign = 0

// predict the price while fixing mpg at different values
replace mpg = `m'
predict yhatm

replace mpg = `m' - `sd'
predict yhatl

replace mpg = `m' - 2*`sd'
predict yhatll

replace mpg = `m' + `sd'
predict yhath

replace mpg = `m' + 2*`sd'
predict yhathh

// nicer display of large numbers 1,000 instead of 1000
format yhat* %8.0gc

// create graph
sort weight
twoway line yhatll yhatl yhatm yhath yhathh weight, ///
title("predicted price for US cars")         ///
ytitle("predicted price (US {c S|})")        ///
lpattern(solid solid solid solid solid)      ///
lcolor("255 255 204"                         ///
"161 218 180"                         ///
" 65 182 196"                         ///
" 44 127 184"                         ///
" 37  52 148" )                       ///
legend( order( - "mpg"                       ///
1 "mean-2*sd"                 ///
2 "mean-1*sd"                 ///
3 "mean"                      ///
4 "mean+1*sd"                 ///
5 "mean+2*sd" ))

// get our original data back
restore```

For more explanation on Stata graphs, please have a look at the book Speaking Stata Graphics