Pie charts are a popular tool used to visualize the frequency or percentage of observations in each group of a categorical variable. You can use Stata's graph pie command to create simple pie charts, or you can add options to make more sophisticated charts.
Let's begin by opening the nhanes2l dataset and tabulating the variable hlthstat.
. webuse nhanes2l (Second National Health and Nutrition Examination Survey) . tabulate hlthstat
Health status | Freq. Percent Cum. | |
Excellent | 2,407 23.29 23.29 | |
Very good | 2,591 25.07 48.36 | |
Good | 2,938 28.43 76.79 | |
Fair | 1,670 16.16 92.95 | |
Poor | 729 7.05 100.00 | |
Total | 10,335 100.00 |
Let's use graph pie to create a simple pie chart for the five categories of hlthstat.
. graph pie, over(hlthstat)
Next, let's add a title to our graph. Note that I'm using the “triple slash” to write my command across two lines. You can't do this in the Command window, but it is useful when writing long graph commands in do-files.
. graph pie, over(hlthstat) /// title("Categories of health status")
We could also change the look of our legend and move it below the graph.
. graph pie, over(hlthstat) /// title("Categories of health status") /// legend(rows(1) position(6))
We can use the plabel() option to display the frequency of each category using a medium-sized, black font.
. graph pie, over(hlthstat) /// title("Categories of health status") /// legend(rows(1) position(6)) /// plabel(_all sum, color(black) size(medium))
We could also display the percentage of observations in each category and use the format() option to display one digit to the right of the decimal place.
. graph pie, over(hlthstat) /// title("Categories of health status") /// legend(rows(1) position(6)) /// plabel(_all percent, color(black) size(medium) format(%9.1f))
Or we could remove the legend and display the names of each category in the pie chart.
. graph pie, over(hlthstat) /// title("Categories of health status") /// legend(off) /// plabel(_all name, color(black) size(medium))
We could also create our pie chart for each category of diabetes. Notice that the legend() and title() options are now inside the by() option.
. graph pie, over(hlthstat) /// plabel(_all name, color(black) size(medium)) /// by(diabetes, /// legend(off) /// title("Categories of health status"))
There are many other options that you can use to customize your pie charts, and you can read about them in the manual. You can also watch a demonstration of these commands by clicking on the link to the YouTube video below.
Watch Pie charts in Stata.
Read more in the Stata Graphics Reference Manual; see [G-2] graph pie.