Announcement

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

  • Twoway scatter with yline () of the average of each variable

    I would like to draw a scatter plot for a variable list with yline () of Average of each variable. However, I wrote this loop but unfortunately, as I did it uses each of the average values of the other variables as well.

    Average of variables av_rule_law av_gov_effec av_gov_exp_health_gdp av_infant_mortality : -0.6452087 -0.5824026 5.376345 66.99238
    Code:
    foreach var of varlist av_rule_law av_gov_effec av_gov_exp_health_gdp av_infant_mortality {
    foreach i in -0.6452087 -0.5824026 5.376345 66.99238 {
    twoway scatter  `var' av_cgdp,  mlabel(code) xline(0, lpattern(dash)) yline(`i', lpattern(dash)) lcolor(. green) mlabgap(5) scheme(vg_brite) mlabposition(12) mlabsize(small) mfcolor(blue) mlcolor(black) mlwidth(medthick) msize(small) ///
    note("Source: simulation", size(medsmall))
    
    graph export "C:\Users\Perron\Downloads\Clairant\average_`var'_`i'.png", as(png) width(1200) replace 
    
    }
    }
    Please, help me to correct specify the mean of each variable as yline (value).

    Thanks,

    Best.

  • #2
    This is, or should be, just one loop over variables -- and at the same time over their means -- which is key to understanding good coding here. You could go

    Code:
    local means -0.6452087 -0.5824026 5.376345 66.99238
    
    foreach var of varlist av_rule_law av_gov_effec av_gov_exp_health_gdp av_infant_mortality {
       gettoken mean means : means
       twoway scatter `var' av_cgdp, mlabel(code) xline(0, lpattern(dash)) yline(`mean', lpattern(dash)) lcolor(. green) mlabgap(5) scheme(vg_brite) mlabposition(12) mlabsize(small) mfcolor(blue) mlcolor(black) mlwidth(medthick) msize(small) ///
       note("Source: simulation", size(medsmall))
       graph export "C:\Users\Perron\Downloads\Clairant\average_`v ar'. png", as(png) width(1200) replace
    }
    where you put the means in a stack and each time around the loop you take off the top value from the stack.

    I wouldn't do that, however.

    I would calculate the means within the loop, not in advance.


    Code:
    foreach var of varlist av_rule_law av_gov_effec av_gov_exp_health_gdp av_infant_mortality {
        su `var', meanonly
        scatter `var' av_cgdp, mlabel(code) xline(0, lpattern(dash)) yline(`r(mean)', lpattern(dash)) lcolor(. green) mlabgap(5) scheme(vg_brite) mlabposition(12) mlabsize(small) mfcolor(blue) mlcolor(black) mlwidth(medthick) msize(small) ///
        note("Source: simulation", size(medsmall))
        graph export "C:\Users\Perron\Downloads\Clairant\average_`v ar'. png", as(png) width(1200) replace
    }
    Last edited by Nick Cox; 21 Jun 2018, 05:46.

    Comment


    • #3
      Dear Nick,

      Many thanks, very useful !

      Indeed, the two codes work well.

      Best.

      Comment

      Working...
      X