-
Notifications
You must be signed in to change notification settings - Fork 0
/
presidential_money.Rmd
1151 lines (798 loc) · 48.7 KB
/
presidential_money.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Dollars for Votes - the US presidential elections"
author: "martin-martin"
date: "29 Februar 2016"
output:
html_document:
toc: true
depth: 4
---
```{r global_options, include=FALSE}
# setting global chunk options to avoid printing r-code, messages and warnings
# left in one line even though more than 80 characters,
# because the source read 'no linebreaks!'
knitr::opts_chunk$set(fig.width=12, fig.height=8, fig.path='graphs/', echo=FALSE, message=FALSE, warning=FALSE)
```
```{r packages}
# loading the packages I use
library(ggplot2)
library(reshape2)
library(plyr)
```
# Introduction
I'm currently spending my time in the USA, and it's (pre-)election time! Having a memebership to a 24h gym gets me exposed to a massive amount of politics on TV while I'm doing my time on the crosstrainer or even when I'm just changing in the dressing room.
It's February, the elections are in November, but there is a near-constant broadcast of candidates battling each other on CNN.
I'm impressed and surprised about this omnipresence of the elections on TV, already so early on. And I'm concerned about the rudeness that these debates often display. Politics in Europe are different. They're not golden, nope. And there are insults and dirty tricks played also there. But here in the US there's a level of "attack", "aggression" and "god" in the talks, that I am thoroughly not used to. :/
One of the times while in the dressing room, I got stuck watching the TV talk about **Dollars per Vote**, and found this comparison very interesting. Some candidates spend very little money as compared to others in absolute, and yet in the end some end up spending still more money _per vote_ received.
Now, my analysis will not deal with this comparison, since the ballots have not been cast yet (for a few months...), but I will make a preliminary analysis of the money that the presidential candidates were receiving from individual contributors in the run-up for the presidency.
---
# Pt. 0: The Data
The data for the 2016 Presidential Campaign Contributions can be found here: http://fec.gov/disclosurep/PDownload.do
Since I am currently in California, I chose and downloaded the dataset for `CA.zip`.
Here's also a peek at the structure of the data that the .csv contains. It's an excerpt from this file: ftp://ftp.fec.gov/FEC/Presidential_Map/2016/DATA_DICTIONARIES/CONTRIBUTOR_FORMAT.txt
I have also indicated which of the columns I ended up dropping.
```{}
The text file is comma delimited and uses double-quotation marks as the text qualifier.
------------------------------------------------------------------------
CMTE_ID COMMITTEE ID S <- dropped
CAND_ID CANDIDATE ID S
CAND_NM CANDIDATE NAME S
CONTBR_NM CONTRIBUTOR NAME S
CONTBR_CITY CONTRIBUTOR CITY S
CONTBR_ST CONTRIBUTOR STATE S <- dropped
CONTBR_ZIP CONTRIBUTOR ZIP CODE S
CONTBR_EMPLOYER CONTRIBUTOR EMPLOYER S
CONTBR_OCCUPATION CONTRIBUTOR OCCUPATION S
CONTB_RECEIPT_AMT CONTRIBUTION RECEIPT AMOUNT N
CONTB_RECEIPT_DT CONTRIBUTION RECEIPT DATE D
RECEIPT_DESC RECEIPT DESCRIPTION S <- dropped
MEMO_CD MEMO CODE S <- dropped
MEMO_TEXT MEMO TEXT S <- dropped
FORM_TP FORM TYPE S <- dropped
FILE_NUM FILE NUMBER N <- dropped
TRAN_ID TRANSACTION ID S <- dropped
ELECTION_TP ELECTION TYPE/PRIMARY GENERAL INDICATOR S <- dropped
Data Type: S = string (alpha or alpha-numeric); D = date; N = numeric
------------------------------------------------------------------------
```
One thing that becomes very obvious here, and that strongly influenced my exploration, is that there is **only one column containing numerical variables**: `contb_receipt_amt`.
This is the column that holds the amounts of the contributions in $, and it is therefore also one of the most interesting columns. A lot of comparisons were anchored to it.
However, there is also another "hidden" numerical value associated with the dataset, and that is the **number of rows**, that allows many graphs to be created in combination with the categorical values of the other columns.
---
## Ideas and Interests that I will explore
- Who got the most contributions? Which person, which party, which gender?
- Which city contributed the most, and to whom (also: in relation to the number of citizens)
- How many "NOT EMPLOYED" people contributed to the campaigns as compared to people with employment; Also: whom did the "NOT EMPLOYED" support the most?
---
# Pt. 1: Mini-Wrangling
In order to be able to load the data, I had to add a comma at the end of the header row in my .csv file.
```{r Load_the_Data}
# Load the Data
setwd('~/Desktop/DAND_P4/p4_US_campaign_funding')
df <- read.csv('P00000001-CA.csv')
#names(df)
```
---
## Adding new columns: cand_gender and cand_party
For some of my questions, I am interested to take a look at the data also depending on the gender and the party affiliation of the different candidates. Since these columns are not present in the dataset, I went to gather the required information online and added it as two new columns to my data.frame `df`.
First I'll be mapping Candidate names to Candidate IDs. This I'll do so that I will be able to refer to a cand_id when passing a function, which is easier than writing out the full name.
```{r Adding_Columns_1}
## PART1 - Mapping
# select only rows that are not duplicates in the cand_id value
candidates <- df[!duplicated(df$cand_id), ]
# define which columns to keep
keeps <- c("cand_id", "cand_nm")
# assigning the new mapping data.frame to a variable
cand_id_map <- candidates[keeps]
#cand_id_map
# how many candidates are in the primaries?
#nrow(cand_id_map)
# I'd also like to have the party associated with the candidate
democrats <- c('P60007168', 'P00003392', 'P60009685', 'P60008885', 'P60007671')
republicans <- c('P60006723', 'P60008521', 'P60008059', 'P60005915',
'P60003670', 'P80001571', 'P60007242', 'P60006111',
'P40003576', 'P20002721', 'P60008398', 'P80003478',
'P60007572', 'P60007697', 'P20003281', 'P60006046')
greens <- c('P20003984')
# double checking
#all_cands <- c(democrats, republicans, greens)
#duplicated(all_cands)
#nrow(cand_id_map) == length(democrats) + length(republicans) + length(greens)
```
Now I can add this new column to the data.frame.
There is one member of the green party 'G', the republicans will get the value 'R' and the democrats the value 'D'
```{r Adding_Columns_2}
## PART2 - Adding the Columns
df$cand_party <- ifelse(df$cand_nm != 'Stein, Jill',
ifelse(df$cand_id %in% republicans, "R", "D"), "G")
#head(subset(df, cand_party == "G"))
# and also the gender of the candidate
female <- c('Fiorina, Carly', 'Clinton, Hillary Rodham', 'Stein, Jill')
# adding a new column to the df
df$cand_gender <- ifelse(df$cand_nm %in% female, "F", "M")
# checking it out
#head(subset(df, cand_nm == 'Fiorina, Carly'))
#names(df)
```
---
## Removing obsolete columns
There is quite a big amount of data that I am not intending to use for my exploration. These include e.g. `conbr_st`, which is in my case always `CA`, or `file_num`, a unique number used to link the transactions to the reports (which I'll also drop).
```{r Removing_Columns}
discard <- c('cmte_id', 'contbr_st', 'receipt_desc', 'memo_cd',
'memo_text', 'form_tp', 'file_num', 'election_tp', 'X')
df <- df[ , !(names(df) %in% discard)]
#names(df)
```
---
# Pt. 2: Exploration
After having cleaned and adapted the dataset to my wishes, I can start into my exploration.
For example, I can query how many individual contributions did each candidate receive, e.g. Hillary Clinton:
```{r First_Steps}
# E.g. for Hillary Clinton:
sum(df$cand_id == 'P00003392')
```
---
## QUESTION 1: _Who got the most money through contributions?_
In this section I'll take a look at money and amounts. I'm wondering which candidate got **the most contributions**, and is it the same person who got **the most money** through contributions? How is the size of the contributions distributed in regards to the candidates?
Which gender received more contributions, or more money? Which political party?
---
### PART 1: the mean and distributions
```{r Exploring_Most_Money_1_1}
# calculating the mean of the contributions for each candidate
mean_contrib_per_cand <- aggregate(contb_receipt_amt ~ cand_nm,
data = df, mean)
# adding a count of contributions
mean_contrib_per_cand$count <- table(df$cand_nm)
#mean_contrib_per_cand
# cool graph showing the distributions!
ggplot(df, aes(cand_nm, contb_receipt_amt)) +
geom_boxplot() +
theme(axis.text.x = element_text(angle = 90))
```
Constructing a frequency plot makes me see something about _Sanders, Bernard_ (who has a big dot low down). Some candidates have a small distribution, and some a wider one, there is another person with a big dot at the bottom, yet also a quite big one higher up (_Clinton, Hillary_); and further one person with a very high distribution up and down, but also a strong base it seems (_Cruz, Ted_). Also _Carson, Benjamin_ shows a large number of contributions in the lower amounts.
```{r Exploring_Most_Money_1_x_add_on}
# thinking about binning data and about displaying statistical values in graphs
# thanks: https://discussions.udacity.com/t/plotting-statistical-overlays/167266/2
df.mean <- aggregate(df['contb_receipt_amt'], df['cand_nm'], mean)
df.median <- aggregate(df['contb_receipt_amt'], df['cand_nm'], median)
# median line plot on mean bar chart
ggplot(df.mean, aes(cand_nm, contb_receipt_amt)) +
geom_bar(stat = 'identity', fill='lightblue') +
ggtitle('median point plot on mean bar chart') +
labs(x = 'candidate',
y = '(mean) contribution $') +
theme(axis.text.x = element_text(angle = 90)) +
geom_point(data = df.median,
aes(x=cand_nm, y=contb_receipt_amt, group=1),
size=1, color="orange")
# mean line plot on median bar chart
ggplot(df.median, aes(cand_nm, contb_receipt_amt)) +
geom_bar(stat = 'identity', fill='orange') +
ggtitle('mean point plot on median bar chart') +
labs(x = 'candidate',
y = '(median) contribution $') +
theme(axis.text.x = element_text(angle = 90)) +
geom_point(data = df.mean,
aes(x=cand_nm, y=contb_receipt_amt, group=1),
size=1, color="lightblue")
```
This is a try experimenting with visualizing statistical variables, such as the mean or the median, on top of the data.
I chose to display the mean and the median contribution for each candidate in relation to each other.
```{r Exploring_Most_Money_1_2}
ggplot(df, aes(contb_receipt_amt, cand_nm)) +
geom_count()
# this graph could be interesting
ggplot(mean_contrib_per_cand, aes(cand_nm, contb_receipt_amt)) +
geom_density() +
geom_label(aes(label=cand_nm)) +
theme(axis.text.x = element_blank())
```
Cleaned up the graph a bit and reordered ascending! This plot gives a nice overview of the mean contributions per candidate! Maybe it's a keeper ; )
```{r Exploring_Most_Money_1_3}
########################## TAKE THIS ONE ##########################
ggplot(mean_contrib_per_cand,
aes(reorder(cand_nm, -contb_receipt_amt), contb_receipt_amt)) +
geom_density() +
coord_flip()
# label is also a cool way to do it, but better this!
# TODO: plot mean amount of contribution vs. number of contributions
# TODO: add the median amount as a line plot?
```
---
### PART 2: amounts
Most of the contributions are below 1000 $!
```{r Exploring_Most_Money_2_1}
ggplot(df, aes(contb_receipt_amt)) +
geom_freqpoly()
# sum all receipt amounts, aggregating rows based on candidate name
money_by_cand <- aggregate(contb_receipt_amt ~ cand_nm, data = df, sum)
# now I can make a graph, maybe interesting with color and alpha
ggplot(aes(x = contb_receipt_amt, y = cand_nm, alpha=0.1, color=cand_nm),
data = df) +
geom_jitter() +
scale_x_continuous() +
# removing the legends for better visibility
guides(color=FALSE, alpha=FALSE)
```
---
#### PART 2.1: refunds
The previous graph gives me negative values for amounts, which is at first very confusing. So I construct a vector holding only the **refunds**.
```{r Exploring_Most_Money_2_2}
neg_contb_amt <- subset(df, contb_receipt_amt < 0)
#head(neg_contb_amt)
only_refunds <- subset(df, contb_receipt_amt < 0)
# sum all receipt amounts, aggregating rows based on candidate name
refunds_by_contb <- aggregate(contb_receipt_amt ~ contbr_nm,
data = only_refunds, sum)
#head(refunds_by_contb)
nrow(refunds_by_contb)
```
Seems there are nearly 1500 "contributors" who actually got more money refunded than what they gave.
And some gave some, but also got some back (or got some back multiple times?):
```{r Exploring_Most_Money_2_3}
nrow(only_refunds)
```
So I tried a plot for these refunds (which was too big, so I'll take a look at the most Dollars)
```{r Exploring_Most_Money_2_4}
# a plot containing the highest refunded people
ggplot(subset(refunds_by_contb, contb_receipt_amt < -10000),
aes(contb_receipt_amt, contbr_nm)) +
geom_point()
```
This is a lot of money to get back. I wonder why and how. But I must admit I don't really understand these US politics and fundings of the candidates
Here's some info: https://ballotpedia.org/California_Proposition_34,_Limits_on_Campaign_Contributions_(2000)
---
#### PART 2.2: contributions
Well, so let's see who *gave* the most:
```{r Exploring_Most_Money_2_5}
only_contribs <- subset(df, contb_receipt_amt > 0)
ggplot(subset(only_contribs, contb_receipt_amt > 10000),
aes(contb_receipt_amt, contbr_nm)) +
geom_point()
top_givers <- subset(only_contribs, contb_receipt_amt > 10000)
nrow(top_givers)
```
There are 24 people that all gave the same amount, so I suspect that there is an upper limit around 10.000$ (maybe without taxes, or such? They should be alread PACs?)
I also spotted potentially erroneous data, with the contributor `DE GROOTE, DOUG MR.` being listed, as well as a `DE GROOTE, DOUG`, both with the same amount, which makes me believe that it is a mistake in the data (or a rather badly executed way of increasing one's contribution limit...)
Maybe can check :)
```{r Exploring_Most_Money_2_6}
#top_givers
duplicated(top_givers$tran_id)
```
Yep, seems that some of those transactions are listed more often in the dataset.
Actually quite a lot of them! 7 `TRUE`!
```{r Exploring_Most_Money_2_7}
dup_givers <- subset(top_givers, duplicated(top_givers$tran_id) == TRUE)
#dup_givers
```
It seems that `DE GROOTE` could be also a company, because it's listed also among the `contbr_employer` column.
Well. But I'm not gonna go hunt down these individuals :)
---
### PART 3: gender and money
Number of contributions per gender of candidate
```{r Exploring_Most_Money_3_1}
ggplot(df, aes(cand_gender)) + geom_bar() + scale_x_discrete()
```
Total amount of money through contributions per gender of candidate
```{r Exploring_Most_Money_3_2}
gender_money <- aggregate(contb_receipt_amt ~ cand_gender, data = df, sum)
#head(gender_money)
ggplot(gender_money, aes(cand_gender, contb_receipt_amt)) +
geom_bar(stat='identity', fill = c('pink', 'lightblue')) + scale_x_discrete()
```
Whoa! seems that females received nearly as much money in contributions as males did, even though there are only 3 female vs. 19 male candidates + there were way less fewer contributions to femal candidates than to male candidates!
---
#### PART 3.1: binning
It could be interesting to take a look at the mean contribution per F/M candidate.
So here are the summaries for the contributions for the *female candidates*, then for the *male candidates*, and finally for the whole dataset combined:
```{r Exploring_Most_Money_3_3}
summary(subset(df, cand_gender == 'F')$contb_receipt_amt)
summary(subset(df, cand_gender == 'M')$contb_receipt_amt)
summary(df$contb_receipt_amt)
# min = -10000 and max = 10800
```
I'll start with a generous binwidth of 1000:
```{r Exploring_Most_Money_3_4}
# making bins for all the money
df$money_bin <- cut(df$contb_receipt_amt, breaks = seq(0, 11000, by = 1000))
#head(df)
# we can make this look nicer using a function:
MoneyCategories <- function(x, lower = 0, upper, by = 1000,
sep = "-", above.char = "+") {
# Orders numerical entries of a column into an array of categorical bins.
#
# Args:
# x: a numerical vector of a data.frame to be binned
# lower: the lower binwidth limit; set to 0
# upper: the upper binwidth limit
# by: the size of one bin; set to 1000
#
#
# Returns:
# the rows of column x with it's entries binned categorically.
labs <- c(paste(seq(lower, upper - by, by = by),
seq(lower + by - 1, upper - 1, by = by),
sep = sep),
paste(upper, above.char, sep = ""))
cut(floor(x), breaks = c(seq(lower, upper, by = by), Inf),
right = FALSE, labels = labs)
}
# and assign the values with the prettified labels to the new colum
df$money_bin <- MoneyCategories(df$contb_receipt_amt, upper = 11000)
#head(df)
# looks better now :)
ggplot(df, aes(money_bin)) +
geom_bar(stat = 'count') +
theme(axis.text.x = element_text(angle = 45))
```
This graphic is pretty useless - nearly every contribution falls within the first bin, there are very few that are above 1000. So i can adjust the binnning:
```{r Exploring_Most_Money_3_5}
df$money_bin <- cut(df$contb_receipt_amt,
breaks = c(0, 100, 200, 300, 400, 500, 600, 700,
800, 900, 1000, 2000, 3000, 11000))
#head(df)
ggplot(df, aes(money_bin)) + geom_bar(stat = 'count')
```
Whoa! Most contributions are actually between 0-100$!! So there are many many small contributions that were made in CA. Let's look at this data in a *table*:
```{r Exploring_Most_Money_3_6}
table(df$money_bin)
```
Interesting, because I already saw that most low contributions went to one candidate: Sanders, Bernard.
---
#### PART 3.2: proportions
I'll go forward displaying proportions of female/male candidates in the respective parties
```{r Exploring_Most_Money_3_7}
ggplot(df, aes(x = cand_gender, y = cand_party)) +
geom_count(aes(size = ..prop.., group = cand_party)) +
scale_size_area(max_size = 30)
```
The proportions on how many candidates of the respective gender are running in the presidential elections is very different between the three parties.
Let's see a graph plotting the statistical percentage of money per candidate per gender
```{r Exploring_Most_Money_3_8}
gender_money$gen_mon_perc <- ifelse(gender_money$cand_gender == 'F',
gender_money$contb_receipt_amt / 3,
gender_money$contb_receipt_amt / 19)
#gender_money
ggplot(gender_money, aes(cand_gender, contb_receipt_amt)) +
scale_x_discrete() +
geom_bar(stat='identity', alpha=0.5) +
geom_bar(aes(cand_gender, gen_mon_perc), stat='identity',
fill=c('pink', 'lightblue'), alpha=0.5)
```
But of course that's **VERY** misleading!... _Clinton, Hillary_ got so much of the amounts contributed to female candidates, that we should make this more clear:
```{r Exploring_Most_Money_3_9}
gender_cand_money <- aggregate(contb_receipt_amt ~ cand_gender + cand_nm,
data = df, sum)
#gender_cand_money
ggplot(gender_cand_money) + scale_x_discrete() +
geom_bar(aes(cand_gender, contb_receipt_amt, fill=cand_nm),
stat='identity', alpha=0.8)
```
As we can see, _Hillary Clinton_ received by far the largest amount of money through contributions. She nearly single-handedly takes half of all the contributions made.
---
### PART 4: party money
I can also see, that Clinton and Sanders make the two biggest single sections, and they are both with the Democrats. Therefore it would be interesting to plot money per party instead of by gender.
```{r Exploring_Most_Money_4_1}
########################## TAKE THIS ONE ##########################
party_cand_money <- aggregate(contb_receipt_amt ~ cand_party + cand_nm,
data = df, sum)
ggplot(party_cand_money) + scale_x_discrete() +
geom_bar(aes(cand_party, contb_receipt_amt, fill=cand_nm),
stat='identity', alpha=0.8)
```
Here we can see that the Democrats received way more money through contributitons than the Republicans did, and that Hillary Clinton alone received more money than all the Republican candidates combined.
Whereas the contributions to the green party are so tiny, that they become invisible in this visualization.
---
### PART 5: candidate money
Number of contributions per candidate:
```{r Exploring_Most_Money_5_1}
ggplot(data = subset(df, table(df$cand_nm) > 500), aes(cand_nm)) +
geom_bar() +
theme(axis.text.x = element_text(angle = 90))
# how many contributions per candidate
table(df$cand_nm)
ggplot(df, aes(contb_receipt_amt)) +
geom_histogram() +
facet_wrap(~cand_nm)
```
While most are vanishingly small in comparison, four candidates stick out in terms of number of contributions.
Let's look at the money amassed through the contributions:
```{r Exploring_Most_Money_5_3}
ggplot(df, aes(sum(contb_receipt_amt))) +
geom_histogram() +
facet_wrap(~cand_nm) +
theme(axis.text.x = element_text(angle = 45))
```
These plots are not very interesting and don't tell me too much new, so enough of this topic for now.
---
## QUESTION 2: _Which city contributed the most, and to whom?_
```{r Exploring_Cities_1}
ggplot(df, aes(contb_receipt_amt, contbr_city)) + scale_y_discrete() +
geom_bin2d()
```
The next one is actually quite interesting, because it shows how people often give full-number-amounts of money (with the distinct lines going vertical).
```{r Exploring_Cities_2}
ggplot(df, aes(contb_receipt_amt, contbr_city)) + scale_y_discrete() +
geom_count()
```
Here i'll apply `geom_jitter()` only to the actual **contributions**, leaving out the refunds.
It nicely shows how much do most people donate (first big bar to the right of 0), about which cities had the most contributions (horizontal black lines), and where are there common discrete jumps, maybe related to regulations such as donation limits (vertical lines).
This is a nice graph :)
```{r Exploring_Cities_3}
########################## TAKE THIS ONE ##########################
# jitter does a similar thing as geom_point (or geom_count)
# setting an `alpha` to better see the density of the distribution
ggplot(only_contribs, aes(contb_receipt_amt, contbr_city)) +
scale_y_discrete() +
geom_jitter(alpha=0.1) +
# removing the ticks & text of the y axis, because there are too many to show
theme(axis.ticks.y = element_blank(), axis.text.y = element_blank())
# TODO: clean it up, remove cities (keep only the ones that gave the most
# money in total), research regarding contribution limits; maybe color dots
# regarding which party was donated to
all_cities <- aggregate(contb_receipt_amt ~ contbr_city, data=only_contribs,
sum)
rich_cities <- subset(all_cities, contb_receipt_amt > 150000)
#nrow(rich_cities)
#head(rich_cities)
```
Trying to remove cities and keep only the onese with high contribution amounts:
```{r Exploring_Cities_4}
ggplot(rich_cities, aes(contb_receipt_amt, contbr_city)) + scale_y_discrete() +
geom_point()
```
Hm... this is not so interesting, so maybe I should rather right away put it in relation with the number of inhabitants.
---
### Getting Population estimates for CA
I found some here: https://www.census.gov/popest/data/cities/totals/2012/SUB-EST2012.html
The data is for 2012, but it's the most current one that is listing *cities* that I could find there.
It's not perfect, but for now I just want to take a look :)
```{r Exploring_Cities_5}
pop_df <- read.csv('population_CA_2012.csv')
#names(pop_df)
#head(pop_df)
# i'm only gonna take the column 'NAME' and the latest estimate
pop_df <- pop_df[, c('NAME', 'POPESTIMATE2012')]
#pop_df
# removing the last word ('city') from the city names (see Resources)
# ^ yay to stackoverflow! and the internet in general! :)
pop_df$NAME <- sub(pop_df$NAME, pattern = " [[:alpha:]]*$", replacement = "")
# converting the strings in the column to uppercase
# to match how they are stored in the other df
pop_df$NAME <- toupper(pop_df$NAME)
# merge the two data.frames by the city-name columns
only_contribs <- merge(only_contribs, pop_df,
by.x = 'contbr_city', by.y = 'NAME')
#head(only_contribs)
ggplot(only_contribs, aes(POPESTIMATE2012, contb_receipt_amt)) + geom_bin2d()
```
Could be interesting to display this with a `facet_wrap()`. However, there are too many cities. So i should maybe try this instead:
1. calculating the ratios for contributions/inhabitant
2. subsetting into categories of lower quartile, mean, upper quartile
3. showing one plot for maybe the mean of each group
```{r Exploring_Cities_6}
### this would be a nice multivariate analysis... just gotta manage it!
# geom_count could be interesting, but it's simply too many cities.
#ggplot(only_contribs, aes(POPESTIMATE2012, contb_receipt_amt)) +
# geom_count() +
# facet_wrap(~ contbr_city)
```
---
### Calculating the Ratios
```{r Exploring_Cities_7}
# calculating total amount of contributions per city
total_contribs <- aggregate(data=only_contribs,
contb_receipt_amt ~ contbr_city, sum)
# merging with population estimate for cities
total_contribs <- merge(total_contribs, pop_df,
by.x = 'contbr_city', by.y = 'NAME')
# removing duplicates
total_contribs <- total_contribs[!duplicated(total_contribs), ]
# calculating number of contributions per city
freq_contbs_city <- count(only_contribs, 'contbr_city')
# adding to total_contribs dataframe
total_contribs <- merge(total_contribs, freq_contbs_city, 'contbr_city')
# renaming the frequency column for clarity
total_contribs <- rename(total_contribs, c('freq' = 'number_of_contb'))
head(total_contribs)
```
Oops, there is also data for "counties" in here, that have now the same name as some of the cities... so I'll have to remove the rows with the higher values for capita.
```{r Exploring_Cities_8}
# removing the counties (the row entries with the higher population estimates)
# Resource: http://stackoverflow.com/questions/25962909/remove-duplicates-based-on-2nd-column-condition
total_contribs <- total_contribs[with(
total_contribs, ave(POPESTIMATE2012, contbr_city, FUN=min) == POPESTIMATE2012
), ]
head(total_contribs)
# TODO: plot the relations in a meaningful graph (or graphs!)
```
That's better :)
Here comes a bit more playing around while extracting the cities with the most contributions, and trying to use `melt()`.
```{r Exploring_Cities_9}
# vector with count of occurences
city_contb_count <- table(df$contbr_city)
#head(city_contb_count)
# trying a graph after using melt()
m <- melt(city_contb_count)
#head(m)
# this is not such a bad plot maybe...
ggplot(m, aes(Var1, value)) + scale_x_discrete() +
geom_point() +
theme(axis.ticks.x = element_blank(), axis.text.x = element_blank()) +
labs(x = 'cities', y = '# of contributions')
```
I'm looking to narrow down to find the cities with the most contributions. Trying different values, I found that using `30000` limits the amount of cities to
```{r Exploring_Cities_10}
length(names(city_contb_count[city_contb_count > 3000]))
five_cities <- names(city_contb_count[city_contb_count > 3000])
five_cities
```
which is something I can work with! :)
Here's an interesting little fact:
more than half the number of contributions come from only 5 cities! Percentage:
```{r Exploring_Cities_11}
# creating a df that contains only contributions made in the 5 cities
# with more than 30 000 contributions
most_contribs <- subset(only_contribs,
only_contribs$contbr_city %in% five_cities)
# calculating the percentage of contributions made
# in the 5 most-contribution-cities
nrow(most_contribs) / nrow(df) * 100
```
Well... but somehow I'm more of a country-boy myself. For now I have enough of these cities, so I'll now move forward to investigate another question. :)
---
## QUESTION 3: _How much and to whom did `NOT EMPLOYED` give_
I am very perplexed and involved with the topic of homeless people in the US, so anything that goes into that direction rings a bell with me.
Here I'm trying to investigate a little bit into the political direction that homeless might be having a tendency for.
However, I understand that this is highly hypothetical, because I only have data of **monetary contributions**, that **"NOT EMPLOYED"** people gave for the presidential campaigns.
Of course giving money != political orientation (It might be a good proxy, however what I'm trying to say is, that it's not an exhaustive factor. Many people might have a political orientation, however did not contribute to the campaigns monetarily. This might be especially true for homeless people, who are very likely to have very little money at their hands).
Further, NOT EMPLOYED != homeless. There are quite a few people that are employed, but homeless in the US. Assuming that they would give a contribution, they would fall into a different category. It is also true that NOT EMPLOYED could be people that are currently simply not working in the official job market. Stay-at-home mums and dads would qualify for this section of society, and they might make up a rather larger number of contributors. These factors have to be considered when looking at the results further down.
The following graphs are not gonna show much about how much money was flowing, but rather is intended as a proxy on where does a certain section of society lean towards politically.
```{r Exploring_Unemployment_1}
# adding a column containing a pseudo-boolean gleaned from the employment data
df$contb_emp_status <- ifelse(df$contbr_occupation == 'NOT EMPLOYED',
'not employed', 'employed')
#head(df)
# aggregating the amounts of money for each of the two groups
empl_money <- aggregate(contb_receipt_amt ~ contb_emp_status, data=df, sum)
```
Who gave how much?
```{r Exploring_Unemployment_2}
ggplot(empl_money, aes(contb_emp_status, contb_receipt_amt)) +
scale_x_discrete() +
geom_bar(fill=c('gray', 'lightblue'), stat = 'identity')
```
Okay, this is not so exciting :)
Wait...
```{r Exploring_Unemployment_3}
table(df$contb_emp_status)
```
There are very few `NOT EMPLOYED` compared to those with employment, so I'll need ratios
Displaying proportions of which party did people with/without employment give contributions to:
```{r Exploring_Unemployment_4}
d <- ggplot(df, aes(x = contb_emp_status, y = cand_party))
d + geom_count(aes(size = ..prop.., group = cand_party, color=cand_party)) +
# increasing the max_size to see the proportions better
scale_size_area(max_size = 80)
```
Interesting: it seems that a much higher percentage of people without employment contribute to the Democrats.
**NOTE:** I boosted the `max_size` variable, in order to make it more clear how vanishingly small is the percentage of `NOT EMPLOYED` people that contributed to the Republican party.
---
So, let's see **for whom**...
```{r Exploring_Unemployment_5}
########################## TAKE THIS ONE ##########################
d <- ggplot(df, aes(x = contb_emp_status, y = cand_nm))
d + geom_count(aes(size = ..prop.., group = cand_party, color=cand_party)) +
scale_size_area(max_size = 10)
```
Sanders, Bernard gets percentage-wise the most contributions from the `NOT EMPLOYED`!
And it seems that apart from Trump, Donald J. there is no Republican currently left in the ballots who got contributions by `NOT EMPLOYED` people.
When increasing the `max_size` also here it becomes even more clear how great the difference between Sanders, Bernard and the other candidates is in this aspect.
**NOTE:** `NOT EMPLOYED` probably also includes **college students**! Which makes sense because Sanders wants to take away college debt, so he has a big bunch of the students on his side (I heard of approximately 80% somewhere).
Let's look at this in another way:
```{r Exploring_Unemployment_6}
ggplot(subset(df, contb_emp_status == 'not employed'),
aes(contb_emp_status, fill=cand_nm)) + scale_x_discrete() +
geom_bar()
```
This sounds like a pie chart, haha, also with the implications of _who gets the biggest piece_ :)
---
Thinking about occupation-voter distribution, now I'm wondering which party do IT people lean towards. :)
So I was collecting all the unique jobs present in the data.frame.
```{r Exploring_Unemployment_7}
jobs <- unique(df$contbr_occupation)
#jobs
length(jobs)
```
Haha, found one row listing with `contb_occupation` : `GRANDPA !!` :)
But well, these are too many, and seems that people just put what they wanted. It hasn't been scanned through and grouped it seems.
I don't want to get into this. So let's rather wrap it up :)
---
# Pt. 3: Discussion of the Analysis
## Structure of the dataset
The dataset consists mainly of categorical variables, such as `cand_nm`, `contbr_occupation` or `contbr_zip`. All these are interesting to put in context with the one continuous variable `cont_receipt_amt`, and of course the **amount of rows**.
A more thorough overview of the data can be taken from the official site:
[ftp://ftp.fec.gov/FEC/Presidential_Map/2016/DATA_DICTIONARIES/CONTRIBUTOR_FORMAT.txt](ftp://ftp.fec.gov/FEC/Presidential_Map/2016/DATA_DICTIONARIES/CONTRIBUTOR_FORMAT.txt)
## Main feature(s) of interest in the dataset
How is the number of individual contributions and the amount of money gained through them spread out among the different candidates.
In further abstraction it is interesting to look at the same with aggregating or subsetting the dataset (e.g. by gender of the candidate, or by origin city of the contributor).
## Other features that help to support the investigation into the features of interest
I found it interesting to add the population count of the cities in CA, to be able to calculate a ratio regarding how many contributions and how much money in total, respectively, was given by city in relations to the number of inhabitants.
## New variables created (indirectly) from existing variables
I created some new columns containing new variables:
- **cand_gender**, defining the gender of the presidential candidate (`'F'` for "female" and `'M'` for "male")
- **cand_party**, defining the party affiliation of the candidate (`'D'` for "Democrats", `'R'` for "Republicans", and `'G'` for "Greens")
- **POPESTIMATE2012**, containing the population estimates of the CA cities for 2012, taken from a different governmental source online
- **contb_emp_status**, where I reduced the `contbr_occupation` to show only whether a contributor was employed or not
## Strongest relationship discovered
In my opinion the strongest relationship that I kept discovering over different plots, was that the **number of contributions received**, was very clearly "won" by **one candidate**: _Sanders, Bernard_.
------
# Pt. 4: Final Plots and Summary
## Plot One
```{r Plot_One}
#cand_id_map
still_cand = c('P60007168', 'P60006723', 'P60005915', 'P00003392',
'P60003670', 'P80001571', 'P60006111')
# update the cand_id_map to current candidates
c_cand_id_map <- subset(cand_id_map, cand_id %in% still_cand)
# limit the dataset to contributions associated with current candidates
current_cands <- subset(df, df$cand_id %in% c_cand_id_map$cand_id)
# sum the contributions (including substracting the refunds)
c_party_cand_money <- aggregate(contb_receipt_amt ~ cand_party + cand_nm,
data = current_cands, sum)
# rearrange factors for visualization
c_party_cand_money$cand_nm_ord <- factor(c_party_cand_money$cand_nm,
levels=c("Sanders, Bernard",
"Clinton, Hillary Rodham",
"Trump, Donald J.",
"Rubio, Marco",
"Kasich, John R.",
"Cruz, Rafael Edward 'Ted'",
"Carson, Benjamin S."))
# I'll employ a function to display the amounts more accessible.
# Resource: http://stackoverflow.com/questions/11610377/how-do-i-change-the-formatting-of-numbers-on-an-axis-with-ggplot
fancy_scientific <- function(l) {
# Formats a number in the following way "#*10^#"
#
# Args:
# l: eventually the label text
#
# Returns:
# the number as the formatted label as an expression
#
l <- format(l, scientific = TRUE)
# quote the part before the exponent to keep all the digits
l <- gsub("^(.*)e", "'\\1'e", l)
# turn the 'e+' into plotmath format
l <- gsub("e", "%*%10^", l)
# return this as an expression
parse(text=l)
}
# plot the graph
ggplot(c_party_cand_money,
aes(cand_party, contb_receipt_amt, fill=cand_nm_ord)) +
scale_x_discrete(labels=c('D' = 'Democrats', 'R' = 'Republicans')) +
scale_y_continuous(labels=fancy_scientific) +
geom_bar(stat='identity', alpha=0.8) +
ggtitle('Individual Contributions to the 2016 Presidential Elections') +
theme(plot.title = element_text(size = 25)) +
labs(x = 'Political Party', y = 'Amount in USD') +
guides(fill=guide_legend(title="Candidates"))
```
## Description One
In this graph displays how much money did each party and each candidate receive through individual contributions for the presidential elections in 2016.
It shows values only for those (main) candidates that are currently still running for the presidency in the primaries (as of 2016-03-02 and from [here]( http://www.theatlantic.com/politics/archive/2016/03/2016-election/384828/)).
We can see the absolute amounts of money in USD that each of the two major political parties in the US received through individual contributions.
It is immediately obvious, that the **democratic party** obtained more than twice the amount of contributions than the **republican party** managed to lucrate.
The contributions are further subdivided to display the amounts that each individual candidate received.
Here **Hillary Clinton** sticks out with an amazingly big sum of contribution-money received. She alone got more Dollars than all the other candidates combined.
---
## Plot Two
```{r fig.height=16, Plot_Two}
# adapting the global fig.height knitr-property to make the graph more readable