100% stacked bar chart in SAS’s SGPLOT

A 100% stacked bar chart is useful for comparing the relative frequencies of an m x n table where frequencies in m are very different. While this is easy to do in Excel, SAS requires an extra step, which you could call a hack or a trick.

First, let’s create an example data set. Say we have a happiness survey of 500 people from Texas and Wyoming, and 90% of the responses are from the more popular state.

data survey;
	length state $10.;
	length mood $5.;

	do i = 1 to 500;
		if uniform(-1) < 0.1 then do;
			state  = 'Wyoming';
			if uniform(-1) < 0.9 then mood = 'happy';
			else mood = 'sad';
		else do;
			state = 'Texas';
			if uniform(-1) < 0.7 then mood = 'happy';
			else mood = 'sad';
	drop i;

Next let’s make create a standard barchart of absolute frequencies:

/* side-by-side bars */
/* if you want stacked bars, remove groupdisplay= */
proc sgplot data=survey;
	vbar state / group=mood groupdisplay=cluster;

Which state is happier? It’s hard to compare the two states because the magnitudes are off:

SAS SGPLOT bar chart

From here you could try a pie chart to compare proportions, but this could make Edward Tufte cry. Don’t give up on the bar chart yet.

The trick to making relative frequencies where each state adds up to 100% is to precalculate the relative frequencies using PROC FREQ:

proc freq data=survey;
	table state * mood/out=freq outpct;

proc sgplot data=freq;
	vbar state /  
		response=pct_row  /* response= means SGPLOT will plot the summed the values */

stacked bar chart adding to 100%, SAS SGPLOT

Finally (from this fictional data) it is clear that Wyoming is a happier state.

This code was run on SAS 9.3. For an alternative way using PROC GCHART (especially if you still use SAS 9.1), see “Create a bar chart in which the subgroups total 100% for each midpoint” (SAS.com).


5 thoughts on “100% stacked bar chart in SAS’s SGPLOT

  1. This is a big chart for only two numbers. I would rather write it in a sentence than show it in a chart.
    “Texas: 70% Happy. Wyoming: 90% Happy.”
    Or even better, give the take away message : “People are more happy in Wyoming (90%) than in Texas (70%).”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s