SAS: How to Plot Means with Standard Error Bars


You can use the following syntax in SAS to create a plot of mean values with standard error bars by group:

/*calculate mean and standard error of points for each team*/
proc sql;
create table groupPlot as
select 
    team, 
    mean(points) as meanPoints, 
    mean(points) - stderr(points) as lowStdPoints,    
    mean(points) + stderr(points) as highStdPoints
from my_data
group by team;
quit;

/*create plot with mean and standard error bars of points for each team*/
proc sgplot data=groupPlot;
scatter x=team y=meanPoints / 
    yerrorlower=lowStdPoints yerrorupper=highStdPoints group=team;
series x=team y=meanPoints / group=team;
run;

This particular example uses PROC SQL to calculate the mean value of the points variable, grouped by the team variable in some dataset.

We then use PROC SGPLOT to create a plot that shows the mean value of the points variable along with standard error bars, grouped by the team variable.

The following example shows how to use this syntax in practice.

Example: Plotting Means with Standard Error Bars in SAS

Suppose we have the following dataset that contains information about the points scored by basketball players on various teams:

/*create dataset*/
data my_data;
    input team $ points;
    datalines;
A 29
A 23
A 20
A 21
A 33
B 14
B 13
B 17
B 14
B 15
C 21
C 22
C 20
C 25
C 24
;
run;

/*view dataset*/
proc print data=my_data;

Suppose we would like to create a plot that shows the mean value of points along with standard error bars for each team.

We can use the following syntax to do so:

/*calculate mean and standard error of points for each team*/
proc sql;
create table groupPlot as
select 
    team, 
    mean(points) as meanPoints, 
    mean(points) - stderr(points) as lowStdPoints,    
    mean(points) + stderr(points) as highStdPoints
from my_data
group by team;
quit;

/*create plot with mean and standard error bars of points for each team*/
proc sgplot data=groupPlot;
scatter x=team y=meanPoints / 
    yerrorlower=lowStdPoints yerrorupper=highStdPoints group=team;
series x=team y=meanPoints / group=team;
run;

The tiny circles show the mean points value for each team and the bars extending from the circles show the standard error of points for each team.

We can also print the table we created using PROC SQL to see the actual mean and standard error values:

/*print mean and standard error of points for each team*/
proc print data=groupPlot;

The values in this table match the ones shown in the plot above.

Additional Resources

The following tutorials explain how to create other charts in SAS:

How to Create Line Plots in SAS
How to Create Boxplots by Group in SAS
How to Create a Scatterplot with Regression Line in SAS

Leave a Reply

Your email address will not be published. Required fields are marked *