-
Notifications
You must be signed in to change notification settings - Fork 1
/
plotting.py
2518 lines (2209 loc) · 83.3 KB
/
plotting.py
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
"""
this module contains functions for plotting the figures and latex tables of the
paper [citation].
the functions of this module write the figures and tables to a user-specified directory.
the figures and tables fall into three categories:
- voter file-only : results relating to predictions made using only voter file information from
voter files with labeled with self-identified race/ethnicity
- subsampled validation : results for validation performed by subsampling voter files
- calibration map validation : results for validation on full voter files using a
calibration map
Functions
---------
self_contained_figures_tables
tables and figures for the voter file only predictions
subsampled_figures_tables
tables and figures for the subsampled validation
calib_map_figures_tables
tables and figures for the calibration map validation
"""
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import fields
import process_census
import process_cps
from raking_bisg import (
make_df_agg,
dist_summary,
subpopulation_preds,
one_calib,
l1_l2_tables,
ll_tables,
load_voter_file,
make_calib_map,
one_calib
)
def main():
dir_out = "/Users/ramin/bisg/writeup/overleaf/"
states = ["nc", "nc", "fl"]
years = [2020, 2010, 2020]
states = ["fl"]
years = [2020]
for state, year in zip(states, years):
print(state, year)
subsampled_figures_tables(state, year, dir_out, load=True)
# calib_map_figures_tables(state, year, dir_out, load=True)
# self_contained_figures_tables(state, year, dir_out, load=True)
def fl_rural_bars(filename, df_agg):
# self-contained voterfile table for rural and urban counties
state = 'fl'
year = 2020
df_cps_reg_voters = process_cps.cps_geo_race(state, year, voters=True)
calib_map = make_calib_map(df_cps_reg_voters, df_agg, verbose=False)
df_state1, df_rural1, df_urban1 = vf_only_rural_tables(df_agg, cols=fields.RAKE_COLS, label='Rake', calib_map=calib_map)
df_state2, df_rural2, df_urban2 = vf_only_rural_tables(df_agg, cols=fields.BISG_BAYES_COLS, label='BISG', calib_map=calib_map)
# bar plot
fig, axs = plt.subplots(2, 3, figsize=(20, 5), gridspec_kw={"height_ratios": [1, 5]})
# x axis label locations
# first plot, mean absolute deviation
labels = fields.PRETTY_PRINT[:5]
xlocs = np.arange(len(labels))
width = 0.35 # the width of the bars
label1 = 'raking'
label2 = 'BISG'
# loop through dataframes with rural/urban/full state errors
df_list = [[df_state1, df_state2], [df_urban1, df_urban2], [df_rural1, df_rural2]]
titles = ['Statewide Average Errors', 'Urban County Average Errors', 'Rural County Average Errors']
for i in range(3):
preds1 = df_list[i][0].loc['Rake'].values[:5]
true_pops1 = df_list[i][0].loc['True'].values[:5]
preds2 = df_list[i][1].loc['BISG'].values[:5]
true_pops2 = df_list[i][1].loc['True'].values[:5]
# compute average errors
avg_errs1 = preds1 / true_pops1 - 1
avg_errs2 = preds2 / true_pops2 - 1
max_err = np.max(np.abs((avg_errs1, avg_errs2)))
# when errors are negligible, still show a slight bar
fac = 0.002
avg_errs1[np.abs(avg_errs1) < max_err * fac] = max_err * fac
avg_errs2[np.abs(avg_errs2) < max_err * fac] = max_err * fac
# add bars to both top and bottom plots (above break and below)
axs[0, i].bar(xlocs - width / 2, avg_errs1, width, label=label1, color="b")
axs[0, i].bar(xlocs + width / 2, avg_errs2, width, label=label2, color="r")
axs[0, i].bar(labels, 0)
axs[1, i].bar(xlocs - width / 2, avg_errs1, width, label=label1, color="b")
axs[1, i].bar(xlocs + width / 2, avg_errs2, width, label=label2, color="r")
axs[1, i].bar(labels, 0)
# zoom-in / limit the view to different portions of the data
axs[0, i].set_ylim(1.8, 2.2) # outliers only
axs[0, i].set_yticks([2.0])
if i == 2:
axs[0, i].set_ylim(2.0, 3.0) # outliers only
axs[0, i].set_yticks([2.5])
axs[1, i].set_ylim(-0.4, 0.5) # most of the data
axs[0, i].xaxis.tick_top()
axs[0, i].tick_params(labeltop=False, top=False) # don't put tick labels at the top
axs[1, i].xaxis.tick_bottom()
axs[1, i].tick_params(left=True, labeltop=False) # don't put tick labels at the top
# set font sizes of axes ticks
axs[1, i].tick_params(axis="x", labelsize=16)
axs[1, i].tick_params(axis="y", labelsize=16)
axs[0, i].tick_params(axis="y", labelsize=16)
# make the cut-out slanted lines to denote the break
d = 0.5 # proportion of vertical to horizontal extent of the slanted line
kwargs = dict(
marker=[(-1, -d), (1, d)],
markersize=12,
linestyle="none",
color="k",
mec="k",
mew=1,
clip_on=False,
)
axs[0, i].plot([0], [0], transform=axs[0, i].transAxes, **kwargs)
axs[1, i].plot([0], [1], transform=axs[1, i].transAxes, **kwargs)
# title and legend
axs[0, i].set_title(titles[i], fontsize=24)
# axs[1, i].legend(fontsize=26, loc="lower left", frameon=False)
# hide the spines between axes above and below break
axs[0, i].spines["bottom"].set_visible(False)
axs[1, i].spines["top"].set_visible(False)
axs[0, i].spines["right"].set_visible(False)
# remove bounding boxes
axs[0, i].spines["top"].set_visible(False)
axs[1, i].spines["right"].set_visible(False)
handles, labels = axs[0, 0].get_legend_handles_labels()
fig.legend(
handles,
labels,
loc="upper center",
fontsize=16,
bbox_to_anchor=(0.5, 1.11),
fancybox=True,
shadow=True,
ncol=2,
)
fig.tight_layout(h_pad=0.5)
# save figure
if filename is not None:
plt.savefig(filename, bbox_inches="tight")
def vf_only_rural_tables(df_agg, cols, label, calib_map=None):
# voter file only BISG for the full state
# cols = fields.VF_BISG
preds_fl, true_pops_fl, true_probs1 = subpopulation_preds(
df_agg, cols, region="region", calib_map=calib_map
)
preds_fl = np.sum(preds_fl, axis=0).astype(int)
true_pops_fl = np.sum(true_pops_fl, axis=0)
preds_fl_pct = preds_fl / preds_fl.sum()
true_pops_fl_pct = true_pops_fl / true_pops_fl.sum()
df_fl = pd.DataFrame(data=np.vstack((preds_fl, true_pops_fl, preds_fl_pct, true_pops_fl_pct,
preds_fl - true_pops_fl, (preds_fl - true_pops_fl) / true_pops_fl)),
columns=fields.PRETTY_PRINT,
index=[label, 'True', f'{label} %', 'True %', 'Error', 'Relative Error'])
# voter file only BISG in rural counties
preds_rural, true_pops_rural, true_probs1 = subpopulation_preds(
df_agg[df_agg['rural']], cols, region="region", calib_map=calib_map
)
preds_rural = np.sum(preds_rural, axis=0).astype(int)
true_pops_rural = np.sum(true_pops_rural, axis=0)
preds_rural_pct = preds_rural / preds_rural.sum()
true_pops_rural_pct = true_pops_rural / true_pops_rural.sum()
df_rural = pd.DataFrame(data=np.vstack((preds_rural, true_pops_rural, preds_rural_pct, true_pops_rural_pct,
preds_rural - true_pops_rural,
(preds_rural - true_pops_rural) / true_pops_rural)),
columns=fields.PRETTY_PRINT,
index=[label, 'True', f'{label} %', 'True %', 'Error', 'Relative Error'])
# voter file only BISG in urban counties
preds_urban, true_pops_urban, true_probs_urban = subpopulation_preds(
df_agg[~df_agg['rural']], cols, region="region", calib_map=calib_map
)
preds_urban = np.sum(preds_urban, axis=0).astype(int)
true_pops_urban = np.sum(true_pops_urban, axis=0)
preds_urban_pct = preds_urban / preds_urban.sum()
true_pops_urban_pct = true_pops_urban / true_pops_urban.sum()
df_urban = pd.DataFrame(data=np.vstack((preds_urban, true_pops_urban, preds_urban_pct, true_pops_urban_pct,
preds_urban - true_pops_urban,
(preds_urban - true_pops_urban) / true_pops_urban)),
columns=fields.PRETTY_PRINT,
index=[label, 'True', f'{label} %', 'True %', 'Error', 'Relative Error'])
return df_fl, df_rural, df_urban
def subsampled_figures_tables(state, year, dir_out, load=False):
"""
make all figures and latex tables for the subsampled validation and save them
in subdirectories of the inputted directory dir_out. if these directories
don't exist, they are created
Parameters
----------
state : string
state
year : integer
year
dir_out : str
home directory of figures and tables
load : bool, optional
load the predictions dataframe df_agg
Returns
-------
None
"""
# directories to save the figures and tables
figures_dir = dir_out + "figures/subsampled/"
tables_dir = dir_out + "tables/subsampled/"
# if the directories don't exist, create them
if not os.path.exists(figures_dir):
os.makedirs(figures_dir)
if not os.path.exists(tables_dir):
os.makedirs(tables_dir)
# load df_agg
df_agg = make_df_agg(state, year, subsample=True, load=load)
# make raking predictions
cols1 = fields.RAKE_COLS
preds1, true_pops1, true_probs1 = subpopulation_preds(
df_agg, cols1, region="county", calib_map=None
)
# make bisg predictions
# cols2 = fields.BISG_CEN_COUNTY_COLS
cols2 = fields.BISG_BAYES_COLS
preds2, true_pops2, true_probs2 = subpopulation_preds(
df_agg, cols2, region="county", calib_map=None
)
# scatterplot
filename = figures_dir + f"{state}{year}_scatters.pdf"
#################### abs_rel_scatters(
# filename, preds1, true_pops1, preds2, true_pops2, label1="raking", label2="BISG"
# )
# abs_rel_scatters2(
# filename, preds1, preds2, true_pops1, label1="raking", label2="BISG"
# )
scatter_and_table(
filename, preds1, preds2, true_pops1, label1="raking", label2="BISG"
)
# barplots, but florida bar plots have an axis break, so they require special functions
if state.lower() == "fl":
filename = figures_dir + f"{state}{year}_bars.pdf"
fl_bar_plots(
filename,
preds1,
true_pops1,
preds2,
true_pops2,
label1="raking",
label2="BISG",
)
filename = figures_dir + f'{state}{year}_rural_bars.pdf'
fl_rural_bars(filename, df_agg)
else:
filename = figures_dir + f"{state}{year}_bars.pdf"
bar_plots(
filename,
preds1,
true_pops1,
preds2,
true_pops2,
label1="raking",
label2="BISG",
)
# write validation table to file
filename_county = tables_dir + f"{state}{year}_validation_table_counties.tex"
filename_region = tables_dir + f"{state}{year}_validation_table_regions.tex"
validation_err_table(
df_agg, filename_county, filename_region, state, calib_map=None
)
# calibration plots
filename = figures_dir + f"{state}{year}_calib_grid.pdf"
cols1 = fields.BISG_BAYES_COLS
cols2 = fields.RAKE_COLS
#################### kstats = calib_plots(filename, df_agg, cols1, cols2, calib_map=None)
kstats = calib_plots2(filename, df_agg, cols1, cols2, calib_map=None)
# calibration table
filename = tables_dir + f"{state}{year}_kuiper.tex"
calib_table(filename, kstats, state, year)
def calib_map_figures_tables(state, year, dir_out, load=False):
"""
make all figures and latex tables for the calibration map validation and save them
in subdirectories of the inputted directory dir_out. if these directories
don't exist, they are created
Parameters
----------
state : string
state
year : integer
year
dir_out : str
home directory of figures and tables
load : bool, optional
load the predictions dataframe df_agg
Returns
-------
None
"""
figures_dir = dir_out + "figures/calib_map/"
tables_dir = dir_out + "tables/calib_map/"
# if the directory to which we're going to write figures and tables
# doesn't exist, then create it
if not os.path.exists(figures_dir):
os.makedirs(figures_dir)
if not os.path.exists(tables_dir):
os.makedirs(tables_dir)
df_cps_reg_voters = process_cps.cps_geo_race(state, year, voters=True)
df_agg = make_df_agg(state, year, subsample=False, load=load)
calib_map = make_calib_map(df_cps_reg_voters, df_agg, verbose=False)
# make raking predictions
cols1 = fields.RAKE_COLS
preds1, true_pops1, true_probs1 = subpopulation_preds(
df_agg, cols1, region="county", calib_map=calib_map
)
# make bisg predictions
cols2 = fields.BISG_BAYES_COLS
preds2, true_pops2, true_probs1 = subpopulation_preds(
df_agg, cols2, region="county", calib_map=calib_map
)
# make voter file predictions
preds1vf, true_pops1vf, _ = subpopulation_preds(
df_agg, fields.VF_BISG, region="county", calib_map=None
)
preds2vf, true_pops2vf, _ = subpopulation_preds(
df_agg, fields.VF_BISG, region="region", calib_map=None
)
# scatter plot
filename = figures_dir + f"{state}{year}_scatters.pdf"
abs_rel_scatters(
filename, preds1, true_pops1, preds2, true_pops2, label1="raking", label2="BISG"
)
# barplot (florida has its own function because there's an axis break)
if state.lower() == "fl":
filename = figures_dir + f"{state}{year}_bars.pdf"
fl_bar_plots(
filename,
preds1,
true_pops1,
preds2,
true_pops2,
label1="raking",
label2="BISG",
)
else:
filename = figures_dir + f"{state}{year}_bars.pdf"
bar_plots(
filename,
preds1,
true_pops1,
preds2,
true_pops2,
label1="raking",
label2="BISG",
)
# write validation table to file
filename_county = tables_dir + f"{state}{year}_validation_table_counties.tex"
filename_region = tables_dir + f"{state}{year}_validation_table_regions.tex"
validation_err_table(df_agg, filename_county, filename_region, state, calib_map)
# calibration plots
filename = figures_dir + f"{state}{year}_calib_grid.pdf"
cols1 = fields.BISG_BAYES_COLS
cols2 = fields.RAKE_COLS
kstats = calib_plots(filename, df_agg, cols1, cols2, calib_map)
# calibration table
filename = tables_dir + f"{state}{year}_kuiper.tex"
calib_table(filename, kstats, state, year)
def self_contained_figures_tables(state, year, dir_out, load=False):
"""
write figures and tables for the paper that involve only the
self-contained and labeled predictions, that is, all of these predictions
involve only the data from labeled voter files. this function will create
directories for saving the figures and tables if they don't exist
Parameters
----------
state : string
one of 'fl', 'nc'
year : int
year, one of 2020 or 2010 for nc and 2020 for fl
dir_out : string
the home directory of the figures and tables
load : bool, optional
load the predictions dataframe df_agg
Returns
-------
None
"""
figures_dir = dir_out + "figures/voter_file_only/"
tables_dir = dir_out + "tables/voter_file_only/"
# if the directory to which we're going to write figures and tables
# doesn't exist, then create it
if not os.path.exists(figures_dir):
os.makedirs(figures_dir)
if not os.path.exists(tables_dir):
os.makedirs(tables_dir)
# load df_agg
df_agg = make_df_agg(state, year, subsample=False, load=load)
# create and write df_summary
df_cen_usa = process_census.usa_census(year)
df_cen_counties = process_census.county_census(state, year)
df_cps_reg_voters = process_cps.cps_geo_race(state, year, voters=True)
df_vf = load_voter_file(state, year, load=load)
df_summary = dist_summary(
state, year, df_cen_usa, df_cen_counties, df_vf, df_cps_reg_voters
)
# make voter file predictions, including only names that appear in the surname list
df_tmp = df_agg[df_agg["in_cen_surs"]]
preds1vf, true_pops1vf, _ = subpopulation_preds(
df_tmp, fields.VF_BISG, region="county", calib_map=None
)
preds2vf, true_pops2vf, _ = subpopulation_preds(
df_tmp, fields.VF_BISG, region="region", calib_map=None
)
# self-contained voterfile table for full state
filename = tables_dir + f"{state}{year}_vf_table_state.tex"
voterfile_state_table(filename, preds1vf, true_pops1vf)
# self-contained voterfile table for rural and urban counties
df_tmp = df_agg[df_agg['in_cen_surs']]
df_state, df_rural, df_urban = vf_only_rural_tables(df_tmp, cols=fields.VF_BISG)
# rural counties
filename = tables_dir + f"{state}{year}_vf_table_rural.tex"
voterfile_state_table(filename, df_rural.loc['BISG', :].values, df_rural.loc['True', :].values)
# urban counties
filename = tables_dir + f"{state}{year}_vf_table_urban.tex"
voterfile_state_table(filename, df_urban.loc['BISG', :].values, df_urban.loc['True', :].values)
# self-contained voter file scatter plots
filename = figures_dir + f"{state}{year}_vf_scatters.pdf"
two_row_comp(
filename=filename,
preds=preds1vf,
true_pops=true_pops1vf,
preds2=preds2vf,
true_pops2=true_pops2vf,
label1="county",
label2="region",
)
# self-contained voter file table for all counties
filename1 = tables_dir + f"{state}{year}_vf_table_counties.tex"
filename2 = tables_dir + f"{state}{year}_vf_table_region.tex"
vf_err_tables(filename1, filename2, df_agg, state)
# summary dataframe
filename = dir_out + f"tables/{state}{year}_summary.tex"
write_df_summary(filename, df_summary)
# calibration plots
filename = figures_dir + f"{state}{year}_calib_grid.pdf"
cols1 = fields.VF_BISG
cols2 = None
kstats = calib_plots(filename, df_agg, cols1, cols2, calib_map=None)
# calibration table
filename = tables_dir + f"{state}{year}_kuiper.tex"
calib_table(filename, kstats, state, year)
def two_row_comp(
filename,
preds,
true_pops,
preds2=None,
true_pops2=None,
label1="BISG",
label2="raking",
c1=None,
c2=None,
):
"""
save a figure with two rows of sactter plots with the absolute error (top row) and relative error (bottom)
of one or two predictions.
Parameters
----------
filename : string
name of file that's written
preds : n x m numpy array
predictions
true_pops : n x m numpy array
the correct totals that preds is trying to predict
preds2 : n x m numpy array, optional
predictions
true_pops2 : n x m numpy array, optional
the correct totals that preds2 is trying to predict
label1 : string, optional
the label in the legend of the first set of predictions
label2 : string, optional
the label in the legend of the second set of predictions
c1 : string, optional
pyplot color of scatter plot dots for first predictions
c2 : strong, optional
pyplot color of scatter plot dots for second predictions
Returns
-------
None
"""
# exclude the "other" category
fig, axs = plt.subplots(2, 5, figsize=(20, 8))
# default colors
if c1 is None:
c1 = "r"
if c2 is None:
c2 = "b"
# compute absolute errors
abs_errs = preds - true_pops
rel_errs = preds / true_pops - 1
true_probs = np.divide(true_pops, np.sum(true_pops, axis=1).reshape((-1, 1)))
if preds2 is not None:
abs_errs2 = preds2 - true_pops2
rel_errs2 = preds2 / true_pops2 - 1
true_probs2 = np.divide(true_pops2, np.sum(true_pops2, axis=1).reshape((-1, 1)))
for i, race in enumerate(fields.RACES[:5]):
# plot a horizontal bar at 0 and make sure the bar extends to the right length
if true_pops2 is not None:
xmin = np.minimum(
np.min(np.log10(true_pops[:, i])), np.min(np.log10(true_pops2[:, i]))
)
xmax = np.maximum(
np.max(np.log10(true_pops[:, i])), np.max(np.log10(true_pops2[:, i]))
)
else:
xmin = np.min(np.min(np.log10(true_pops[:, i])))
xmax = np.max(np.max(np.log10(true_pops[:, i])))
# in rare cases, a subpopulation might contain zero people
if np.isneginf(xmin):
xmin = 0
xs = np.linspace(xmin, xmax, 2)
# size of dots
s = 15
axs[0, i].plot(xs, np.zeros_like(xs), c="black")
axs[0, i].scatter(
np.log10(true_pops[:, i]), abs_errs[:, i], label=label1, c=c1, s=s
)
axs[0, i].set_title(f"{fields.PRETTY_PRINT[i]}", fontsize=24)
axs[0, i].tick_params(axis="x", labelsize=14)
axs[0, i].tick_params(axis="y", labelsize=14)
axs[0, i].yaxis.get_offset_text().set_fontsize(14)
# comparison
if preds2 is not None:
axs[0, i].scatter(
np.log10(true_pops2[:, i]), abs_errs2[:, i], label=label2, c=c2, s=s
)
# formatting
axs[0, i].ticklabel_format(style="sci", axis="both", scilimits=(-2, 2))
axs[1, i].plot(xs, np.zeros_like(xs), c="black")
# scatter plot
axs[1, i].scatter(
np.log10(true_pops[:, i]), rel_errs[:, i], label=label1, c=c1, s=s
)
axs[1, i].tick_params(axis="x", labelsize=14)
axs[1, i].tick_params(axis="y", labelsize=14)
axs[1, i].set_title(f"{fields.PRETTY_PRINT[i]}", fontsize=24)
# comparison
if preds2 is not None:
axs[1, i].scatter(
np.log10(true_pops2[:, i]), rel_errs2[:, i], label=label2, c=c2, s=s
)
axs[0, i].spines["top"].set_visible(False)
axs[0, i].spines["right"].set_visible(False)
axs[1, i].spines["top"].set_visible(False)
axs[1, i].spines["right"].set_visible(False)
# set zero to be the center of the y-axis
for i, race in enumerate(fields.RACES[:5]):
yabs_max = np.max(np.abs(axs[0, i].get_ylim()))
axs[0, i].set_ylim(ymin=-yabs_max, ymax=yabs_max)
yabs_max = np.max(np.abs(axs[1, i].get_ylim()))
axs[1, i].set_ylim(ymin=-yabs_max, ymax=yabs_max)
# one legend for the full plot
handles, labels = axs[0, 0].get_legend_handles_labels()
fig.legend(
handles,
labels,
loc="upper center",
fontsize=24,
bbox_to_anchor=(0.5, 1.15),
fancybox=True,
shadow=True,
ncol=2,
)
fig.text(
0.5, 0.51, "$\\log_{10}$ of population", ha="center", va="center", fontsize=24
)
fig.text(
0.0,
0.75,
"Error",
ha="center",
va="center",
rotation="vertical",
fontsize=22,
)
fig.text(
0.5, -0.02, "$\\log_{10}$ of population", ha="center", va="center", fontsize=24
)
fig.text(
0.0,
0.25,
"Relative error",
ha="center",
va="center",
rotation="vertical",
fontsize=22,
)
fig.tight_layout(h_pad=7)
# save figure
if filename is not None:
plt.savefig(filename, bbox_inches="tight")
def two_row_comp_total_pop(
filename,
preds,
true_pops,
label1="BISG",
c1=None,
):
"""
save a figure with two rows of sactter plots with the absolute error (top row) and relative error (bottom)
of one or two predictions.
Parameters
----------
filename : string
name of file that's written
preds : n x m numpy array
predictions
true_pops : n x m numpy array
the correct totals that preds is trying to predict
label1 : string, optional
the label in the legend of the first set of predictions
c1 : string, optional
pyplot color of scatter plot dots for first predictions
Returns
-------
None
"""
# exclude the "other" category
fig, axs = plt.subplots(2, 5, figsize=(20, 8))
# default colors
if c1 is None:
c1 = "r"
# x axis values
x_axis_vals = np.sum(true_pops, axis=1)
# compute errors
abs_errs = preds - true_pops
rel_errs = preds / true_pops - 1
true_probs = np.divide(true_pops, np.sum(true_pops, axis=1).reshape((-1, 1)))
for i, race in enumerate(fields.RACES[:5]):
# plot a horizontal bar at 0 and make sure the bar extends to the right length
xmin = np.min(np.min(np.log10(true_pops[:, i])))
xmax = np.max(np.max(np.log10(true_pops[:, i])))
xmin = np.min(np.min(np.log10(x_axis_vals)))
xmax = np.max(np.max(np.log10(x_axis_vals)))
# in rare cases, a subpopulation might contain zero people
if np.isneginf(xmin):
xmin = 0
xs = np.linspace(xmin, xmax, 2)
# size of dots
s = 15
axs[0, i].plot(xs, np.zeros_like(xs), c="black")
axs[0, i].scatter(
# np.log10(true_pops[:, i]), abs_errs[:, i], label=label1, c=c1, s=s
np.log10(x_axis_vals), abs_errs[:, i], label=label1, c=c1, s=s
)
axs[0, i].set_title(f"{fields.PRETTY_PRINT[i]}", fontsize=24)
axs[0, i].tick_params(axis="x", labelsize=14)
axs[0, i].tick_params(axis="y", labelsize=14)
axs[0, i].yaxis.get_offset_text().set_fontsize(14)
# formatting
axs[0, i].ticklabel_format(style="sci", axis="both", scilimits=(-2, 2))
axs[1, i].plot(xs, np.zeros_like(xs), c="black")
# scatter plot
axs[1, i].scatter(
# np.log10(true_pops[:, i]), rel_errs[:, i], label=label1, c=c1, s=s
np.log10(x_axis_vals), rel_errs[:, i], label=label1, c=c1, s=s
)
axs[1, i].tick_params(axis="x", labelsize=14)
axs[1, i].tick_params(axis="y", labelsize=14)
axs[1, i].set_title(f"{fields.PRETTY_PRINT[i]}", fontsize=24)
# set zero to be the center of the y-axis
for i, race in enumerate(fields.RACES[:5]):
yabs_max = np.max(np.abs(axs[0, i].get_ylim()))
axs[0, i].set_ylim(ymin=-yabs_max, ymax=yabs_max)
yabs_max = np.max(np.abs(axs[1, i].get_ylim()))
axs[1, i].set_ylim(ymin=-yabs_max, ymax=yabs_max)
# one legend for the full plot
handles, labels = axs[0, 0].get_legend_handles_labels()
fig.legend(
handles,
labels,
loc="upper center",
fontsize=24,
bbox_to_anchor=(0.5, 1.15),
fancybox=True,
shadow=True,
ncol=2,
)
fig.text(
0.5, 0.51, "$\\log_{10}$ of population", ha="center", va="center", fontsize=24
)
fig.text(
0.0,
0.75,
"Error",
ha="center",
va="center",
rotation="vertical",
fontsize=22,
)
fig.text(
0.5, -0.02, "$\\log_{10}$ of population", ha="center", va="center", fontsize=24
)
fig.text(
0.0,
0.25,
"Relative error",
ha="center",
va="center",
rotation="vertical",
fontsize=22,
)
fig.tight_layout(h_pad=7)
# save figure
if filename is not None:
plt.savefig(filename, bbox_inches="tight")
def one_row_pct_group(
filename,
true_pops,
label="BISG",
c1=None,
):
"""
save a figure with two rows of sactter plots with the absolute error (top row) and relative error (bottom)
of one or two predictions.
Parameters
----------
filename : string
name of file that's written
true_pops : n x m numpy array
the correct totals that preds is trying to predict
label1 : string, optional
the label in the legend of the first set of predictions
c1 : string, optional
pyplot color of scatter plot dots for first predictions
Returns
-------
None
"""
# exclude the "other" category
fig, axs = plt.subplots(1, 5, figsize=(20, 4))
# default colors
if c1 is None:
c1 = "r"
# x axis values
x_axis_vals = np.sum(true_pops, axis=1)
pcts = np.divide(true_pops, np.sum(true_pops, axis=1).reshape((-1, 1)))
for i, race in enumerate(fields.RACES[:5]):
# size of dots
s = 15
axs[i].scatter(np.log10(x_axis_vals), pcts[:, i], label=label, c=c1, s=s)
axs[i].set_title(f"{fields.PRETTY_PRINT[i]}", fontsize=24)
axs[i].tick_params(axis="x", labelsize=14)
axs[i].tick_params(axis="y", labelsize=14)
axs[i].yaxis.get_offset_text().set_fontsize(14)
# formatting
# axs[i].ticklabel_format(style="sci", axis="both", scilimits=(-4, 4))
# one legend for the full plot
handles, labels = axs[0].get_legend_handles_labels()
fig.legend(
handles,
labels,
loc="upper center",
fontsize=24,
bbox_to_anchor=(0.5, 1.15),
fancybox=True,
shadow=True,
ncol=2,
)
fig.text(
0.5, -0.02, "$\\log_{10}$ of population", ha="center", va="center", fontsize=24
)
fig.text(
0.0,
0.5,
"% of county population",
ha="center",
va="center",
rotation="vertical",
fontsize=22,
)
fig.tight_layout(h_pad=7)
# save figure
if filename is not None:
plt.savefig(filename, bbox_inches="tight")
def calib_subplots(width, height):
"""
create the axes for the calibration plots with 5 subpopulations, 3 in the first row and 2 in the next
Parameters
----------
width : float
width of the figure
height : float
height of the figure
Returns
-------
pyplot figure
figure with calibration plot grid
list
pyplot axes of calibration plot
"""
fig = plt.figure(layout=None, figsize=(width, height))
gs = fig.add_gridspec(
nrows=2,
ncols=9,
left=0.00,
right=1.0,
bottom=0.0,
top=1.0,
hspace=0.35,
wspace=0.7,
)
ax00 = fig.add_subplot(gs[0, 0:3])
ax01 = fig.add_subplot(gs[0, 3:6])
ax02 = fig.add_subplot(gs[0, 6:9])
ax03 = fig.add_subplot(gs[1, 1:4])
ax04 = fig.add_subplot(gs[1, 5:8])
axs = np.array([ax00, ax01, ax02, ax03, ax04])
return fig, axs
def scatterplot_subplots():
"""
create the axes for the scatter plots with 5 subpopulations and absolute and relative errors.
these subplots will contain 3 scatter plots in the first two rows and two in the next 2.
Parameters
----------
None
Returns
-------
pyplot figure
figure with scatterplots
list
pyplot axs
"""
fig = plt.figure(layout=None, figsize=(20, 18))
gs = fig.add_gridspec(
nrows=4,
ncols=9,
left=0.00,
right=1.0,
bottom=0.0,
top=1.0,
hspace=0.5,
wspace=0.7,
)
ax00 = fig.add_subplot(gs[0, 0:3])
ax01 = fig.add_subplot(gs[0, 3:6])
ax02 = fig.add_subplot(gs[0, 6:9])
ax10 = fig.add_subplot(gs[1, 0:3])
ax11 = fig.add_subplot(gs[1, 3:6])
ax12 = fig.add_subplot(gs[1, 6:9])
ax03 = fig.add_subplot(gs[2, 1:4])
ax04 = fig.add_subplot(gs[2, 5:8])
ax13 = fig.add_subplot(gs[3, 1:4])
ax14 = fig.add_subplot(gs[3, 5:8])
axs = np.array([[ax00, ax01, ax02, ax03, ax04], [ax10, ax11, ax12, ax13, ax14]])
return fig, axs
def abs_rel_scatters2(
filename, preds1, preds2, true_pops, label1="raking", label2="BISG"
):
"""
construct a 4 x 3 grid of scatter plots of subpopulation estimation
for two different predictions. the first 2 x 1 upper left subplots
correspond to one race/ethnicity, the upper scatter plot shows
absolute error and the lower one relative error.
Parameters
----------
filename : string
name of file that's written
preds1 : n x m numpy array
predictions
true_pops1 : n x m numpy array
the correct totals that preds is trying to predict
preds2 : n x m numpy array
predictions
true_pops2 : n x m numpy array
the correct totals that preds2 is trying to predict
label1 : string, optional
the label in the legend of the first set of predictions
label2 : string, optional
the label in the legend of the second set of predictions
Returns
-------
None
"""
alph = 1.0
fig, axs = scatterplot_subplots()
# size of dots in scatter plot
s = 30