How to Build Bar Graphs in Stata: A Step‑by‑Step Guide
Bar charts are a go‑to visual for summarizing categorical data, and Stata makes them surprisingly straightforward. Whether you’re prepping a conference slide or checking a model’s output, learning to create bar graphs in Stata will save you time and polish your results.
Why Choose Bar Graphs in Stata?
Stata’s graphics engine blends flexibility with consistency. You can produce simple frequency bars with a single line of code, yet also layer error bars, stack categories, or apply custom color palettes without leaving the command window. Because the syntax stays within the same framework as data manipulation, reproducing a graph for a new dataset is just a matter of tweaking a few options.
Step 1: Prepare Your Data
Before you type any graph command, make sure the variables you plan to plot are in the right shape. For a basic bar chart you’ll need a categorical variable (the x‑axis) and either a count or a summary statistic (the y‑axis).
- Counting observations. If you simply want to see how many cases fall into each category, the
graph barcommand can compute frequencies on the fly. - Summarizing a numeric variable. Use
collapseor theby:prefix to calculate means, medians, or totals first. - Handling missing values. Stata excludes missing entries by default, but you can add the
missingoption if you need to display them.
Example: collapse (mean) income, by(region) creates a dataset where each region has its average income ready for plotting.
Step 2: Choose the Right Bar Command
Stata offers two primary commands for bar charts: graph bar and twoway bar. The former is designed for categorical summaries, while the latter gives more control over axes and layering.
- Simple frequencies.
graph bar, over(sex)draws a bar for each level of sex. - Grouped bars.
graph bar (mean) wage, over(education) over(gender)produces side‑by‑side bars for each education level split by gender. - Stacked bars. Add the
stackoption to combine groups within each category.
If you need to overlay a line or scatter plot, switch to twoway syntax: twoway (bar y x) (line y2 x).
Step 3: Tweak the Appearance
Good graphics balance clarity with visual appeal. Stata’s options let you adjust titles, labels, colors, and legends without rewriting the whole command.
- Titles and subtitles.
title("Average Wage by Education") subtitle("Survey 2023") - Axis labels. Use
ylabel(, angle(horizontal))to rotate tick marks for readability. - Colors. The
color()option accepts named palettes (e.g.,color(pastel)) or explicit RGB values. - Bar width and gap. Adjust
barwidth()andgap()to prevent bars from looking cramped.
Remember to keep the legend concise; a crowded legend defeats the purpose of a clean bar chart.
Step 4: Add Error Bars or Confidence Intervals
When presenting summary statistics, showing variability can be crucial. Stata’s ci and blabel() options let you attach confidence intervals directly onto the bars.
Example: graph bar (mean) wage, over(education) ci draws error bars representing the 95 % confidence interval around each mean. If you prefer a custom interval, calculate it beforehand and feed it via the yvar() option.
Step 5: Export the Graph
Once you’re happy with the look, save the graph in a format that matches your audience. Stata’s graph export command supports PNG, PDF, SVG, and EPS.
- High‑resolution PNG.
graph export mygraph.png, width(1200) replace - Publication‑ready PDF.
graph export mygraph.pdf, replace - Editable vector graphics. Choose SVG if you need to tweak the image later in Illustrator.
Adding replace overwrites an existing file, which is handy during iterative work.
Common Pitfalls and How to Avoid Them
Even seasoned users stumble over a few quirks.
- Over‑crowded categories. If a variable has too many levels, consider recoding it into broader groups.
- Misaligned axes. When using
twoway, setyaxis(1)for both plots to keep scales consistent. - Forgotten
sort. Bar order follows the underlying data order; usesortor theasc/descoptions to control the sequence.
Putting It All Together: A Mini Script
The following block demonstrates a typical workflow from raw data to a polished bar chart.
* Load datause survey2023.dta, clear
* Summarize income by region
collapse (mean) income, by(region)
* Create bar graph with confidence intervals
graph bar (mean) income, over(region) ci ///
title("Mean Income by Region") ///
ylabel(, angle(horizontal)) ///
color(pastel) barwidth(0.6) gap(0.2)
* Export as PDF
graph export income_by_region.pdf, replace
Adjust the options to suit your own dataset, and you’ll have a publication‑ready chart in minutes.
Frequently Asked Questions
Can I create horizontal bar charts in Stata? Yes. Add the horizontal option to graph bar, e.g., graph bar, over(sex) horizontal.
How do I display percentages instead of counts? Use the percent suboption: graph bar, over(category) percent will scale each bar to reflect its share of the total.
Is it possible to label each bar with its exact value? The blabel(bar, format(%9.2f)) option places numeric labels directly on the bars, customizing the format as needed.
What if I need to combine a bar chart with a line chart? Switch to twoway syntax and layer the plots: twoway (bar y x) (line y2 x, lcolor(red)).