Skip to content

brycewang-stanford/Auto-Empirical-Research-Skills / skills/32-dylantmoore-stata-skill/plugins/stata/skills/stata

Comprehensive Stata reference for writing correct .do files, data management, econometrics, causal inference, graphics, Mata programming, and 20 community packages (reghdfe, estout, did, rdrobust, etc.). Covers syntax, options, gotchas, and idiomatic patterns. Use this skill whenever the user asks you to write, debug, or explain Stata code.

FileKindSize
SKILL.mdskill md16.4 KB
packages/asdoc.mdmarkdown8.5 KB
packages/binsreg.mdmarkdown10.1 KB
packages/coefplot.mdmarkdown10.1 KB
packages/data-manipulation.mdmarkdown10.1 KB
packages/diagnostics.mdmarkdown15.3 KB
packages/did.mdmarkdown16.0 KB
packages/estout.mdmarkdown17.7 KB
packages/event-study.mdmarkdown29.8 KB
packages/graph-schemes.mdmarkdown14.1 KB
packages/ivreg2.mdmarkdown11.1 KB
packages/nprobust.mdmarkdown12.4 KB
packages/outreg2.mdmarkdown11.2 KB
packages/package-management.mdmarkdown10.2 KB
packages/psmatch2.mdmarkdown18.6 KB
packages/rdrobust.mdmarkdown13.4 KB
packages/reghdfe.mdmarkdown10.4 KB
packages/synth.mdmarkdown23.0 KB
packages/tabout.mdmarkdown12.1 KB
packages/winsor.mdmarkdown6.7 KB
packages/xtabond2.mdmarkdown14.9 KB
references/advanced-programming.mdmarkdown10.1 KB
references/basics-getting-started.mdmarkdown5.8 KB
references/bootstrap-simulation.mdmarkdown8.4 KB
references/data-import-export.mdmarkdown7.4 KB
references/data-management.mdmarkdown11.0 KB
references/date-time-functions.mdmarkdown6.8 KB
references/descriptive-statistics.mdmarkdown6.4 KB
references/difference-in-differences.mdmarkdown20.9 KB
references/external-tools-integration.mdmarkdown20.1 KB
references/filing-issues.mdmarkdown4.7 KB
references/gmm-estimation.mdmarkdown8.8 KB
references/graphics.mdmarkdown8.6 KB
references/limited-dependent-variables.mdmarkdown8.2 KB
references/linear-regression.mdmarkdown12.4 KB
references/machine-learning.mdmarkdown12.4 KB
references/mata-data-access.mdmarkdown8.2 KB
references/mata-introduction.mdmarkdown6.4 KB
references/mata-matrix-operations.mdmarkdown6.3 KB
references/mata-programming.mdmarkdown8.4 KB
references/matching-methods.mdmarkdown19.2 KB
references/mathematical-functions.mdmarkdown7.4 KB
references/maximum-likelihood.mdmarkdown16.6 KB
references/missing-data-handling.mdmarkdown18.5 KB
references/nonparametric-methods.mdmarkdown11.7 KB
references/panel-data.mdmarkdown8.7 KB
references/programming-basics.mdmarkdown8.1 KB
references/regression-discontinuity.mdmarkdown13.4 KB
references/sample-selection.mdmarkdown17.7 KB
references/sem-factor-analysis.mdmarkdown15.2 KB
references/spatial-analysis.mdmarkdown19.4 KB
references/string-functions.mdmarkdown8.7 KB
references/survey-data-analysis.mdmarkdown13.7 KB
references/survival-analysis.mdmarkdown12.3 KB
references/tables-reporting.mdmarkdown24.2 KB
references/time-series.mdmarkdown9.9 KB
references/treatment-effects.mdmarkdown23.1 KB
references/variables-operators.mdmarkdown4.9 KB
references/workflow-best-practices.mdmarkdown25.8 KB

references/graphics.md

View on GitHub
# Graphics in Stata

## Twoway Graphs

### Scatter Plots

```stata
twoway scatter mpg weight

// Marker customization
twoway scatter mpg weight, ///
    msymbol(square) msize(medium) mcolor(blue)
// Symbols: circle, square, triangle, diamond, plus, x, oh, dh, etc.

// Marker labels
twoway scatter mpg weight, ///
    mlabel(make) mlabposition(3) mlabsize(vsmall)
// Position uses clock notation: 12=top, 3=right, 6=bottom, 9=left

// Jitter to reduce overplotting
twoway scatter mpg weight, jitter(5)
```

### Line and Connected Plots

```stata
twoway line mpg weight, sort
twoway connected mpg weight, sort     // Lines + markers
```

### Overlaying Multiple Plot Types

```stata
// Scatter with linear fit and CI
twoway (scatter mpg weight) (lfitci mpg weight)

// Groups with different markers
twoway (scatter mpg weight if foreign==0, msymbol(circle) mcolor(blue)) ///
       (scatter mpg weight if foreign==1, msymbol(triangle) mcolor(red)), ///
       legend(label(1 "Domestic") label(2 "Foreign"))

// Scatter + linear + quadratic fit
twoway (scatter mpg weight) (lfit mpg weight) (qfit mpg weight)
```

### Area and Range Plots

```stata
twoway area mpg weight, sort fcolor(blue%30)

// Shaded confidence interval
twoway (rarea upper lower x, fcolor(gray%20)) (line yhat x)

// Range plots
twoway rcap lower upper x              // With caps
twoway rspike lower upper x            // Spikes
twoway rbar lower upper x              // Bars
```

### Function Plots

```stata
twoway function y=normalden(x), range(-4 4)

twoway (function y=x, range(-5 5)) ///
       (function y=x^2, range(-5 5))
```

---

## Bar and Box Plots

### Graph Bar

```stata
graph bar mpg, over(foreign)
graph hbar mpg, over(foreign)           // Horizontal
graph bar (count) mpg, over(foreign)    // Frequencies
graph bar, over(foreign) percent        // Percentages

// Bar labels and multiple grouping
graph hbar mpg, over(foreign) over(rep78) ///
    blabel(bar, format(%4.1f))

// Custom colors, stacking
graph bar (mean) mpg (mean) price, over(foreign) ///
    stack bar(1, color(navy)) bar(2, color(maroon))

// Sorted bars
graph hbar (mean) mpg, over(make, sort(1) descending)
```

### Graph Box

```stata
graph box mpg, over(foreign)
graph box mpg, over(foreign) noout      // Remove outliers
graph box mpg, over(foreign) over(rep78)

// Customization
graph box mpg, over(foreign) ///
    box(1, fcolor(navy%50)) box(2, fcolor(maroon%50)) ///
    medtype(line) medline(lwidth(thick) lcolor(red))
```

**GOTCHA: `graph box` is incompatible with `twoway`** — you cannot place `graph box` inside a `twoway` call or use `addplot()` with it. For overlaying jittered points on box plots, build boxes manually with `twoway rbar`/`rspike`/`scatter` primitives. The stats tempfile must be group-level (one row per group via `collapse`), not observation-level — merging observation-level data back as `m:1` causes `r(459)`.

---

## Histograms

```stata
histogram mpg                           // Density (default)
histogram mpg, frequency                // Counts
histogram mpg, fraction                 // Proportions
histogram mpg, percent                  // Percentages
histogram mpg, bin(10) start(10)        // Bin control

// With normal overlay and labels
histogram mpg, frequency bin(15) normal ///
    addlabel fcolor(navy%60) lcolor(navy)

// Discrete variable
histogram rep78, discrete percent addlabel xlabel(1(1)5)

// By group
histogram mpg, by(foreign) frequency bin(10)
```

---

## Graph Options

### Titles and Labels

```stata
twoway scatter mpg weight, ///
    title("Main Title", size(medium)) ///
    subtitle("Subtitle") ///
    note("Note at bottom") ///
    xtitle("Weight (pounds)") ///
    ytitle("Mileage (mpg)")
```

### Axis Options

```stata
twoway scatter mpg weight, ///
    xscale(range(1500 5000)) yscale(range(10 40)) ///
    xlabel(2000(1000)5000, format(%9.0fc)) ///
    ylabel(10(5)40, angle(0))

// Log scale, reverse axis
twoway scatter mpg weight, xscale(log) yscale(reverse)

// Multiple y-axes
twoway (scatter mpg weight, yaxis(1)) ///
       (scatter price weight, yaxis(2))
```

### Legend Options

```stata
// Position: clock notation (0=center inside, 6=bottom outside)
legend(position(6) rows(1))
legend(ring(0) position(5))            // Inside plot at 5 o'clock
legend(label(1 "Domestic") label(2 "Foreign"))
legend(order(2 "Foreign" 1 "Domestic")) // Reorder
legend(off)                             // Remove
legend(title("Origin"))
```

### Graph Region

```stata
graphregion(color(white))               // White background
plotregion(color(gs15) margin(medium))
aspectratio(1)                          // Square plot
xsize(8) ysize(6)                       // Size in inches

// Grid lines
ylabel(, grid gstyle(dot))
xlabel(, grid)
```

---

## Schemes and Styles

```stata
set scheme s2color                      // Default color
set scheme s1mono                       // Black and white
set scheme economist                    // Economist style
set scheme sj                           // Stata Journal
twoway scatter mpg weight, scheme(plotplain)  // Per-graph

// Community schemes
ssc install blindschemes, replace       // plotplain
ssc install schemepack, replace         // white_tableau, gg_hue, etc.
set scheme white_cividis                // Colorblind-friendly
```

### grstyle for Quick Customization

```stata
ssc install grstyle, replace
ssc install palettes, replace
grstyle init
grstyle set plain
grstyle set color hue
grstyle clear                           // Reset
```

### Publication Recommendations

- B&W journals: `s1mono` or `plotplain`
- Color online: `sj` or `plotplain`
- Presentations: `economist` or `white_tableau`
- Colorblind: `white_cividis`

---

## Combining Graphs

```stata
// Create named graphs
twoway scatter mpg weight, name(g1, replace) nodraw
twoway scatter mpg length, name(g2, replace) nodraw

// Combine
graph combine g1 g2, rows(1)           // Side by side
graph combine g1 g2, cols(1)           // Stacked

// Options
graph combine g1 g2, ///
    ycommon xcommon ///                 // Shared axes
    iscale(0.8) ///                     // Scale internal elements
    imargin(medium) ///                 // Margin around each
    title("Combined Figure")

// From saved files
graph save graph1.gph, replace
graph combine graph1.gph graph2.gph

// Different panel sizes
twoway scatter mpg weight, fxsize(66.67) name(left, replace)
graph bar mpg, over(foreign) fxsize(33.33) name(right, replace)
graph combine left right, cols(2)
```

---

## Exporting Graphs

```stata
// Vector formats (scalable, best for publications)
graph export figure.pdf, replace
graph export figure.eps, replace
graph export figure.svg, replace

// Raster formats
graph export figure.png, width(3000) replace   // High-res
graph export figure.png, width(800) replace     // Web

// Save Stata format for editing
graph save figure.gph, replace
```

**Best practices by use case:**
- Word: `.emf` (Windows) or `.png` width(1200)
- LaTeX: `.pdf` or `.eps`
- PowerPoint: `.png` width(1920)
- Web: `.png` width(800) or `.svg`
- Journal: `.eps`, `.tif` width(3000), or `.pdf`

```stata
// Batch export
foreach g in g1 g2 g3 {
    graph export `g'.png, name(`g') width(1200) replace
}
```

---

## Marginsplot

```stata
regress mpg i.foreign weight
margins foreign
marginsplot

// Continuous variable
margins, at(weight=(2000(500)4500))
marginsplot

// Interaction: continuous x categorical
regress mpg c.weight##i.foreign
margins foreign, at(weight=(2000(250)4500))
marginsplot, xdimension(weight) recast(line) recastci(rarea)

// Marginal effects
margins, dydx(weight) at(weight=(2000(500)4500))
marginsplot, yline(0, lpattern(dash))

// Customization
marginsplot, ///
    recast(bar)                         // Bar plot
    recast(line) recastci(rarea)        // Line + shaded CI
    plot1opts(lcolor(navy) lwidth(medthick))
    ci1opts(fcolor(navy%15) lwidth(none))
```

### Combining Marginsplots

```stata
quietly regress mpg weight
margins, at(weight=(2000(500)4500))
marginsplot, name(m1, replace) nodraw

quietly regress mpg c.weight##i.foreign
margins foreign, at(weight=(2000(500)4500))
marginsplot, xdimension(weight) name(m2, replace) nodraw

graph combine m1 m2, ycommon
```

---

## Quick Reference

| Graph Type | Command |
|---|---|
| Scatter | `twoway scatter` |
| Line | `twoway line` |
| Bar chart | `graph bar` / `graph hbar` |
| Box plot | `graph box` / `graph hbox` |
| Histogram | `histogram` |
| Margins | `marginsplot` |

**Key options:** `title()`, `xtitle()`, `ytitle()`, `xlabel()`, `ylabel()`, `legend()`, `scheme()`, `graphregion()`, `plotregion()`

**Combining:** `graph combine g1 g2`, `rows()`, `cols()`, `ycommon`, `xcommon`

**Export:** `graph export file.pdf`, `graph export file.png, width(3000)`, `graph save file.gph`
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 323kUpdated Claude CodeCodexVerifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 323kUpdated Claude CodeCodexVerifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 323kUpdated Claude CodeCodexVerifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 198kUpdated Claude CodeCodexVerifiedInstall