Calculating and Graphing Correlation

By Annabella Tyrrell · Published 25 November 2026
analysisgraphicsstata

Heavier cars tend to travel fewer miles per gallon. We can measure the strength of this relationship across the 74 models in Stata’s auto dataset using Pearson’s correlation coefficient, r. The coefficient ranges from −1 to 1, with values closer to either endpoint indicating a stronger linear relationship.

Calculate the Correlation

Calculate the correlation between vehicle weight and fuel economy. Stata stores the coefficient in r(rho), which we can save for the graph:

sysuse auto, clear
(1978 automobile data)

correlate weight mpg
(obs=74)

             |   weight      mpg
-------------+------------------
      weight |   1.0000
         mpg |  -0.8072   1.0000


scalar weight_mpg_r = r(rho)

The correlation is −0.8072, indicating a strong negative association between weight and fuel economy. The coefficient is unitless therefore expressing weight in kilograms instead of pounds would give the same result.

Graph the Relationship

Plot fuel economy against weight and overlay a least-squares line. Use the stored coefficient in the subtitle so the graph reports the value calculated from the data:

local r_label = strtrim(string(weight_mpg_r, "%6.4f"))


twoway ///
     (scatter mpg weight, mcolor(navy%70) msymbol(O)) ///
     (lfit mpg weight, lcolor(maroon) lwidth(medthick)), ///
     xlabel(1500(500)5000, format(%9.0fc)) ///
     ylabel(10(5)45, angle(horizontal)) ///
     xtitle("Vehicle weight (lb)") ///
     ytitle("Fuel economy (mpg)") ///
     title("Vehicle weight and fuel economy") ///
     subtitle("Pearson's r = `r_label'") ///
     legend(order(1 "Car model" 2 "Linear fit") rows(1) position(6))

Fuel economy varies more widely among the lighter models, even though the overall relationship is strongly negative. The comparison is between different cars. Their engines and designs also differ, so the correlation alone cannot tell us how much fuel economy would change if weight were reduced on the same car.

4 views 0 found this useful