Announcement

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

  • overlay two scatterplots plus lfit lines

    I have established that within one variable A, two subsets appear have a different relation with variable X. Now I'm trying to plot this.
    Using 'graph twoway' I manage either 2 scatterplots in one graph or one scatterplot plus linear fit (see code below and graphs attached).

    Want I want to achieve is:
    1) have one graph, with scatterplots for both subsets, and linear fit lines for each
    2) ideally, to have the scatterplots for subsets 1 and 2 just slightly offset (with respect to values of X) so that they do not overlap anymore.


    Code:
    *scatterplots colorcoded bu subset (graph.gph)
    graph twoway (scatter A X if subset==1) (scatter A X if subset==2), xtitle(X) ytitle(A) legend(order(2 "A, subset 1" 1 "A, subset 2"))
    
    *scatterplot one subset with linear fitted values (graph2.gph)
    graph twoway (scatter A X if subset==1) (lfit  A X if subset==1), xtitle(X) ytitle("A, subset 1") legend(order(1 "A, subset 1" 1 "Lin. fit (A, subset 1"))
    Attached Files

  • #2
    Please use .png graphs as attachments. A big disadvantage of .gph attachments is that you can't compare graphs easily. See FAQ #12.

    Consider this:

    Code:
    sysuse auto, clear
    gen rep78_2 = rep78 + cond(foreign, 0.1, -0.1)
    scatter mpg rep78_2 if foreign, ms(Oh) mcolor(red) ///
    || scatter mpg rep78_2 if !foreign, ms(X) mcolor(blue) ///
    || lfit mpg rep78 if foreign, lcolor(red) ///
    || lfit mpg rep78 if !foreign, lcolor(blue) ///
    ytitle("`: var label mpg'") legend(order(1 "Foreign" 2 "Domestic"))
    Click image for larger version

Name:	offsetgph.png
Views:	1
Size:	10.0 KB
ID:	1312867

    Comment


    • #3
      Thanks, that's very helpful. The offset trick in particular is simple but effective. Wouldn't have come up with that myself.

      Comment


      • #4
        For offsetting to work, the variable concerned should take on only a relatively small set of values, e.g. a few integers.

        More at

        SJ-7-1 gr0026 . . . . Stata tip 42: The overlay problem: Offset for clarity
        . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . J. Cui
        Q1/07 SJ 7(1):141--142 (no commands)
        tip for graphing several quantities on a continuous axis

        http://www.stata-journal.com/sjpdf.h...iclenum=gr0026

        Comment

        Working...
        X