Search code examples
stata

Overlay line on scatter plot


In Stata, is there a way to overlay a line when the slope and y-intercept are known, onto a twoway scatter Y X?

For example, if the slope were slope and the y-intercept were yint, and the Y values were in an array called Y and the X values were in an array called X what would the syntax be?

Lets say we want to overlay y=2x+1, where x = [0,1,2,3,4,5] and y = [3,4,5,6,7,8].


Solution

  • You can do this with twoway function:

    twoway function y=2*x+1, range(0 5)
    

    And as with any twoway graph, you can combine it with scatter:

    twoway scatter var1 var2 || function y=2*x+1, range(0 5)
    

    Here's a toy example:

    clear
    set obs 20
    
    generate x = rnormal(3, 2)
    generate y = rnormal(5, 2)
    
    twoway scatter y x  || function y=2*x+1, range(0 5)
    

    enter image description here