forked from michaelstepner/binscatter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binscatter.ado
1287 lines (1017 loc) · 39.1 KB
/
binscatter.ado
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
*!forked version 1.01 23jan2020 Dylan Balla-Elliott, dballaelliott@hbs.edu
*!forked from: version 7.02 24nov2013 Michael Stepner, stepner@mit.edu
/* CC0 license information:
To the extent possible under law, the author has dedicated all copyright and related and neighboring rights
to this software to the public domain worldwide. This software is distributed without any warranty.
This code is licensed under the CC0 1.0 Universal license. The full legal text as well as a
human-readable summary can be accessed at http://creativecommons.org/publicdomain/zero/1.0/
*/
* Why did I include a formal license? Jeff Atwood gives good reasons: http://www.codinghorror.com/blog/2007/04/pick-a-license-any-license.html
program define binscatter, eclass sortpreserve
version 12.1
syntax varlist(min=2 numeric) [if] [in] [aweight fweight], [by(varname) ///
Nquantiles(integer 20) GENxq(name) discrete xq(varname numeric) MEDians ///
CONTROLs(varlist numeric ts fv) absorb(varname) noAddmean ///
LINEtype(string) rd(numlist ascending) reportreg ///
COLors(string) MColors(string) LColors(string) Msymbols(string) ///
savegraph(string) savedata(string) replace ///
nofastxtile randvar(varname numeric) randcut(real 1) randn(integer -1) ///
/* LEGACY OPTIONS */ nbins(integer 20) create_xq x_q(varname numeric) ///
symbols(string) method(string) unique(string) ci(string asis) vce(passthru) ///
*]
set more off
// local env_seed = c(seed)
local bin_seed = 20021380
** parse CI options
local model_ci = strpos(`"`ci'"',"model") > 0
local bin_ci = strpos(`"`ci'"',"bins") > 0
local ci_input :subinstr local ci "model" ""
local ci_input :subinstr local ci_input "bins" ""
if "`ci_input'" == ""{
/* do nothing */
/*need to check this so it doesn't try to trim an empty string */
}
else if trim("`ci_input'") != ""{
di as error "`=trim(`ci_input')' not valid option for " as input "ci"
}
** Create convenient weight local
if ("`weight'"!="") local wt [`weight'`exp']
***** Begin legacy option compatibility code
if (`nbins'!=20) {
if (`nquantiles'!=20) {
di as error "Cannot specify both nquantiles() and nbins(): both are the same option, nbins is supported only for backward compatibility."
exit
}
di as text "NOTE: legacy option nbins() has been renamed nquantiles(), and is supported only for backward compatibility."
local nquantiles=`nbins'
}
if ("`create_xq'"!="") {
if ("`genxq'"!="") {
di as error "Cannot specify both genxq() and create_xq: both are the same option, create_xq is supported only for backward compatibility."
exit
}
di as text "NOTE: legacy option create_xq has been renamed genxq(), and is supported only for backward compatibility."
local genxq="q_"+word("`varlist'",-1)
}
if ("`x_q'"!="") {
if ("`xq'"!="") {
di as error "Cannot specify both xq() and x_q(): both are the same option, x_q() is supported only for backward compatibility."
exit
}
di as text "NOTE: legacy option x_q() has been renamed xq(), and is supported only for backward compatibility."
local xq `x_q'
}
if ("`symbols'"!="") {
if ("`msymbols'"!="") {
di as error "Cannot specify both msymbols() and symbols(): both are the same option, symbols() is supported only for backward compatibility."
exit
}
di as text "NOTE: legacy option symbols() has been renamed msymbols(), and is supported only for backward compatibility."
local msymbols `symbols'
}
if ("`linetype'"=="noline") {
di as text "NOTE: legacy line type 'noline' has been renamed 'none', and is supported only for backward compatibility."
local linetype none
}
if ("`method'"!="") {
di as text "NOTE: method() is no longer a recognized option, and will be ignored. binscatter now always uses the fastest method without a need for two instances"
}
if ("`unique'"!="") {
di as text "NOTE: unique() is no longer a recognized option, and will be ignored. binscatter now considers the x-variable discrete if it has fewer unique values than nquantiles()"
}
***** End legacy option capatibility code
*** Perform checks
* Set default linetype and check valid
if ("`linetype'"=="") local linetype lfit
else if !inlist("`linetype'","connect","lfit","qfit","none") {
di as error "linetype() must either be connect, lfit, qfit, or none"
exit
}
* Check that nofastxtile isn't combined with fastxtile-only options
if "`fastxtile'"=="nofastxtile" & ("`randvar'"!="" | `randcut'!=1 | `randn'!=-1) {
di as error "Cannot combine randvar, randcut or randn with nofastxtile"
exit
}
* Misc checks
if ("`genxq'"!="" & ("`xq'"!="" | "`discrete'"!="")) | ("`xq'"!="" & "`discrete'"!="") {
di as error "Cannot specify more than one of genxq(), xq(), and discrete simultaneously."
exit
}
if ("`genxq'"!="") confirm new variable `genxq'
if ("`xq'"!="") {
capture assert `xq'==int(`xq') & `xq'>0
if _rc!=0 {
di as error "xq() must contain only positive integers."
exit
}
if ("`controls'`absorb'"!="") di as text "warning: xq() is specified in combination with controls() or absorb(). note that binning takes places after residualization, so the xq variable should contain bins of the residuals."
}
if `nquantiles'!=20 & ("`xq'"!="" | "`discrete'"!="") {
di as error "Cannot specify nquantiles in combination with discrete or an xq variable."
exit
}
if "`reportreg'"!="" & !inlist("`linetype'","lfit","qfit") {
di as error "Cannot specify 'reportreg' when no fit line is being created."
exit
}
if "`replace'"=="" {
if `"`savegraph'"'!="" {
if regexm(`"`savegraph'"',"\.[a-zA-Z0-9]+$") confirm new file `"`savegraph'"'
else confirm new file `"`savegraph'.gph"'
}
if `"`savedata'"'!="" {
confirm new file `"`savedata'.csv"'
confirm new file `"`savedata'.do"'
}
}
/* use version 15.1 if we need to plot with transparency */
if "`ci'" != "" version 15.0
* Mark sample (reflects the if/in conditions, and includes only nonmissing observations)
marksample touse
markout `touse' `by' `xq' `controls' `absorb', strok
qui count if `touse'
local samplesize=r(N)
local touse_first=_N-`samplesize'+1
local touse_last=_N
* Parse varlist into y-vars and x-var
local x_var=word("`varlist'",-1)
local y_vars=regexr("`varlist'"," `x_var'$","")
local ynum=wordcount("`y_vars'")
* Check number of unique byvals & create local storing byvals
if "`by'"!="" {
local byvarname `by'
capture confirm numeric variable `by'
if _rc {
* by-variable is string => generate a numeric version
tempvar by
tempname bylabel
egen `by'=group(`byvarname'), lname(`bylabel')
}
local bylabel `:value label `by'' /*catch value labels for numeric by-vars too*/
tempname byvalmatrix
qui tab `by' if `touse', nofreq matrow(`byvalmatrix')
local bynum=r(r)
forvalues i=1/`bynum' {
local byvals `byvals' `=`byvalmatrix'[`i',1]'
}
}
else local bynum=1
****** Create residuals ******
if (`"`controls'`absorb'"'!="") quietly {
* Parse absorb to define the type of regression to be used
if `"`absorb'"'!="" {
local regtype "areg"
local absorb "absorb(`absorb')"
}
else {
local regtype "reg"
}
* Generate residuals
local firstloop=1
foreach var of varlist `x_var' `y_vars' {
tempvar residvar
`regtype' `var' `controls' `wt' if `touse', `absorb'
predict `residvar' if e(sample), residuals
if ("`addmean'"!="noaddmean") {
summarize `var' `wt' if `touse', meanonly
replace `residvar'=`residvar'+r(mean)
}
label variable `residvar' "`var'"
if `firstloop'==1 {
local x_r `residvar'
local firstloop=0
}
else local y_vars_r `y_vars_r' `residvar'
}
}
else { /*absorb and controls both empty, no need for regression*/
local x_r `x_var'
local y_vars_r `y_vars'
}
****** Regressions for fit lines ******
if ("`reportreg'"=="") local reg_verbosity "quietly"
if inlist("`linetype'","lfit","qfit") `reg_verbosity' {
* If doing a quadratic fit, generate a quadratic term in x
if "`linetype'"=="qfit" {
tempvar x_r2
gen `x_r2'=`x_r'^2
}
* Create matrices to hold regression results
tempname e_b_temp
forvalues i=1/`ynum' {
tempname y`i'_coefs
tempname y`i'_vcv
tempname y`i'_b
}
* LOOP over by-vars
local counter_by=1
if ("`by'"=="") local noby="noby"
foreach byval in `byvals' `noby' {
* LOOP over rd intervals
tokenize "`rd'"
local counter_rd=1
while ("`1'"!="" | `counter_rd'==1) {
* display text headers
if "`reportreg'"!="" {
di "{txt}{hline}"
if ("`by'"!="") {
if ("`bylabel'"=="") di "-> `byvarname' = `byval'"
else {
di "-> `byvarname' = `: label `bylabel' `byval''"
}
}
if ("`rd'"!="") {
if (`counter_rd'==1) di "RD: `x_var'<=`1'"
else if ("`2'"!="") di "RD: `x_var'>`1' & `x_var'<=`2'"
else di "RD: `x_var'>`1'"
}
}
* set conditions on reg
local conds `touse'
if ("`by'"!="" ) local conds `conds' & `by'==`byval'
if ("`rd'"!="") {
if (`counter_rd'==1) local conds `conds' & `x_r'<=`1'
else if ("`2'"!="") local conds `conds' & `x_r'>`1' & `x_r'<=`2'
else local conds `conds' & `x_r'>`1'
}
* LOOP over y-vars
local counter_depvar=1
foreach depvar of varlist `y_vars_r' {
* display text headers
if (`ynum'>1) {
if ("`controls'`absorb'"!="") local depvar_name : var label `depvar'
else local depvar_name `depvar'
di as text "{bf:y_var = `depvar_name'}"
}
* perform regression
local reg_cmd reghdfe
if "`medians'" != "" local reg_cmd bsqreg
else /* if it's not a median regression, add in the no absorb option */ local noabsorb noabsorb
if ("`reg_verbosity'"=="quietly") capture `reg_cmd' `depvar' `x_r2' `x_r' `wt' if `conds', `vce' `noabsorb'
else capture noisily `reg_cmd' `depvar' `x_r2' `x_r' `wt' if `conds', `vce' `noabsorb'
pause
* store results
if (_rc==0){
matrix e_b_temp=e(b)
}
else if (_rc==2000) {
if ("`reg_verbosity'"=="quietly") di as error "no observations for one of the fit lines. add 'reportreg' for more info."
if ("`linetype'"=="lfit") matrix e_b_temp=.,.
else /*("`linetype'"=="qfit")*/ matrix e_b_temp=.,.,.
}
else {
error _rc
exit _rc
}
* relabel matrix row
/* maybe this will be helpful... */
if ("`by'"!="") matrix roweq e_b_temp = "by`counter_by'"
if ("`rd'"!="") matrix rownames e_b_temp = "rd`counter_rd'"
else matrix rownames e_b_temp = "="
* save to y_var matrix
if (`counter_by'==1 & `counter_rd'==1) matrix `y`counter_depvar'_coefs'=e_b_temp
else matrix `y`counter_depvar'_coefs'=`y`counter_depvar'_coefs' \ e_b_temp
** save coefs and vcv
if (`counter_by'==1 & `counter_rd'==1) matrix `y`counter_depvar'_b'= e(b)
else matrix `y`counter_depvar'_b'= `y`counter_depvar'_b' \ e(b)
if (`counter_by'==1 & `counter_rd'==1) matrix `y`counter_depvar'_vcv'= e(V)
else matrix `y`counter_depvar'_vcv'= `y`counter_depvar'_vcv' \ e(V)
* increment depvar counter
local ++counter_depvar
}
* increment rd counter
if (`counter_rd'!=1) mac shift
local ++counter_rd
}
* increment by counter
local ++counter_by
}
* relabel matrix column names
forvalues i=1/`ynum' {
if ("`linetype'"=="lfit") matrix colnames `y`i'_coefs' = "`x_var'" "_cons"
else if ("`linetype'"=="qfit") matrix colnames `y`i'_coefs' = "`x_var'^2" "`x_var'" "_cons"
}
}
******* Define the bins *******
/* save time and don't cluster std errors of the mean estimates if we aren't going to use them */
if !`bin_ci' local vce ""
* Specify and/or create the xq var, as necessary
if "`xq'"=="" {
if !(`touse_first'==1 & word("`:sortedby'",1)=="`x_r'") sort `touse' `x_r'
if "`discrete'"=="" { /* xq() and discrete are not specified */
* Check whether the number of unique values > nquantiles, or <= nquantiles
capture mata: characterize_unique_vals_sorted("`x_r'",`touse_first',`touse_last',`nquantiles')
if (_rc==0) { /* number of unique values <= nquantiles, set to discrete */
local discrete discrete
if ("`genxq'"!="") di as text `"note: the x-variable has fewer unique values than the number of bins specified (`nquantiles'). It will therefore be treated as discrete, and genxq() will be ignored"'
local xq `x_r'
local nquantiles=r(r)
if ("`by'"=="") {
tempname xq_boundaries xq_values
matrix `xq_boundaries'=r(boundaries)
matrix `xq_values'=r(values)
}
}
else if (_rc==134) { /* number of unique values > nquantiles, perform binning */
if ("`genxq'"!="") local xq `genxq'
else tempvar xq
if ("`fastxtile'"!="nofastxtile") fastxtile `xq' = `x_r' `wt' in `touse_first'/`touse_last', nq(`nquantiles') randvar(`randvar') randcut(`randcut') randn(`randn')
else xtile `xq' = `x_r' `wt' in `touse_first'/`touse_last', nq(`nquantiles')
if ("`by'"=="") {
mata: characterize_unique_vals_sorted("`xq'",`touse_first',`touse_last',`nquantiles')
if (r(r)!=`nquantiles') {
di as text "warning: nquantiles(`nquantiles') was specified, but only `r(r)' were generated. see help file under nquantiles() for explanation."
local nquantiles=r(r)
}
tempname xq_boundaries xq_values
matrix `xq_boundaries'=r(boundaries)
matrix `xq_values'=r(values)
}
}
else {
error _rc
}
}
else { /* discrete is specified, xq() & genxq() are not */
if ("`controls'`absorb'"!="") di as text "warning: discrete is specified in combination with controls() or absorb(). note that binning takes places after residualization, so the residualized x-variable may contain many more unique values."
capture mata: characterize_unique_vals_sorted("`x_r'",`touse_first',`touse_last',`=`samplesize'/2')
if (_rc==0) {
local xq `x_r'
local nquantiles=r(r)
if ("`by'"=="") {
tempname xq_boundaries xq_values
matrix `xq_boundaries'=r(boundaries)
matrix `xq_values'=r(values)
}
}
else if (_rc==134) {
di as error "discrete specified, but number of unique values is > (sample size/2)"
exit 134
}
else {
error _rc
}
}
}
else {
if !(`touse_first'==1 & word("`:sortedby'",1)=="`xq'") sort `touse' `xq'
* set nquantiles & boundaries
mata: characterize_unique_vals_sorted("`xq'",`touse_first',`touse_last',`=`samplesize'/2')
if (_rc==0) {
local nquantiles=r(r)
if ("`by'"=="") {
tempname xq_boundaries xq_values
matrix `xq_boundaries'=r(boundaries)
matrix `xq_values'=r(values)
}
}
else if (_rc==134) {
di as error "discrete specified, but number of unique values is > (sample size/2)"
exit 134
}
else {
error _rc
}
}
********** Compute scatter points **********
if ("`by'"!="") {
sort `touse' `by' `xq'
tempname by_boundaries
mata: characterize_unique_vals_sorted("`by'",`touse_first',`touse_last',`bynum')
matrix `by_boundaries'=r(boundaries)
}
forvalues b=1/`bynum' {
if ("`by'"!="") {
mata: characterize_unique_vals_sorted("`xq'",`=`by_boundaries'[`b',1]',`=`by_boundaries'[`b',2]',`nquantiles')
tempname xq_boundaries xq_values
matrix `xq_boundaries'=r(boundaries)
matrix `xq_values'=r(values)
}
/* otherwise xq_boundaries and xq_values are defined above in the binning code block */
* Define x-means
tempname xbin_means
if ("`discrete'"=="discrete") {
matrix `xbin_means'=`xq_values'
}
else {
means_in_boundaries `x_r' `wt', bounds(`xq_boundaries') `medians' `vce'
matrix `xbin_means'=r(means)
}
* LOOP over y-vars to define y-means
local counter_depvar=0
foreach depvar of varlist `y_vars_r' {
local ++counter_depvar
means_in_boundaries `depvar' `wt', bounds(`xq_boundaries') `medians' `vce'
* store to matrix
if (`b'==1) {
tempname y`counter_depvar'_scatterpts
tempname y`counter_depvar'_loci
tempname y`counter_depvar'_hici
/*add confidence intervals */
matrix `y`counter_depvar'_scatterpts' = `xbin_means',r(means)
matrix `y`counter_depvar'_loci' = `xbin_means',r(loci)
matrix `y`counter_depvar'_hici' = `xbin_means',r(hici)
}
else {
* make matrices conformable before right appending
local rowdiff=rowsof(`y`counter_depvar'_scatterpts')-rowsof(`xbin_means')
if (`rowdiff'==0) matrix `y`counter_depvar'_scatterpts' = `y`counter_depvar'_scatterpts',`xbin_means',r(means)
else if (`rowdiff'>0) matrix `y`counter_depvar'_scatterpts' = `y`counter_depvar'_scatterpts', ( (`xbin_means',r(means)) \ J(`rowdiff',2,.) )
else /*(`rowdiff'<0)*/ matrix `y`counter_depvar'_scatterpts' = ( `y`counter_depvar'_scatterpts' \ J(-`rowdiff',colsof(`y`counter_depvar'_scatterpts'),.) ) ,`xbin_means',r(means)
/* append confidence intervals if by is used */
local rowdiff_lo=rowsof(`y`counter_depvar'_loci')-rowsof(`xbin_means')
if (`rowdiff_lo'==0) matrix `y`counter_depvar'_loci' = `y`counter_depvar'_loci',`xbin_means',r(loci)
else if (`rowdiff_lo'>0) matrix `y`counter_depvar'_loci' = `y`counter_depvar'_loci', ( (`xbin_means',r(loci)) \ J(`rowdiff_lo',2,.) )
else /*(`rowdiff'<0)*/ matrix `y`counter_depvar'_loci' = ( `y`counter_depvar'_loci' \ J(-`rowdiff_lo',colsof(`y`counter_depvar'_loci'),.) ) ,`xbin_means',r(loci)
local rowdiff_hi=rowsof(`y`counter_depvar'_hici')-rowsof(`xbin_means')
if (`rowdiff_hi'==0) matrix `y`counter_depvar'_hici' = `y`counter_depvar'_hici',`xbin_means',r(hici)
else if (`rowdiff_hi'>0) matrix `y`counter_depvar'_hici' = `y`counter_depvar'_hici', ( (`xbin_means',r(hici)) \ J(`rowdiff_hi',2,.) )
else /*(`rowdiff'<0)*/ matrix `y`counter_depvar'_hici' = ( `y`counter_depvar'_hici' \ J(-`rowdiff_hi',colsof(`y`counter_depvar'_hici'),.) ) ,`xbin_means',r(hici)
}
}
}
*********** Perform Graphing ***********
* If rd is specified, prepare xline parameters
if "`rd'"!="" {
foreach xval in "`rd'" {
local xlines `xlines' xline(`xval', lpattern(dash) lcolor(gs8))
}
}
* Fill colors if missing
if `"`colors'"'=="" local colors ///
navy maroon forest_green dkorange teal cranberry lavender ///
khaki sienna emidblue emerald brown erose gold bluishgray ///
/* lime magenta cyan pink blue */
if `"`mcolors'"'=="" {
if (`ynum'==1 & `bynum'==1 & "`linetype'"!="connect") local mcolors `: word 1 of `colors''
else local mcolors `colors'
}
if `"`lcolors'"'==`""' {
if (`ynum'==1 & `bynum'==1 & "`linetype'"!="connect") local lcolors `: word 2 of `colors''
else local lcolors `colors'
pause
}
local num_mcolor=wordcount(`"`mcolors'"')
local num_lcolor=wordcount(`"`lcolors'"')
* Prepare connect & msymbol options
if ("`linetype'"=="connect") local connect "c(l)"
if "`msymbols'"!="" {
local symbol_prefix "msymbol("
local symbol_suffix ")"
}
*** Prepare scatters
* c indexes which color is to be used
local c=0
local counter_series=0
* LOOP over by-vars
local counter_by=0
if ("`by'"=="") local noby="noby"
foreach byval in `byvals' `noby' {
local ++counter_by
local xind=`counter_by'*2-1
local yind=`counter_by'*2
* LOOP over y-vars
local counter_depvar=0
foreach depvar of varlist `y_vars' {
local ++counter_depvar
local ++c
* LOOP over rows (each row contains a coordinate pair)
local row=1
local xval=`y`counter_depvar'_scatterpts'[`row',`xind']
local yval=`y`counter_depvar'_scatterpts'[`row',`yind']
local y_loci=`y`counter_depvar'_loci'[`row',`yind']
local y_hici=`y`counter_depvar'_hici'[`row',`yind']
if !missing(`xval',`yval') {
local ++counter_series
local scatters `scatters' (scatteri
/* local cis `cis' (scatteri */
local lo `lo' (scatteri
local hi `hi' (scatteri
if ("`savedata'"!="") {
if ("`by'"=="") local savedata_scatters `savedata_scatters' (scatter `depvar' `x_var'
else local savedata_scatters `savedata_scatters' (scatter `depvar'_by`counter_by' `x_var'_by`counter_by'
}
}
else {
* skip the rest of this loop iteration
continue
}
while (`xval'!=. & `yval'!=.) {
local scatters `scatters' `yval' `xval'
/* local cis `cis' `y_loci' `y_hici' `xval' */
local lo `lo' `y_loci' `xval'
local hi `hi' `y_hici' `xval'
local ++row
local xval=`y`counter_depvar'_scatterpts'[`row',`xind']
local yval=`y`counter_depvar'_scatterpts'[`row',`yind']
local y_loci=`y`counter_depvar'_loci'[`row',`yind']
local y_hici=`y`counter_depvar'_hici'[`row',`yind']
}
* Add options
local scatter_options `connect' mcolor(`: word `c' of `mcolors'') lcolor(`: word `c' of `lcolors'') `symbol_prefix'`: word `c' of `msymbols''`symbol_suffix'
local scatters `scatters', `scatter_options')
local ci_options lcolor(`: word `c' of `mcolors''%75) lpattern(dash) recast(line)
local lo `lo' , `ci_options')
local hi `hi' , `ci_options')
/* local ci_options fcolor(`: word `c' of `mcolors''%30) lcolor(`: word `c' of `mcolors''%0) recast(rarea)
local cis `cis', `ci_options') */
if ("`savedata'"!="") local savedata_scatters `savedata_scatters', `scatter_options')
* Add legend
if "`by'"=="" {
if (`ynum'==1) local legend_labels off
else if "`ci'" != "" local legend_labels `legend_labels' lab(`=2*`counter_series'' `depvar')
else /* no ci */ local legend_labels `legend_labels' lab(`counter_series' `depvar')
}
else {
if ("`bylabel'"=="") local byvalname=`byval'
else {
local byvalname `: label `bylabel' `byval''
}
if (`ynum'==1){
if "`ci'" != "" local legend_labels `legend_labels' lab(`counter_series' `byvarname'=`byvalname')
else /* no ci */ local legend_labels `legend_labels' lab(`=3*`counter_series'' `byvarname'=`byvalname')
}
else {
local legend_labels `legend_labels' lab(`counter_series' `depvar': `byvarname'=`byvalname')
}
}
if ("`by'"!="" | `ynum'>1) local order `order' `counter_series'
}
}
*** Fit lines
if inlist(`"`linetype'"',"lfit","qfit") {
if "`linetype'" == "lfit" local n_coefs 2
else if "`linetype'" == "qfit" local n_coefs 3
* c indexes which color is to be used
local c=0
local rdnum=wordcount("`rd'")+1
tempname fitline_bounds
if ("`rd'"=="") matrix `fitline_bounds'=.,.
else matrix `fitline_bounds'=.,`=subinstr("`rd'"," ",",",.)',.
* LOOP over by-vars
local counter_by=0
if ("`by'"=="") local noby="noby"
foreach byval in `byvals' `noby' {
local ++counter_by
** Set the column for the x-coords in the scatterpts matrix
local xind=`counter_by'*2-1
* Set the row to start seeking from
* note: each time we seek a coeff, it should be from row (rd_num)(counter_by-1)+counter_rd
local row0=( `rdnum' ) * (`counter_by' - 1)
* LOOP over y-vars
local counter_depvar=0
foreach depvar of varlist `y_vars_r' {
local ++counter_depvar
local ++c
local model_obs = round(100/`rdnum')*`rdnum'
* Find lower and upper bounds for the fit line
matrix `fitline_bounds'[1,1]=`y`counter_depvar'_scatterpts'[1,`xind']
local fitline_ub_rindex=`nquantiles'
local fitline_ub=.
while `fitline_ub'==. {
local fitline_ub=`y`counter_depvar'_scatterpts'[`fitline_ub_rindex',`xind']
local --fitline_ub_rindex
}
matrix `fitline_bounds'[1,`rdnum'+1]=`fitline_ub'
* LOOP over rd intervals
tempname temp_x temp_lo temp_hi
forvalues counter_rd=1/`rdnum' {
local vcv0 = (( `row0') + (`counter_rd' - 1 )) * `n_coefs' + 1
if (`"`linetype'"'=="lfit") {
local coef_quad=0
local coef_lin=`y`counter_depvar'_coefs'[`row0'+`counter_rd',1]
local coef_cons=`y`counter_depvar'_coefs'[`row0'+`counter_rd',2]
}
else if (`"`linetype'"'=="qfit") {
local coef_quad=`y`counter_depvar'_coefs'[`row0'+`counter_rd',1]
local coef_lin=`y`counter_depvar'_coefs'[`row0'+`counter_rd',2]
local coef_cons=`y`counter_depvar'_coefs'[`row0'+`counter_rd',3]
}
if !missing(`coef_quad',`coef_lin',`coef_cons') {
local leftbound=`fitline_bounds'[1,`counter_rd']
local rightbound=`fitline_bounds'[1,`counter_rd'+1]
if `model_ci'{
local xobs = round(100/`rdnum')
tempname coefs vcv
if `"`linetype'"'=="lfit"{
mat `coefs' = `y`counter_depvar'_coefs'[`row0'+`counter_rd',1],`y`counter_depvar'_coefs'[`row0'+`counter_rd',2]
mat `vcv' = `y`counter_depvar'_vcv'[`vcv0'..`=`vcv0'+1',1],`y`counter_depvar'_vcv'[`vcv0'..`=`vcv0'+1',2]
}
else if (`"`linetype'"'=="qfit"){
mat `coefs' = `y`counter_depvar'_coefs'[`row0'+`counter_rd',1],`y`counter_depvar'_coefs'[`row0'+`counter_rd',2],`y`counter_depvar'_coefs'[`row0'+`counter_rd',3]
mat `vcv' = `y`counter_depvar'_vcv'[`vcv0'..`=`vcv0'+2',1],`y`counter_depvar'_vcv'[`vcv0'..`=`vcv0'+2',2],`y`counter_depvar'_vcv'[`vcv0'..`=`vcv0'+2',3]
}
model_bounds, cov(`vcv') means(`coefs') seed(`bin_seed') x_range(`leftbound' `rightbound') x_obs(`xobs') `=trim("`linetype'")'
local row = 1
matrix `temp_x' = r(model_x)
matrix `temp_lo' = r(model_lo)
matrix `temp_hi' = r(model_hi)
local plot_m_hi (scatteri
local plot_m_lo (scatteri
/* we got these matrices, now we can plot them... */
while !missing(`temp_x'[`row',1], `temp_lo'[`row',1], `temp_hi'[`row',1] ){
local plot_m_hi `plot_m_hi' `=`temp_hi'[`row',1]' `=`temp_x'[`row',1]'
local plot_m_lo `plot_m_lo' `=`temp_lo'[`row',1]' `=`temp_x'[`row',1]'
local ++row
}
local plot_m_hi `plot_m_hi' , lcolor(`: word `c' of `lcolors'') lpattern(dash) recast(line))
local plot_m_lo `plot_m_lo' , lcolor(`: word `c' of `lcolors'') lpattern(dash) recast(line))
local fit_cis `fit_cis' `plot_m_hi' `plot_m_lo'
}
local fits `fits' (function `coef_quad'*x^2+`coef_lin'*x+`coef_cons', range(`leftbound' `rightbound') lcolor(`: word `c' of `lcolors''))
}
}
}
}
}
* Prepare y-axis title
if (`ynum'==1) local ytitle `y_vars'
else if (`ynum'==2) local ytitle : subinstr local y_vars " " " and "
else local ytitle : subinstr local y_vars " " "; ", all
* Display graph
/* only plot cis if specified */
/** MORE FLEXIBLE VERSION **/
if `bin_ci' {
preserve
clear
local counter_depvar= 0
local cis
local ci_type (rarea
local color = 0
foreach v in `y_vars' {
local ++counter_depvar
qui: svmat `y`counter_depvar'_loci', names("y`counter_depvar'_lo")
qui: svmat `y`counter_depvar'_hici', names("y`counter_depvar'_hi")
local by_index = 1
foreach byval in `byvals' `noby'{
local cis `cis' `ci_type'
local y_index = 2*`by_index'
local x_index = `y_index' - 1
local cis `cis' y`counter_depvar'_lo`y_index' y`counter_depvar'_hi`y_index' y`counter_depvar'_hi`x_index', fcolor(`:word `++color' of `colors''%30) lcolor(`:word `color' of `colors''%0))
local ++by_index
}
}
local graphcmd twoway `cis' `scatters' `fits' `fit_cis', graphregion(fcolor(white)) `xlines' xtitle(`x_var') ytitle(`ytitle') legend(`legend_labels' order(`order')) `options'
`graphcmd'
restore
}
else {
local graphcmd twoway `scatters' `fits' `fit_cis', graphregion(fcolor(white)) `xlines' xtitle(`x_var') ytitle(`ytitle') legend(`legend_labels' order(`order')) `options'
if ("`savedata'"!="") local savedata_graphcmd twoway `savedata_scatters' `fits', graphregion(fcolor(white)) `xlines' xtitle(`x_var') ytitle(`ytitle') legend(`legend_labels' order(`order')) `options'
`graphcmd'
}
****** Save results ******
* Save graph
if `"`savegraph'"'!="" {
* check file extension using a regular expression
if regexm(`"`savegraph'"',"\.[a-zA-Z0-9]+$") local graphextension=regexs(0)
if inlist(`"`graphextension'"',".gph","") graph save `"`savegraph'"', `replace'
else graph export `"`savegraph'"', `replace'
}
* Save data
if ("`savedata'"!="") {
*** Save a CSV containing the scatter points
tempname savedatafile
file open `savedatafile' using `"`savedata'.csv"', write text `replace'
* LOOP over rows
forvalues row=0/`nquantiles' {
*** Put the x-variable at the left
* LOOP over by-vals
forvalues counter_by=1/`bynum' {
if (`row'==0) { /* write variable names */
if "`by'"!="" local bynlabel _by`counter_by'
file write `savedatafile' "`x_var'`bynlabel',"
}
else { /* write data values */
if (`row'<=`=rowsof(`y1_scatterpts')') file write `savedatafile' (`y1_scatterpts'[`row',`counter_by'*2-1]) ","
else file write `savedatafile' ".,"
}
}
*** Now y-variables at the right
* LOOP over y-vars
local counter_depvar=0
foreach depvar of varlist `y_vars' {
local ++counter_depvar
* LOOP over by-vals
forvalues counter_by=1/`bynum' {
if (`row'==0) { /* write variable names */
if "`by'"!="" local bynlabel _by`counter_by'
file write `savedatafile' "`depvar'`bynlabel'"
}
else { /* write data values */
if (`row'<=`=rowsof(`y`counter_depvar'_scatterpts')') file write `savedatafile' (`y`counter_depvar'_scatterpts'[`row',`counter_by'*2])
else file write `savedatafile' "."
}
* unless this is the last variable in the dataset, add a comma
if !(`counter_depvar'==`ynum' & `counter_by'==`bynum') file write `savedatafile' ","
} /* end by-val loop */
} /* end y-var loop */
file write `savedatafile' _n
} /* end row loop */
file close `savedatafile'
di as text `"(file `savedata'.csv written containing saved data)"'
*** Save a do-file with the commands to generate a nicely labeled dataset and re-create the binscatter graph
file open `savedatafile' using `"`savedata'.do"', write text `replace'
file write `savedatafile' `"insheet using `savedata'.csv"' _n _n
if "`by'"!="" {
foreach var of varlist `x_var' `y_vars' {
local counter_by=0
foreach byval in `byvals' {
local ++counter_by
if ("`bylabel'"=="") local byvalname=`byval'
else {
local byvalname `: label `bylabel' `byval''
}
file write `savedatafile' `"label variable `var'_by`counter_by' "`var'; `byvarname'==`byvalname'""' _n
}
}
file write `savedatafile' _n
}
file write `savedatafile' `"`savedata_graphcmd'"' _n
file close `savedatafile'
di as text `"(file `savedata'.do written containing commands to process saved data)"'
}
*** Return items
ereturn post, esample(`touse')
ereturn scalar N = `samplesize'
ereturn local graphcmd `"`graphcmd'"'
if inlist("`linetype'","lfit","qfit") {
forvalues yi=`ynum'(-1)1 {
ereturn matrix y`yi'_coefs=`y`yi'_coefs'
}
}
if ("`rd'"!="") {
tempname rdintervals
matrix `rdintervals' = (. \ `=subinstr("`rd'"," ","\",.)' ) , ( `=subinstr("`rd'"," ","\",.)' \ .)
forvalues i=1/`=rowsof(`rdintervals')' {
local rdintervals_labels `rdintervals_labels' rd`i'
}
matrix rownames `rdintervals' = `rdintervals_labels'
matrix colnames `rdintervals' = gt lt_eq
ereturn matrix rdintervals=`rdintervals'
}
if ("`by'"!="" & "`by'"=="`byvarname'") { /* if a numeric by-variable was specified */
forvalues i=1/`=rowsof(`byvalmatrix')' {
local byvalmatrix_labels `byvalmatrix_labels' by`i'
}
matrix rownames `byvalmatrix' = `byvalmatrix_labels'
matrix colnames `byvalmatrix' = `by'
ereturn matrix byvalues=`byvalmatrix'
}
end
**********************************
* Helper programs
program define model_bounds, rclass
version 15.1
syntax, COV(passthru) Means(passthru) seed(passthru) x_range(numlist max=2 min=2 ascending) [qfit lfit x_obs(integer 100)]
local n_draws = 100000
if "`lfit'" != "" local coefs "b1 b0"
else if "`qfit'" != "" local coefs "b2 b1 b0"
else {
di as error "Please select qfit or lfit in model_bounds"
exit
}
gettoken x_min x_max: (local) x_range
local x_step = (`x_max' - `x_min')/`x_obs'
preserve
qui: drawnorm `coefs', `means' `cov' n(`n_draws') `seed' clear
tempvar yhat
local row = 1
local x_i = `x_min'
forvalues i = 1/`x_obs' {
if "`lfit'" != "" gen `yhat' = b1*`x_i' + b0
else /* if qfit */ gen `yhat' = b2*`x_i'*`x_i' + b1*`x_i' + b0