Announcement

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

  • Adding custom xlines to scatter plots?

    Hi everyone,

    I am looking to add custom xlines to a scatter plot in Stata. I've created a reproducible example below:

    Code:
    sysuse auto, clear
    
    split make, parse(" ") gen(brand)
    drop brand2 brand3
    rename brand1 brand
    
    collapse (mean) mpg (sum) price (p25) mpg25 = mpg (p75) mpg75 = mpg (first) foreign, by(brand)
    sort brand
    gen obsno = _n
    twoway (scatter mpg obsno [w=price] if foreign == 0, xtitle("Brand") xlabel(, noticks nolabel) ytitle("Avg. MPG") msymbol(Oh) mcolor(midblue)) ///
    (scatter mpg obsno [w=price] if foreign == 1, msymbol(Oh) mcolor(red) legend(order(1 "Domestic" 2 "Foreign")))
    I am looking to add a vertical line through each point of my plot, where the line should stretch from mpg25 to mpg75 for each brand. Any suggestions on how I might go about doing this? I attempted to do this by stacking a bar chart onto the plot:
    Code:
    gen pline = mpg75 - mpg25
    twoway (scatter mpg obsno [w=price] if foreign == 0, xtitle("Brand") xlabel(, noticks nolabel) ytitle("Avg. MPG") msymbol(Oh) mcolor(midblue)) ///
    (scatter mpg obsno [w=price] if foreign == 1, msymbol(Oh) mcolor(red) legend(order(1 "Domestic" 2 "Foreign"))) ///
    bar pline obsno, barwidth(0.05)
    but this was unsuccessful as I could not align the bars with the center of the points.

    Thank you!
    Last edited by Daniel Moore; 12 Aug 2024, 13:06.

  • #2
    I have figured this out, so for future reference I will share the solution here. rcap does the trick.

    Code:
    twoway (scatter mpg obsno [w=price] if foreign == 0, xtitle("Brand") xlabel(, noticks nolabel) ytitle("Avg. MPG") msymbol(Oh) mcolor(midblue)) ///
    (scatter mpg obsno [w=price] if foreign == 1, msymbol(Oh) mcolor(red) legend(order(1 "Domestic" 2 "Foreign"))) ///
    rcap mpg75 mpg25 obsno

    Comment


    • #3
      Good that you solved your problem.

      As a detail note that

      Code:
      split make, parse(" ") gen(brand)
      drop brand2 brand3
      rename brand1 brand
      could be

      Code:
      gen brand = word(make, 1)

      Comment

      Working...
      X