colorssasgchart

Assign colors to vertical bars using proc gchart in SAS


In PROC GCHART, when creating a bar chart, the color of a vertical bar is determined by the PATTERN statement. The PATTERN statement assigns colors to the bars based on the alphabetical or hierarchical order of the values. How can I specifically assign a color based on a value? For example, if my values are "boy" and "girl," how can I make the value "boy" appear in blue regardless of whether the value "girl" exists and vice versa?


Solution

  • Unfortunately, if you are using SAS/GRAPH, you can't use an attribute map, which is the way to handle this. If you have SAS 9.2+, you can use ODS Graphics (PROC SGPLOT), which has that option. attrmap connects the proc with a dataset that stores the values of a variable and the color (or other attributes) associated with each value of that variable.

    An example from the SAS doc page on SGPLOT:

    *create dummy dataset;
    data finances;
    format income dollar8. expense dollar8.;
    length expensetype $ 9;
    input Year incometype $ income expensetype $ expense;
    datalines;
    2000 Salary 20000 Utilities 4000
    2000 Bonus   2000 Rent      7000
    2000 Gifts    500 Food      8000 
    2001 Salary 25000 Utilities 5000
    2001 Bonus   1000 Rent      8000
    2001 Gifts    200 Food      6000 
    2002 Salary 23000 Utilities 4500
    2002 Bonus    500 Rent      9000
    2002 Gifts    500 Food      7000
    ;
    run;
    
    *Create attribute map.  ID = used to specify its use later, usually matches the variable but does not have to.  Value is the value you are changing the color/etc. for.  Then variables appropriate to what you are changing and to what, so fillcolor here for example.  ;
    data attrmap;
    length value $ 9 fillcolor $ 9; *I find that problems with attrmaps usually are due to length differences in dataset variables vs attrmap variables;
    retain linecolor "black";  *using black for all of them;
    input id $ value $ fillcolor $;
    datalines;
    income  Salary    blue
    income  Bonus     gray
    income  Gifts     lightgray
    expense Utilities red
    expense Rent      yellow
    expense Food      orange
    ;
    run;
    
    
    proc sgplot data=finances dattrmap=attrmap; *specifying the attrmap here;
    yaxis label="Dollars";
    vbarparm category=year response=income / group=incometype attrid=income  /*using the attrmap here */
             barwidth=0.4 discreteoffset=-0.2 name="income"; 
    vbarparm category=year response=expense / group=expensetype attrid=expense
             barwidth=0.4 discreteoffset=0.2 name="expense"; 
    keylegend "income" / position=bottomleft title="Income";
    keylegend "expense" / position=bottomright title="Expenses";
    run;