Announcement

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

  • Add coefficent and R2 to twoway scatter lfit plot - within graph *

    Dear All

    I am using twoway scatter lfit to visualize the association between two measures, as in the example below.

    Code:
                clear all
                sysuse auto.dta
                global v  price mpg
                twoway     (scatter $v) (lfit $v)  , legend(off)  aspectratio(1)
    I would like to add a box within the figure, e.g. in the example below at position 1, which contains the correlation (or standardized beta coefficient) and the R2 of the unconditional association.

    Any pointers on how to accomplish this would be greatly appreciated!
    Last edited by Johannes Muller; 10 Sep 2023, 05:19.

  • #2
    Code:
    ssc desc aaplot

    Comment


    • #3
      Dear Nick,

      That's awesome, many thanks!

      Is there any way to get the stats "inside" the graph? For example, similar to the positioning of the legend in the marginsplot below?

      Code:
                  clear all
                  sysuse auto.dta
                  global v  price mpg
                  
                  twoway     (scatter $v) (lfit $v)  , legend(off)  aspectratio(1)
                   
                  reg rep78 c.price##c.mpg
                      margins, noatlegend at(price ==(4000 1000 15000) mpg=(12 20 30 40)) post  
                      marginsplot, xdimension(price) recast(line)  noci  legend(rows(4) ring(0) pos(10))
      ​​​​​

      Comment


      • #4
        Ps. I would also be keen to focus solely on the coefficient of interest, e.g. mpg above, without adding the information on the constant.

        Ideally, I'd only show the correlation / standardized beta of mpg, along with R2, within the graph, while excluding the other information (and also labels).

        That is, add a small box which reads
        Corr = X
        R2 = X

        Comment


        • #5
          Hi Johannes. If you estimate the correlation corresponding to your scatterplot, Pearson r will be stored as r(rho).

          Code:
          . clear all
          
          . sysuse auto
          (1978 automobile data)
          
          . local v  price mpg
          
          . correlate `v'
          (obs=74)
          
                       |    price      mpg
          -------------+------------------
                 price |   1.0000
                   mpg |  -0.4686   1.0000
          
          
          . return list
          
          scalars:
                            r(N) =  74
                          r(rho) =  -.4685966881951871
          
          matrices:
                            r(C) :  2 x 2
          
          . local r = r(rho)
          
          . local rsq = r(rho)^2
          
          .
          . display "r = " `r'
          r = -.46859669
          
          . display "r^2 = " `rsq'
          r^2 = .21958286
          And see examples in the documentation on how to add text to graphs.

          HTH.

          PS- I changed your global macro to a local macro. You can search the archives of this forum for more info on why many knowledgeable Stata users rail against (over)use of global macros. ;-)
          --
          Bruce Weaver
          Email: [email protected]
          Version: Stata/MP 18.5 (Windows)

          Comment


          • #6
            The major point is that you can and should write custom code for your own specific choices. Here is some token code. The syntax is either a subset of that of aaplot or similar in spirit. The main challenge is that it's all very well to say you want text within the graph, but you presumably do not want it occluding the data. Consequently I make the text an argument to note() but allow it to be moved.

            Code:
            program jmplot
                version 11 
                syntax varlist(numeric min=2 max=2) [if] [in] [,   ///
                corrformat(str) rsqformat(str) ///
                lopts(str) noteopts(str asis) ///
                backdrop(str) addplot(str asis) by(str) * ]
            
                if "`by'" != "" { 
                    di as err "by() option not supported"
                    exit 191
                }
            
                quietly { 
                    marksample touse 
                    count if `touse' 
                    if r(N) == 0 error 2000 
                    if r(N) == 1 error 2001 
            
                    tokenize `varlist' 
                    args y x
            
                    if "`corrformat'" == "" local corrformat %4.3f  
                    if "`rsqformat'" == "" local rsqformat %4.3f
            
                    correlate `y' `x' if `touse' 
                    local text "corr `: di `corrformat' r(rho)';"
                    local text "`text' {it:R}{sup:2} `: di `rsqformat' r(rho)^2'"
                }
            
                local ydesc : var label `y' 
                if `"`ydesc'"' == "" local ydesc "`y'"
                local legend legend(off)  
            
                graph twoway            ///
                (`backdrop')                    /// 
                (lfit `y' `x' if `touse',    ///
                sort                ///
                note(`"`text'"', `noteopts')       ///
                lc(gs12)                    /// 
                `lopts'                 ///
                )                ///
                (scatter `y' `x' if `touse',    ///
                ms(oh) pstyle(p1)           ///
                ytitle(`"`ydesc'"')     ///
                `legend' `options'    ///
                )                ///
                || `addplot'               
            end
            Some examples can be seen by running

            Code:
            sysuse auto, clear
            
            jmplot mpg weight
            
            jmplot mpg weight, noteopts(ring(0) pos(1))
            
            jmplot mpg weight, noteopts(ring(0) pos(1)) aspect(1)
            
            jmplot mpg weight, noteopts(ring(0) pos(1) size(medlarge)) aspect(1)
            
            jmplot mpg weight, noteopts(ring(0) pos(1) size(medium)) aspect(1)

            Comment


            • #7
              Dear Bruce and Nick,

              Many thanks for these incredibly helpful pointers - based on your input, things worked out perfectly.

              Thank you!

              Comment

              Working...
              X