Different label for each bar in a bar chart using Proc sgplot

3k Views Asked by At

I'm trying to add the number of each group into the labels of groups on xaxis using Proc sgplot in SAS. Here is the data and the graph I'd like to have. I want to have sample of each bar on xaxis (hand writen parts). Your help is very much appreciated!

Data have ;
input type  sex $  n n_total percent ;
datalines;
0  F  6    29  20.7 
1  F  387  496 78.2  
0  M  4    15  26.6
1  M  264  305 86.5
;
Run; 

proc sgplot data=have ;
vbarparm category= type  response=percent /group=sex groupdisplay=cluster datalabel;
run; 

Graph that I want to create: enter image description here

2

There are 2 best solutions below

3
On BEST ANSWER

You can compute a bar data label that shows the percent value and the text n=<N>

Example:

Data have ;
input type  sex $  n n_total percent ;
datalines;
0  F  6    29  20.7 
1  F  387  496 78.2  
0  M  4    15  26.6
1  M  264  305 86.5
;
Run; 

data plot;
  set have;
  barlabel = cats(percent) || ' %N/(n=' || cats(n_total, ')');
run;

proc sgplot data=plot;
  vbarparm 
    category=type  
    response=percent 
  / group=sex 
    groupdisplay=cluster 
    datalabel=barlabel datalabelfitpolicy=splitalways splitchar='/'
  ;
  label percent = 'Percent N having some attribute';
run; 

enter image description here

1
On

While I agree with Richard that you might be better off putting this in the bar label, it's easy to put it in an axis table as well.

Data have ;
input type  sex $  n n_total percent ;
datalines;
0  F  6    29  20.7 
1  F  387  496 78.2  
0  M  4    15  26.6
1  M  264  305 86.5
;
Run; 

proc sgplot data=have ;
vbarparm category= type  response=percent /group=sex groupdisplay=cluster datalabel;
xaxistable n_total/class=sex classdisplay=cluster position=bottom location=inside colorgroup=sex;
run; 

classdisplay=cluster makes the values spread out like the bars do, location=inside puts it right below the bar, and colorgroup=sex makes it colored like the bars (instead of black). position=bottom is the default, just highlighting that option.

You could further customize what shows up if you wanted to in the same manner Richard did - by creating a text variable that contains exactly what you want to display for each, and using that as your variable (the first argument to xaxistable). That variable can be numeric or charcter.