Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 36 ยท Descriptive and Graphs

Graph Basics in Stata

Draw your first Stata graphs: histogram, scatter plot, line plot, bar graph, box plot and twoway overlays. Learn graph command anatomy, titles, axes, labels, by() and legends.

A good graph often shows what a table of numbers hides: skew, outliers, clusters, curved relationships. Stata has a powerful graphics system with two families of commands: ready-made shortcuts such as histogram, and the flexible twoway family that overlays layers. This lesson walks through the common graphs and the options that make them readable. The commands are read-only here; the editors below draw text-based stand-ins to show the idea.

Anatomy of a graph command

STATA
twoway (scatter price mpg) (lfit price mpg), title("Price and mileage") ///
    xtitle("Miles per gallon") ytitle("Price (USD)") legend(off)
  • twoway starts a plot with x and y axes.
  • Each pair of parentheses is a plot layer: here a scatter plot and a fitted line.
  • After the comma come graph options: titles, axes, legend, size.
  • /// continues a command onto the next line in a do-file (the line-continuation mark).

Each graph opens in the Graph window. Drawing a new graph replaces the previous one unless you give it a name: , name(g1, replace).

Histograms

STATA
sysuse auto, clear
histogram price
histogram price, bin(15) percent
histogram price, width(1000) start(3000) normal
histogram price, by(foreign)
histogram rep78, discrete frequency
  • bin(#) or width(#) sets the bins: too few bars hide structure, too many look noisy.
  • Default shows density (area sums to 1); percent, fraction or frequency change the y-axis.
  • normal overlays a normal curve with the same mean and standard deviation.
  • discrete gives one bar per value for integer variables with few values.

Use kdensity price for a smooth density estimate and graph box/graph dotplot for other views of one variable.

Scatter plots and lines

STATA
scatter price mpg
twoway scatter price mpg, mlabel(make)             // label points
twoway scatter price mpg, msymbol(Oh) mcolor(navy%60)
twoway (scatter price mpg) (lfit price mpg)        // add a linear fit
twoway (scatter price mpg) (qfit price mpg)        // quadratic fit
twoway (scatter price mpg) (lowess price mpg)      // smooth curve
twoway line gnp year                               // line plot over time
twoway (line y1 year) (line y2 year)               // two series
scatter price mpg, by(foreign)                     // panels by group
graph matrix price mpg weight                      // scatter-plot matrix

For a line plot, sort by x first (sort year), because line connects points in data order. Marker options: msymbol() (shape: O circle, D diamond, T triangle, +), msize(), mcolor(). The suffix %60 sets 60% opacity, which helps with overlapping points. With many points, use jitter() or msymbol(p) (a tiny dot).

Bar graphs and box plots

STATA
graph bar price, over(foreign)                     // mean of price by group
graph bar (median) price, over(rep78) over(foreign)
graph bar (count) price, over(rep78)               // counts
graph hbar price, over(rep78) bar(1, color(navy))  // horizontal bars
graph box price, over(foreign)                     // box plot
graph box price mpg, over(foreign) nooutsides      // hide outlier points
graph pie price, over(foreign)                     // pie (use rarely)

A bar graph by default shows the mean of the variable. State the statistic in parentheses: (mean), (median), (sum), (count), (sd). A box plot shows the median, the 25th and 75th percentiles (box), whiskers to the most extreme points within 1.5 times the interquartile range, and the points beyond as outliers.

flowchart TD
    A["What do you want to show?"] --> B["One numeric variable"]
    A --> C["Two numeric variables"]
    A --> D["Category counts or means"]
    A --> E["Trend over time"]
    B --> B1["histogram / kdensity / box"]
    C --> C1["scatter + lfit"]
    D --> D1["graph bar / dot"]
    E --> E1["twoway line"]

Choose the graph from the question you ask of the data.

Titles, axes and labels

STATA
twoway scatter price mpg, ///
    title("Car price by fuel economy") subtitle("74 cars, 1978") ///
    xtitle("Miles per gallon") ytitle("Price (USD)") ///
    xlabel(10(10)40) ylabel(, angle(horizontal) format(%9.0fc)) ///
    note("Source: Stata sample data") ///
    name(price_mpg, replace)
  • xlabel(10(10)40) puts tick labels from 10 to 40 in steps of 10; ylabel(, angle(horizontal)) keeps defaults but turns the text horizontal.
  • xscale(range(0 50)) changes the range; yscale(log) uses a log axis.
  • title(), subtitle(), note() and caption() place text. Use size(small) to shrink it.
  • legend(order(1 "Data" 2 "Fit") position(6)) renames and moves legend entries; legend(off) hides it.
  • plotregion(margin(small)) and graphregion(color(white)) adjust the frame and background.

Several panels: by() and combine

STATA
scatter price mpg, by(foreign, total)           // one panel per group (+ total)
histogram price, by(foreign, cols(1))           // stacked in one column

twoway scatter price mpg, name(a, replace)
histogram price, name(b, replace)
graph combine a b, cols(2) title("Two views")   // join saved graphs

by() repeats the graph for each group. graph combine joins different graphs you have named (name()) or saved (saving() or graph save).

Stand-in: a text histogram and a scatter

Python cannot call Stata's graph engine here, so the two editors draw character plots. They teach the same decision that histogram, width() and scatter involve: how you bin and scale shapes the story.

Python Stand-in: histogram with different bin widths

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Stand-in: a text scatter plot

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does /// do in a do-file?

    Three slashes join the next line to the current command.
  2. 2. What does graph bar price, over(foreign) show by default?

    graph bar uses (mean) unless another statistic is named.
  3. 3. How do you overlay a fitted line on a scatter plot?

    Each plot layer goes in parentheses in a twoway command.
  4. 4. Why sort the data before twoway line?

    Unsorted x values make the line jump back and forth.

Summary

  • twoway stacks plot layers (scatter, line, lfit, lowess) in parentheses; histogram, graph bar and graph box are shortcuts.
  • Bins and scales shape the picture: try several bin() or width() values.
  • Bar graphs show the mean by default; name the statistic ((median), (count)).
  • Options set titles, axis labels, legends and notes; by() makes panels and graph combine joins graphs.
  • Use name() to keep several graphs open and /// to break long commands.

Next: Exporting Graphs, Schemes and Styles