Announcement

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

  • Connecting the means in a dot plot

    I am asked to create a dot plot with two means on each line - one for group A and the other for group B. My collaborators want there to be a line connecting just the 2 means, but not extending below or above them. I can easily get a dotted line from 0 to maximum, but I don't see how to get it just from A to B. Here is what I have so far:

    Code:
    graph dot (mean) *_want, ///
        over(role,  relabel(1 "Mental Health*" 2 "Heat Illness*" 3 "Vector-borne Illness*" 4 "Air-quality*" ///
            5 "Pollen*" 6 "Storm/flood Trauma*" 7 "Storm/flood Illness*" 8 "Water-borne Illness*" 9 "Food-borne Illness*")) ///
        groupyvars ///
        ytitle("Percentage reporting resources would be moderately or very helpful", size(small)) ///
        legend(pos(4) ring(0) size(small)) ///
        subtitle("*P<0.05 for Physician vs. NP/PA", pos(7) span size(small)) ///
        name(want_db, replace)
    Click image for larger version

Name:	want_db.tif
Views:	1
Size:	31.6 KB
ID:	1783653



    Any suggestions? Thanks

  • #2
    interesting question

    Comment


    • #3
      Try -coefplot- from SSC for some flexibility:

      Code:
      *  to get going we generate simulated data somewhat matching your variables and structure
      clear
      set seed 12345
      set obs 200
      
      g  role = cond(_n <= 100, 1, 2)
      lab define role_lbl 1 "Physician" 2 "NP/PA"
      lab values role role_lbl
      
      * Generate percentage indicators (0 or 100) with realistic group differences
      gen mental_want = (runiform() < cond(role == 1, 0.78, 0.65)) * 100
      gen heat_want   = (runiform() < cond(role == 1, 0.64, 0.52)) * 100
      gen vector_want = (runiform() < cond(role == 1, 0.58, 0.45)) * 100
      gen air_want    = (runiform() < cond(role == 1, 0.71, 0.59)) * 100
      gen pollen_want = (runiform() < cond(role == 1, 0.49, 0.61)) * 100
      gen trauma_want = (runiform() < cond(role == 1, 0.68, 0.54)) * 100
      gen storm_want  = (runiform() < cond(role == 1, 0.55, 0.43)) * 100
      gen water_want  = (runiform() < cond(role == 1, 0.60, 0.48)) * 100
      g food_want   = (runiform() < cond(role == 1, 0.52, 0.40)) * 100
      
      * Install coefplot 
      capture which coefplot
      if _rc ssc install coefplot, replace
      
      *. Verify 'role' exists 
      confirm variable role
      levelsof role, local(levels)
      local g1 : word 1 of `levels'
      local g2 : word 2 of `levels'
      
      cap confirm string variable role
      if !_rc {
          local cond1 `"role == "`g1'""'
          local cond2 `"role == "`g2'""'
      }
      else {
          local cond1 `"role == `g1'"'
          local cond2 `"role == `g2'"'
      }
      
      
      **likely can start here:  
      * Calculate group means and store in matrices
      quietly {
          mean *_want if `cond1'
          matrix b1 = e(b)
          mean *_want if `cond2'
          matrix b2 = e(b)
      }
      
      * 4. Stack the two mean vectors to define the connecting segment bounds
      matrix ci_range = b1 \ b2
      
      **Plot the connected dot plot sorted from highest to lowest Group 1 mean
      coefplot ///
          (matrix(b1), ci(ci_range) ciopts(lcolor(gs8) lwidth(medthick)) ///
              label("Physician") mcolor(navy) msymbol(O) msize(medium)) ///
          (matrix(b2), noci ///
              label("NP/PA") mcolor(maroon) msymbol(O) msize(medium)), ///
          nooffsets ///
          sort(1, descending) ///
          coeflabels( ///
              mental_want = "Mental Health*" ///
              heat_want   = "Heat Illness*" ///
              vector_want = "Vector-borne Illness*" ///
              air_want    = "Air-quality*" ///
              pollen_want = "Pollen*" ///
              trauma_want = "Storm/flood Trauma*" ///
              storm_want  = "Storm/flood Illness*" ///
              water_want  = "Water-borne Illness*" ///
              food_want   = "Food-borne Illness*" ///
          ) ///
          xtitle("Percentage reporting resources would be moderately or very helpful", size(small)) ///
          legend(order(2 "Physician" 3 "NP/PA") pos(4) ring(0) cols(1) size(small)) ///
          subtitle("*P<0.05 for Physician vs. NP/PA", pos(7) span size(small)) ///
          name(want_db, replace)
      Last edited by eric_a_booth; 17 Nov 2026, 21:43.
      Eric A. Booth | Sr. Researcher | Texas2036.org | www.github.com/EricABooth

      Comment


      • #4
        Here's a solution using official commands only.

        Code:
        webuse nlswork, clear 
        
        separate wks_work, by(collgrad) veryshortlabel 
        egen mean0 = mean(wks_work0), by(race)
        egen mean1 = mean(wks_work1), by(race)
        tabdisp race, c(mean?)
        
        twoway rspike mean? race, ///
        horizontal lc(black) ysc(r(0.8 3.2) reverse) yla(1/3, noticks valuelabel) ///
        || scatter race mean0, msize(large) mc(stc1) ///
        || scatter race mean1, msize(large) mc(stc2) xsc(alt) xtitle(Weeks of work) ///
        legend(order(2 "Not graduate" 3 "Graduate") pos(6) row(1))

        Click image for larger version

Name:	connected_dot.png
Views:	1
Size:	34.5 KB
ID:	1788209

        Comment


        • #5
          Wonderful stuff - very elegant. Not to be ungrateful, but I asked that question almost a year ago. Why the response how?
          This forum is great - many thanks for all your help!
          Ben

          Comment


          • #6
            Click image for larger version

Name:	meansgap_demo.png
Views:	1
Size:	99.6 KB
ID:	1788218

            Thanks, Ben! When the discussion picked up again, I thought I’d share a self-contained Stata example for anyone who runs into the same problem.
            And thanks, Nick. Your horizontal rspike answers Ben's question.
            The example above applies it to Ben's wide data layout, with one outcome per row. A second panel shows the signed difference between NP/PA and physicians on a common zero line. The rows are ordered by the absolute difference.

            An asterisk next to an outcome marks p < 0.05 from a two-sided unequal-variance t test for independent groups. The p-values are unadjusted for multiple comparisons and are listed in the Results window along with the means and differences.

            Run the full example in a fresh Stata session to generate the synthetic data. To use your own data, start at the comment "Summarize each outcome" after loading your data and check the two role codes. The example assumes the *_want variables are on a 0-100 scale, so the differences are in percentage points.

            Code:
            version 16.0
            * Standalone example using official Stata commands.
            * For your own data, start at "Summarize each outcome" with the data loaded.
            clear
            set obs 200
            generate byte role = 1 + (_n > 100)
            label define role_labels 1 "Physician" 2 "NP/PA"
            label values role role_labels
            bysort role: generate respondent = _n
            
            * Synthetic 0/100 responses with exact percentages in each group.
            generate byte mental_want = 100*(respondent <= cond(role == 1, 78, 67))
            generate byte heat_want   = 100*(respondent <= cond(role == 1, 64, 56))
            generate byte vector_want = 100*(respondent <= cond(role == 1, 58, 66))
            generate byte air_want    = 100*(respondent <= cond(role == 1, 70, 65))
            generate byte pollen_want = 100*(respondent <= cond(role == 1, 50, 63))
            generate byte trauma_want = 100*(respondent <= cond(role == 1, 69, 53))
            generate byte storm_want  = 100*(respondent <= cond(role == 1, 54, 48))
            generate byte water_want  = 100*(respondent <= 56)
            generate byte food_want   = 100*(respondent <= cond(role == 1, 49, 53))
            
            label variable mental_want "Mental health"
            label variable heat_want   "Heat illness"
            label variable vector_want "Vector-borne illness"
            label variable air_want    "Air quality"
            label variable pollen_want "Pollen"
            label variable trauma_want "Storm/flood trauma"
            label variable storm_want  "Storm/flood illness"
            label variable water_want  "Water-borne illness"
            label variable food_want   "Food-borne illness"
            local demo_subtitle subtitle("Synthetic example", size(small))
            
            * Summarize each outcome for the two role codes.
            * Outcomes are on the 0-100 scale. Edit the role codes below if needed.
            local physician 1
            local nppa 2
            preserve
            keep if inlist(role, `physician', `nppa')
            tempfile summary
            tempname results means_plot gap_plot
            postfile `results' long input_order str32 outcome str244 topic ///
                double mean_a mean_b p using "`summary'"
            local i = 0
            foreach v of varlist *_want {
                local ++i
                local topic : variable label `v'
                if `"`topic'"' == "" local topic `v'
            
                quietly summarize `v' if role == `physician', meanonly
                local n_a = r(N)
                local mean_a = cond(r(N), r(mean), .)
                quietly summarize `v' if role == `nppa', meanonly
                local n_b = r(N)
                local mean_b = cond(r(N), r(mean), .)
            
                local p = .
                if min(`n_a', `n_b') >= 2 {
                    quietly ttest `v', by(role) unequal
                    if r(se) > 0 & r(se) < . local p = r(p)
                }
                if `n_a' + `n_b' > 0 {
                    post `results' (`i') ("`v'") (`"`topic'"') (`mean_a') (`mean_b') (`p')
                }
            }
            postclose `results'
            use "`summary'", clear
            if _N == 0 {
                restore
                error 2000
            }
            
            * Order by absolute difference and mark the outcome labels.
            generate double gap = mean_b - mean_a
            generate double abs_gap = abs(gap)
            gsort -abs_gap input_order
            generate long row = _n
            local last = _N
            local bottom = _N + .5
            forvalues i = 1/`last' {
                local topic = topic[`i']
                if p[`i'] < .05 local topic `"`topic'*"'
                label define topics `i' `"`topic'"', add
            }
            label values row topics
            format p %9.4f
            list outcome mean_a mean_b gap p, noobs separator(0)
            
            * Draw both panels with the same row positions.
            local blue "27 75 116"
            local teal "0 110 99"
            local shared yscale(reverse range(.5 `bottom') noline) ///
                ytitle("") legend(off) scheme(s2color) ///
                graphregion(color(white)) plotregion(fcolor(white) lcolor(white))
            
            twoway ///
                (rspike mean_a mean_b row, horizontal lcolor(gs9) lwidth(medthick)) ///
                (scatter row mean_a, msymbol(O) msize(small) mcolor("`blue'")) ///
                (scatter row mean_b, msymbol(Oh) msize(medlarge) mcolor("`teal'")), ///
                `shared' ylabel(1(1)`last', valuelabel angle(horizontal) noticks nogrid labsize(small)) ///
                xlabel(0(20)100, labsize(small)) xtitle("Moderately or very helpful (%)", size(small)) ///
                title("Group means", size(medsmall)) name(`means_plot') nodraw
            
            * Use a symmetric scale around zero for the differences.
            generate byte zero = 0
            quietly summarize abs_gap, meanonly
            local limit = 1.35
            local ticks 0
            if r(N) > 0 & r(max) > 0 {
                local unit = 10^floor(log10(r(max)))
                local extent = ceil(r(max)/`unit')*`unit'
                local limit = 1.35*`extent'
                local ticks -`extent' 0 `extent'
            }
            generate str16 gap_label = strtrim(string(gap, "%9.3g"))
            replace gap_label = "+" + gap_label if gap > 0 & gap < .
            replace gap_label = "n/a" if missing(gap)
            
            twoway ///
                (rspike zero gap row, horizontal lcolor(gs9) lwidth(medthick)) ///
                (scatter row gap if gap < 0, msymbol(O) mcolor("`blue'") ///
                    mlabel(gap_label) mlabcolor("`blue'") mlabposition(9) mlabsize(small)) ///
                (scatter row gap if gap > 0 & gap < ., msymbol(O) mcolor("`teal'") ///
                    mlabel(gap_label) mlabcolor("`teal'") mlabposition(3) mlabsize(small)) ///
                (scatter row gap if gap == 0, msymbol(O) mcolor(gs6) ///
                    mlabel(gap_label) mlabcolor(gs6) mlabposition(3) mlabsize(small)) ///
                (scatter row zero if missing(gap), msymbol(i) ///
                    mlabel(gap_label) mlabcolor(gs8) mlabposition(3) mlabsize(small)), ///
                `shared' ylabel(1(1)`last', nolabel noticks grid glcolor("231 235 239") glpattern(solid)) ///
                xscale(range(-`limit' `limit')) ///
                xlabel(`ticks', format(%9.3g) labsize(small)) xline(0, lcolor(gs10)) ///
                xtitle("NP/PA minus physician (percentage points)", size(small)) ///
                title("Signed gap", size(medsmall)) name(`gap_plot') nodraw
            
            graph combine `means_plot' `gap_plot', rows(1) imargin(small) ///
                scheme(s2color) graphregion(color(white)) ///
                title("Reported usefulness of health resources", size(medium)) ///
                `demo_subtitle' ///
                note("A = Physician (filled)     B = NP/PA (open)" ///
                    "* p < 0.05 (two-sided unequal-variance t tests, unadjusted)", size(small)) ///
                xsize(9) ysize(5) name(want_gap_builtin, replace)
            graph drop `means_plot' `gap_plot'
            restore
            graph export "meansgap_builtin.png", name(want_gap_builtin) width(1600) replace

            Comment


            • #7
              Nice - many thanks!

              Comment


              • #8
                #5

                Wonderful stuff - very elegant. Not to be ungrateful, but I asked that question almost a year ago. Why the response how?
                Hard for me to explain for myself. I can't reconstruct for myself what was in my mind on 8 December 2025 and whether I saw the question or not, or wanted to reply but didn't.

                The question itself remains highly valuable. People often want something like this and it perhaps should be a little easier in Stata. At the moment I incline to thinking that explaining a few tricks that people can vary is a better way to go than trying to wrap it up in another command, which could wire in too many defaults that then users want or need to change, and so forth.

                The most natural or at least usual name would appear to be dumbbell plot, which doesn't appeal to me on any ground, partly for its association (even tenuously) with very poor jokes. Connected dot plot is a bit better. Paired dot chart I like better.

                I sense a Stata Journal Tip emerging, but plenty of time for others to get in earlier with a command and help file.

                https://journals.sagepub.com/doi/pdf...867X0800800208 and https://journals.sagepub.com/doi/pdf...867X0900900408 had some loosely related material in 2008 and 2009.

                Comment


                • #9
                  Cool. Thanks.

                  Comment


                  • #10
                    Arrows too, particularly for before and after comparisons https://journals.sagepub.com/doi/epd...867X0500500214

                    Comment


                    • #11
                      Cross-reference https://www.statalist.org/forums/for...graph-in-stata

                      Comment

                      Working...
                      X