如何在PROC SGPLOT中按百分比降序设置分组条形顺序?
How to Reorder Population Groups by Percent in PROC SGPLOT HBar Chart
Got it, let's fix that grouping order issue in your PROC SGPLOT bar chart. There are two common scenarios depending on exactly what you need—let's break them down:
Scenario 1: Reorder groups per district (each bar's groups sorted by its own Percent descending)
If you want each district's bar segments to appear in descending order of their respective Percent values (so the largest population segment is on top/left for each district), follow these steps:
- First, sort your dataset to ensure that within each district, the population groups are ordered from highest to lowest Percent.
- Use the
GROUPORDER=DATAoption in thehbarstatement to tell SAS to use the order of groups as they appear in the sorted data.
/* Sort data: group by district, then sort within each district by Percent descending */ proc sort data=Colordistricts; by distrct descending Percent; run; /* Generate the bar chart with group order matching the sorted data */ proc sgplot data=Colordistricts; hbar distrct / response=Percent group=population grouporder=data; run;
Scenario 2: Reorder groups globally (fixed order across all districts, sorted by total/average Percent)
If you want a consistent group order across all districts (e.g., "Black Color" first because it has the highest overall Percent across all districts), you'll need to define a custom order based on aggregated values:
- Calculate the total (or average) Percent for each population group to determine their global ranking.
- Create a custom format to map each population group to a sorted label (this ensures SAS recognizes your desired order).
- Use
GROUPORDER=FORMATTEDin thehbarstatement to apply the custom order.
/* Calculate total Percent for each population group */ proc summary data=Colordistricts nway; class population; var Percent; output sum=TotalPercent; /* Use mean=AvgPercent if you prefer average instead */ run; /* Sort the summary data by total Percent descending to get our desired order */ proc sort data=summary; by descending TotalPercent; run; /* Create a format that assigns ordered labels to each population group */ proc format cntlin=summary; value $poporder 'Black Color' = '1. Black Color' /* Adjust these values to match your summary results */ 'White' = '2. White' 'Asian' = '3. Asian'; run; /* Apply the format and generate the chart with the global custom order */ proc sgplot data=Colordistricts; format population $poporder.; hbar distrct / response=Percent group=population grouporder=formatted; run;
Key Notes:
- The
GROUPORDERoption is critical here:DATAuses the order groups appear in your dataset, whileFORMATTEDuses the order defined by your custom format. - If you go with the global order, double-check the
$poporderformat to make sure the labels match the sorted results from yourproc summarystep.
内容的提问来源于stack exchange,提问作者Nathan123
相关产品推荐
相关产品推荐

