Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Connect points pairwise two way scatter

    Hi all,

    I am making a twoway scatterplot graph on Stata (see code below) on which I include the fitted curve from a regression.
    My dataset is a panel (N=198), T= 2. I would like to connect the points by group in the graph. Basically, I would like to have a line that connects village V1 in time T1 to village V1 in time T2, village V2 in time T1 to village V2 in time T2 etc

    Here is my code, if anyone have suggestions so I can keep draw a line between the two periods for each village and include the fitted curve from the model in the graph.

    Code:
    reg Y X1 X2 c.X1#c.X2 i.ID i.year, r
    predict Live_predict if e(sample)==1, xb
    gen X1_effect = _b[X1]*X1
    replace Live_predict = Live_predict - lndist_effect
    egen Live_mean = mean(Live_predict)
    
    gen model_Live = Live_mean + lndist_effect
    drop X1_effect
    
    * Scatter plot
    
    twoway (scatter Y X1, mlabel()) (connected model_Live X1, connect(ascending) sort(X1) msymbol(i)), ytitle("Y title") xtitle("X title") graphregion(color(white)) leg(off) 
    graph export graph2.png, replace
    Thanks!

  • #2
    First you need to -xtset- your data. Then the -xtline- command will give you these village-by-village connected plots. If you want the data points themselves marked, add the -recast(connect)- option. If you want all these plots on a single graph, use the -overlay- option. (This is only advisable if the number of panels is small; otherwise you will get an unreadable spaghetti-mess.) And if you want to superimpose the regression line, use the -addplot()- option.

    I suggest reading -help xtline- to see other options available to you before proceeding.

    Comment


    • #3
      Consider using arrows here. Otherwise how do you know which points are time 1 and time 2? Toy demo:

      Code:
      clear 
      set obs 8
      set seed 2803
      gen id = ceil(_n/2) 
      gen y = runiformint(1, 10)
      gen x = runiformint(1, 10)
      gen t = cond(mod(_n,2), 1, 2) 
      list 
      reshape wide y x, i(id) j(t) 
      twoway pcarrow y1 x1 y2 x2
      See also https://www.stata-journal.com/sjpdf....iclenum=gr0015

      Comment

      Working...
      X