Calculating and Graphing the Mean

By Annabella Tyrrell · Published 24 November 2026
graphicsstata

We can use four cars from Stata’s built-in auto dataset to calculate their mean price and show it on a bar chart.

Load the Car Prices

Load the auto dataset and keep the first four observations:

sysuse auto, clear

keep in 1/4

Then, list the four models and their prices:

list make price, noobs

+-----------------------+

make            price

AMC Concord     4,099

AMC Pacer       4,749

AMC Spirit      3,799

Buick Century   4,816

+-----------------------+

Find the Mean

Use summarize to calculate the mean of price:

summarize price

Variable |        Obs        Mean    Std. dev.       Min        Max

-------------+---------------------------------------------------------
price |          4     4365.75     497.315       3799       4816

The four cars have an average price of $4,365.75.

Check the Calculation

After summarize, Stata stores the total price in r(sum) and the number of cars in r(N). Use display to check the calculation:

display "Total price = $" %9.0fc r(sum)
Total price = $   17,463

display "Number of cars = " r(N)
Number of cars = 4

display "Mean price = $" %9.2fc (r(sum) / r(N))
Mean price = $ 4,365.75

The four prices add up to $17,463. Dividing by 4 gives $4,365.75.

Graph the Prices and Mark the Mean

Draw one bar per car and add a dashed line at the mean price. The meanonly option calculates the mean without printing another summary table. We save the result in a local macro called mean_price so that yline() can place the line at the calculated value:

quietly summarize price, meanonly

local mean_price = r(mean)

local mean_label : display %12.2fc `mean_price'

local mean_label = strtrim("`mean_label'")

graph bar (asis) price, over(make, sort(1)) ///
     blabel(bar, format(%9.0fc)) ///
     yline(mean_price', lcolor(maroon) lpattern(dash)) ///
     ylabel(0(1000)5000 mean_price' "`mean_label'", ///
         format(%9.0fc) angle(horizontal)) ///
     ytitle("Price (US dollars)") ///
     title("Prices of four cars") ///
     note("Dashed line marks the mean price")

The AMC Spirit and AMC Concord fall below the $4,365.75 mean, while the AMC Pacer and Buick Century sit above it.

6 views 0 found this useful