BookmarkSubscribeRSS Feed
tc
Lapis Lazuli | Level 10 tc
Lapis Lazuli | Level 10

ElectoralVotes.png

 

Might create another chart with actuals once the election results are in, but for now here's a SAS ODS Graphics Waterfall chart that shows how a candidate could win only 12 states and still get elected President. Night, all!

 

 

* Fun With SAS ODS Graphics: How Many States Does It Take To Win A Presidential Election?;

* Get Electoral College Votes and Estimated Population by State
  https://en.wikipedia.org/wiki/1836_United_States_presidential_election
  https://www.census.gov/data/tables/time-series/demo/popest/2020s-state-total.html;
  
proc import datafile='/home/ted.conway/StatesVotesPopulation.xlsx' out=StatesVotesPopulation dbms=xlsx;

* Get state name to state code mapping;

proc import datafile='/home/ted.conway/state2statecd.xlsx' out=state2statecd dbms=xlsx;

proc sql;                                             * Join data;
create table statecodesvotespopulation as
select coalesce(s2c.statecd, svp.state) as statecd, svp.*
from StatesVotesPopulation svp left join state2statecd s2c on svp.state=s2c.state order by votes desc;

data statecodesvotespopulationrank;                   * Rank states by # electoral votes for Waterfall chart;
set statecodesvotespopulation;
rank=_n_;

%SGANNO;                                              * Annotate chart with Wikipedia pics of Harris and Trump using SAS-provided macros;         
data presidentpics;                                   * Pics from https://en.wikipedia.org/wiki/2024_United_States_presidential_election;
%SGIMAGE (image="/home/ted.conway/Harris.png",drawspace="DATAVALUE",xc1="WI",y1=110,height=80,heightunit="DATA",anchor="BOTTOM");
%SGIMAGE (image="/home/ted.conway/Trump.png",drawspace="DATAVALUE",xc1="MS", y1=110, height=80,heightunit="DATA",anchor="BOTTOM");

ods graphics / height=11in width=14in imagefmt=png;   * Create waterfall plot of votes by state - 538 total, takes 270 to win!;
proc sgplot data=statecodesvotespopulationrank noborder nowall sganno=presidentpics;
inset 'Q. HOW MANY STATES DOES IT TAKE TO WIN THE PRESIDENCY?' ' ' 'A. JUST TWELVE!' ' ' / textattrs=(size=16pt weight=bold) position=bottom;
waterfall category=statecd response=votes / datalabel fillattrs=(color=royalblue) baselineattrs=(thickness=0) barwidth=1 nooutline finalbarattrs=(color=royalblue) finalbartickvalue='ALL';
xaxis display=(nolabel noticks) grid valueattrs=(size=8.5pt) fitpolicy=none;    
yaxis display=(noticks) label='ELECTORAL VOTES' grid valueattrs=(size=9pt);
refline 270 / axis=y label='270 (YOU WIN!)' labelloc=inside labelpos=min lineattrs=(thickness=2pt) labelattrs=(weight=bold);

 

 

SAMPLE DATA

SampleElectoralCollegeData.png

6 REPLIES 6
Rick_SAS
SAS Super FREQ

Nice application of the little-used WATERFALL statement in PROC SGPLOT. This chart type is also called a "cascade chart." It is useful for visualizing cumulative sums. For readers who have never used a cascade plot, see Create a cascade chart in SAS - The DO Loop

tc
Lapis Lazuli | Level 10 tc
Lapis Lazuli | Level 10

2024ElectoralResultsUpdate.png

 

A follow-up SAS ODS Graphics step plot of electoral votes won by each candidate for each state using the latest results from NBC News.

  

* Fun With SAS ODS Graphics: 2024 Electoral College Results
  Based on nbcnews.com/politics/2024-elections/president-results;

* Get Electoral College Votes and Most Recent Results by State
  https://www.nbcnews.com/politics/2024-elections/president-results;
proc import datafile='/home/ted.conway/PresidentialElectionResults2024.xlsx' out=ElectionResults dbms=xlsx replace;

* Get state name to state code mapping;
proc import datafile='/home/ted.conway/state2statecd.xlsx' out=state2statecd dbms=xlsx;

proc sql;                                             * Append state abbreviation (special join logic for split states, DC);
create table StateCodesElectionResults as
select s2c.statecd, case when harris>trump then 'Harris' else 'Trump' end as Winner, sum(er.votes) as Votes
from ElectionResults er 
left join state2statecd s2c on translate(er.state,' ','123')=s2c.state or scan(er.state,-1,' ,')=s2c.statecd
group by winner, s2c.statecd order by winner;
                                                      * Get total electoral votes for each state for ranking (biggest first);
create table statevotes as select statecd, sum(votes) as numvotes from StateCodesElectionResults group by 1 order by 2 desc, 1;
create table rankstatevotes as select monotonic() as rank, sv.* from statevotes sv;
                                                      * Append rankings;
create table StateCodesElectionResultsRank as
select s.*, r.rank from StateCodesElectionResults s join rankstatevotes r on s.statecd=r.statecd
order by winner, rank;

data data2chart;                                      * Get cumulative vote totals for chart for candidates;
set StateCodesElectionResultsRank;
by winner;
if first.winner then totvotes=0;
totvotes+votes;

proc sort data=data2chart; by rank winner;            * Put data back in order for charting (states with most votesfirst); 

%SGANNO;                                              * Anotate chart with Wikipedia pics of Harris and Trump using SAS-provided macros;         
data presidentpics;                                   * Pics from https://en.wikipedia.org/wiki/2024_United_States_presidential_election;
%SGIMAGE (image="/home/ted.conway/Harris.png",drawspace="DATAVALUE",xc1="WY",y1=217,height=45,heightunit="DATA",anchor="TOPRIGHT");
%SGIMAGE (image="/home/ted.conway/Trump.png",drawspace="DATAVALUE",xc1="WY", y1=300, height=45,heightunit="DATA",anchor="TOPRIGHT");
%SGTEXT (LABEL="312",drawspace="DATAVALUE",xc1="SD", y1=253, textsize=16, textweight="bold",textcolor="red",anchor="TOP"); * Trump electoral votes;
%SGTEXT (LABEL="226",drawspace="DATAVALUE",xc1="SD", y1=170, textsize=16, textweight="bold",textcolor="blue",anchor="TOP"); * Harris electoral votes;

ods graphics / antialias height=11in width=14in;      * Create step plot of electoral votes by state by candidate;
proc sgplot data=data2chart noborder nowall sganno=presidentpics;
styleattrs datacontrastcolors=(blue red);             * Party colors;
inset "2024 ELECTORAL COLLEGE RESULTS" ' ' ' ' / textattrs=(size=24pt weight=bold) position=bottom;
step x=statecd y=totvotes / grouporder=data group=winner discreteoffset=0 datalabelpos=top justify=center datalabel=statecd markers filledoutlinedmarkers  markerattrs=(symbol=circlefilled) lineattrs=(thickness=2pt);
xaxistable votes / label=" ";                         * Electoral votes for each state;
xaxis display=(nolabel noticks noline) grid valueattrs=(size=8.5pt) fitpolicy=none;    
yaxis display=(noticks noline) label='ELECTORAL VOTES' grid valueattrs=(size=9pt) offsetmax=.075 values=(0 to 325 by 100);
keylegend / position=bottom location=inside noborder title=" "; * Legend for candidates;
refline 270 / axis=y label='270 to Win' labelloc=inside labelpos=min lineattrs=(thickness=2pt); * Votes needed to win;
run;

 

 

Rick_SAS
SAS Super FREQ

I think you need to use the JUSTIFY=LEFT option for the STEP function instead of JUSTIFY=CENTER. That will make the step function to increase when it gets to the location of the state that awards the electoral votes.

tc
Lapis Lazuli | Level 10 tc
Lapis Lazuli | Level 10

2024ElectoralResultsUpdateV2.png

 

@Rick_SAS: Thanks - that does indeed greatly improve things!

Ksharp
Super User

TC,

I think use warterfill graph in clinical trial ,would better .

 

data president;
infile cards expandtabs truncover;
input panel stat $ n name $ cutoff;
cards;
1 Trump  312 Trump  270
1 Harris 226 Harris
2 CA 54  Harris
2 TX 40  Trump
2 FL 30 Trump
2 NY 28 Harris
2 IL 19 Harris
2 PA 19 Trump
2 OH 17 Trump
2 GA 16 Trump
2 NC 16 Trump
2 MI 15 Trump
2 NJ 14 Harris
2 VA 13 Harris
2 WA 12 Harris
2 AZ 11 Trump
2 IN 11 Trump
2 MA 11 Harris
2 TN 11 Trump
2 CO 10 Harris
2 MD 10 Trump
2 MN 10 Harris
2 MO 10 Harris
2 WI 10 Trump
2 AL 9 Trump
2 SC 9 Trump
2 KY 8 Trump
2 LA 8  Trump
2 OR 8 Harris
2 CT 7 Harris
2 OK 7 Trump
2 AR 6 Trump
2 IA 6 Trump
2 KS 6 Trump
2 MS 6 Trump
2 NV 6 Trump
2 UT 6 Trump
2 NE 5 Trump
2 NM 5 Harris
2 HI 4 Harris
2 ID 4 Trump
2 ME 4 Trump
2 MT 4 Trump
2 NH 4 Harris
2 RI 4 Harris
2 WV 4 Trump
2 AK 3 Trump
2 DC 3 Harris
2 DE 3 Harris
2 ND 3 Trump
2 SD 3 Trump
2 VT 3 Harris
2 WY 3 Trump
;

%SGANNO;                                                  
data sganno;                                  
%SGTEXT (LABEL="270 to Win",drawspace="GRAPHPERCENT",y1=99, x1=82,  WIDTH=20,textsize=10); 
run;
ods graphics / antialias height=1000px width=600px; 
proc sgpanel data=president noautolegend sganno=sganno;
panelby panel/onepanel spacing=10 noborder layout=rowlattice noheader PROPORTIONAL uniscale=column;
styleattrs datacolors=(red blue);
hbar stat/response=n group=name categoryorder=respdesc datalabel nooutline ;
refline cutoff / axis=x  lineattrs=(thickness=2pt); 
colaxis display=none;
rowaxis display=(nolabel);
run;

Ksharp_0-1731124281964.png

 

GraphGuy
Meteorite | Level 14

Is there a way to get the lines to start at zero?

hackathon24-white-horiz.png

The 2025 SAS Hackathon Kicks Off on June 11!

Watch the live Hackathon Kickoff to get all the essential information about the SAS Hackathon—including how to join, how to participate, and expert tips for success.

YouTube LinkedIn

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 6 replies
  • 2729 views
  • 16 likes
  • 4 in conversation