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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
* ==============================================================================
* ciquartile: Creating spike plots with interquarterile range
* Author: Zong Huang
* 
* Based off of Alexander Staudt's cibar
* ==============================================================================

* over1 : over-variable
* over2 : additional over-variable
* over3 : additional over-variable
* bar : plot spikes as bar; default is scatter
* horizontal : plot spikes horizontally; default is vertically
* reverse : reverse order of spikes
* missing : omit missing spikes (buggy)
* gap2 : specify gap between spike groups (over2); default is 67% (of a spike)
* gap3 : specify gap between spike groups (over3); default is 100% (of a spike) 
* spikeopts : specify the look of the spikes (global)
* spikecolor : specify the color of the spikes, delimited by spaces
* spikegap : specify gap within spike groups; default is 0% (of a spike)
* spike : specify the look for each spike, delimited by ||
* spikegroup : specify the look for each spike group (over2), delimited by ||
* ciopts : specify the look of the confidence intervals (global)
* cicolor : specify the color of the confidence intervals, delimited by spaces
* ci : specify the look for each confidence interval, delimited by ||
* cigroup : specify the look for each confidence interval group (over2), delimited by ||
* graphopts : specify additional graph options

program define ciquartile
    syntax anything(name = var) [if], ///
           over1(string) [over2(string) over3(string) ///
           bar horizontal missing reverse ///
           gap2(integer 67) gap3(integer 100) ///
           spikeopts(string asis) spikecolor(string asis) spikegap(integer 0) ///
           spike(string asis) spikegroup(string asis) ///
           ciopts(string asis) cicolor(string asis) ///
           ci(string asis) cigroup(string asis) ///
           graphopts(str asis)]
    
    preserve
        
    * ==========================================================================
    * Parse options
    * ==========================================================================
    
    * If option
    mark touse `if'
    qui keep if touse == 1
    
    * Direction option
    if "`horizontal'" == "horizontal" {
        local a1 "y"
        local a2 "x"
        local a1_angle "labgap(2) angle(0)"
        local a1_order "s median"
    }
    else {
        local a1 "x"
        local a2 "y"
        local a1_angle "labgap(2)"
        local a1_order "median s"
    }
    
    * Group options
    local bylist = "`over1' `over2' `over3'"
    local n_over = wordcount("`bylist'")
    local gap2 = `gap2' / 100 - 1
    local gap3 = `gap3' / 100
    
    * Spike options
    local spikeopts = "fintensity(inten100) `a1'axis(1 2 3)" + " " + `"`spikeopts'"'
    local sg = `spikegap' / 100

    * Confidence interval options
    local ciopts = "lcolor(gs8)" + " " + `"`ciopts'"'

    * ==========================================================================
    * Calculate mean and confidence interval
    * ==========================================================================
    
    * Calculate percentiles
    bysort `bylist': egen lb     = pctile(`var'), p(25)
    bysort `bylist': egen median = mean(`var')
    bysort `bylist': egen ub     = pctile(`var'), p(75)
    

    * Get percentiles
    keep `bylist' lb median ub
    duplicates drop

    foreach x in `bylist' {
        qui drop if `x' == . // Confidence intervals not calculated for missing groups
    }

    * ==========================================================================
    * Get group labels
    * ==========================================================================
    
    if `n_over' == 2 {
        capture confirm existence `over2'
        if _rc == 6 {
            local over2 = "`over3'"
            display as txt "You specified over3() but not over2(). The value of over3() is used in over2() instead."
        }
    }

    * Reindex group levels sequentially
    forvalues i = 1/`n_over' {
        qui tab `over`i''
        local labels`i' = `r(r)'
        qui levelsof(`over`i''), local(levels`i')
    }

    forvalues i = 1/`n_over' {
        qui gen over`i'_n = .
        tokenize "`levels`i''"
        forvalues j = 1/`labels`i'' {
            qui replace over`i'_n = `j' if `over`i'' == ``j''
        }
    }

    * Label sequential group levels
    forvalues i = 1/`n_over' {
        tokenize "`levels`i''"
        forvalues j = 1/`labels`i'' {
            local ltext : label (`over`i'') ``j''
            label define vlabel`i' `j' `"`ltext'"', add
            if `j' == `labels`i'' label value over`i'_n vlabel`i'
        }
    }

    forvalues i = 1/`n_over' {
        qui levelsof(over`i'_n), local(levels`i'_n)
    }

    * ==========================================================================
    * Generate graph labels (single group case)
    * ==========================================================================
    
    if `n_over' == 1 {  
        * Adjust spacing for spikegap
        qui tab over1_n
        qui gen s = over1_n
        qui replace s = s * (1 + `sg')

        * Reverse spacing if applicable
        if "`reverse'" == "reverse" replace s = s * -1

        * Get spacing for spikes
        qui sum s
        local s_min = `r(min)' - .75
        local s_max = `r(max)' + .75
        
        * Get labels for spikes
        local axis = "`a1'label(`s_min'" + " " + `"" ""' + " " + "`s_max'" + " " + `"" ""' + ", noticks `a1_angle')"
    } 

    * ==========================================================================
    * Generate graph labels (two group case)
    * ==========================================================================
    
    if `n_over' == 2 {
        * Add missing spikes
        forvalues i = 1/`labels1' {
            forvalues j = 1/`labels2' {
                qui tab median if over1_n == `i' & over2_n == `j'
                if `r(r)' == 0 {
                    local obsv = _N + 1
                    qui set obs `obsv'
                    qui replace over1_n = `i' in `obsv'
                    qui replace over2_n = `j' in `obsv'
                }
            }
        }
        sort over2_n over1_n

        * Adjust spacing for spikegap
        qui gen s = .
        tokenize "`levels1_n'"
        forvalues i = 1/`labels1' {
            qui replace s = over1_n + (``i'' - 1) * (`sg') if over1_n == ``i''
        }
        
        * Adjust spacing for gap2
        tokenize "`levels2_n'"
        forvalues i = 1/`labels2' {
            qui replace s = s + (`labels1' + 1 + `gap2' + `sg') * (`i' - 1) if over2_n == ``i''
        }

        * Get spacing for spikes  
        forvalues i = 1/`labels2' {
            qui sum s if over2_n == `i'
            local s_`i' = `r(mean)'
            if `i' == `labels2' {
                local s_min = 0
                local s_max = `r(max)' + 1
            }
        }

        * Reverse spacing if applicable
        if "`reverse'" == "reverse" {
            replace s = s * -1 
            forvalues i = 1/`labels2' {
                local s_`i' = `s_`i'' * -1
            }
            local s_max = `s_max' * -1
        }

        * Get labels for spikes     
        local axis = "`a1'label(`s_min'" + " " + `"" ""'
        forvalues i = 1/`labels2' {
            local l_`i' : label (over2_n) `i'
        
            local axis = `"`axis'"' + " " + "`s_`i''" + " " + `"`"`l_`i''"'"'
        }       
        local axis = `"`axis'"' + " " + "`s_max'" + " " + `"" ""' + " " + ", noticks `a1_angle')"
    }
    
    * ==========================================================================
    * Generate graph labels (three group case)
    * ==========================================================================
    
    if `n_over' == 3 {
        * Add missing spikes
        forvalues i = 1/`labels1' {
            forvalues j = 1/`labels2' {
                forvalues k = 1/`labels3' {
                    qui tab median if over1_n == `i' & over2_n == `j' & over3_n == `k'
                    if `r(r)' == 0 {
                        local obsv = _N+1
                        qui set obs `obsv'
                        qui replace over1_n = `i' in `obsv'
                        qui replace over2_n = `j' in `obsv'
                        qui replace over3_n = `k' in `obsv'
                    }
                }
            }
        }
        sort over3_n over2_n over1_n

        * Drop missing cross-groups (if applicable)
        qui egen over_cg = group(over3_n over2_n)
        
        if "`missing'" == "missing" {
            bysort over2_n over3_n: egen nonmissing = count(median)
            qui drop if nonmissing == 0
        }

        sort over_cg `over1'

        * Index cross-groupings
        qui tab over_cg
        local labels_cg = `r(r)'
        qui levelsof(over_cg), local(levels_cg)

        * Adjust spacing for spikegap
        qui gen index = _n
        qui gen over1_n2 = mod(index, `labels1')
        qui replace over1_n2 = `labels1' if over1_n2 == 0

        qui gen s = .
        tokenize "`levels1_n'"
        forvalues i = 1/`labels1' {
            qui replace s = over1_n2 + (``i'' - 1) * (`sg') if over1_n2 == ``i''
        }
        
        * Adjust spacing for gap2
        tokenize "`levels_cg'"
        forvalues i = 1/`labels_cg' {
            qui replace s = s + (`i' - 1) * (`labels1' + 1 + `gap2' + `sg') if over_cg == ``i''
        }
        
        * Adjust spacing for gap3
        forvalues i = 1/`labels3' {
            qui replace s = s + (-`gap2' + 1) * (`i' - 1) * `gap3' if over3_n == `i'
        }

        * Get spacing for spikes
        tokenize "`levels_cg'" 

        forvalues i = 1/`labels_cg' {
            qui sum s if over_cg == ``i''  
            local s_`i' = `r(mean)'
            if `i' == `labels2' {
                local s_min = 0
                local s_max = `r(max)' + 1
            }
        }
                
        * Reverse spacing if applicable
        if "`reverse'" == "reverse" {
            replace s = s * -1 
            forvalues i = 1/`labels_cg' {
                local s_`i' = `s_`i'' * -1
            }
            local s_max = `s_max' * -1
        }
                
        * Get labels for cross-groupings
        tokenize "`levels3_n'"
        forvalues i = 1/`labels3' {
            tokenize "`levels2_n'"
            forvalues j = 1/`labels2' {

                local l`j' : label (over2_n) ``j''
                local y = `j' + (`i' - 1) * `labels2'
                local y_l = "`y'" + " " + `"`"`l`j''"'"'
                
                if `i' == 1 & `j' == 1 local vlabel = `"`y_l'"'
                else local vlabel = `"`vlabel'"' + " " + `"`y_l'"'
            }
        }

        qui label define vlabel `vlabel'
        qui label value over_cg vlabel
                        
        * Get labels for spikes
        tokenize "`levels_cg'"   
        
        local axis = "`a1'label(`s_min'" + " " + `"" ""' 
        forvalues i = 1/`labels_cg' {
            local l_`i' : label (over_cg) ``i''
           
            local axis = `"`axis'"' + " " + "`s_`i''" + " " + `"`"`l_`i''"'"'  
        }
        local axis = `"`axis'"' + " " + "`s_max'" + " " + `"" ""' + " " + ", noticks `a1_angle')"
        
        * Get labels for spike groupings
        forvalues i = 1/`labels3' {
            forvalues j = 1/`labels_cg' {
                qui sum s if over3_n == `i'
            }
            local ss_`i' = `r(mean)'
            local ll_`i' : label (over3_n) `i'
            
            if `i' == 1 local l3 = "`ss_`i''" + " " + `"`"`ll_`i''"'"'
            else local l3 = `"`l3'"' + " " + "`ss_`i''" + " " + `"`"`ll_`i''"'"'

            if `i' == `labels3' {
                local axis = `"`axis'"' + " " + "`a1'label(" + `"`l3'"' + ", noticks `a1_angle' axis(2))"
            }
        }
    }
            
    * ==========================================================================
    * Generate graph components (single group case)
    * ==========================================================================
    
    if `n_over' == 1 {
        * Generate graph components
        forvalues j = 1/`labels1' {
            if "`bar'" == "bar" {
                qui gen spike`j' = "bar median s if over1_n == `j', `spikeopts' `horizontal'"
            } 
            else {
                qui gen spike`j' = "scatter `a1_order' if over1_n == `j', `spikeopts'"
            }
          
            qui gen rcap`j' = "rcap lb ub s if over1_n == `j', `ciopts' `horizontal'"
        }
        
        * Add colors to graph command
        if wordcount(`"`spikecolor'"') > 0 {
            qui gen scolors = `"`spikecolor'"'
            qui split scolors, gen(scolor)
             
            forvalues j = 1/`r(nvars)' {
                cap qui replace spike`j' = spike`j' + " color(" + scolor`j' + ")"
            }
        }
     
        if wordcount(`"`cicolor'"')  > 0 {
            qui gen rcolors = `"`cicolor'"'
            qui split rcolors, gen(rcolor)
             
            forvalues j = 1/`r(nvars)' {
                cap qui replace rcap`j' = rcap`j' + " lcolor(" + rcolor`j' + ")"
            }
        }

        * Add options to graph command
        if wordcount(`"`spike'"') > 0 {
            gen sopts = `"`spike'"'
            qui split sopts, gen(sopt) p("||")
            
            forvalues j = 1/`r(nvars)' {
                cap qui replace spike`j' = spike`j' + " " + sopt`j'
            }
        }
        
        if wordcount(`"`ci'"') > 0 {
            gen ropts = `"`ci'"'
            qui split ropts, gen(ropt) p("||")
            
            forvalues j = 1/`r(nvars)' {
                cap qui replace rcap`j' = rcap`j' + " " + ropt`j'
            }
        }
    }

    * ==========================================================================
    * Generate graph components (multiple group case)
    * ==========================================================================
    
    if `n_over' > 1 {
        * Generate graph components
        forvalues i = 1/`labels1' {
            forvalues j = 1/`labels2' {
                if "`bar'" == "bar" {
                    qui gen spike`i'`j' = "bar median s if over1_n == `i' & over2_n == `j', `spikeopts' `horizontal'"
                } 
                else {
                    qui gen spike`i'`j' = "scatter `a1_order' if over1_n == `i' & over2_n == `j', `spikeopts'"
                }
              
                qui gen rcap`i'`j' = "rcap lb ub s if over1_n == `i' & over2_n == `j', `ciopts' `horizontal'"
            }
        }
        
        * Add colors to graph command
        if wordcount(`"`spikecolor'"') > 0 {
            qui gen scolors = `"`spikecolor'"'
            qui split scolors, gen(scolor)
             
            forvalues i = 1/`r(nvars)' {
                forvalues j = 1/`labels2' {
                    cap qui replace spike`i'`j' = spike`i'`j' + " color(" + scolor`i' + ")"
                }
            }
        }
     
        if wordcount(`"`cicolor'"')  > 0 {
            qui gen rcolors = `"`cicolor'"'
            qui split rcolors, gen(rcolor)
             
            forvalues i = 1/`r(nvars)' {
                forvalues j = 1/`labels2' {
                    cap qui replace rcap`i'`j' = rcap`i'`j' + " lcolor(" + rcolor`i' + ")"
                }
            }
        }

        * Add options to graph command
        if wordcount(`"`spike'"') > 0 {
            gen sopts = `"`spike'"'
            qui split sopts, gen(sopt) p("||")

            forvalues i = 1/`r(nvars)' {
                forvalues j = 1/`labels2' {
                    cap qui replace spike`i'`j' = spike`i'`j' + " " + sopt`i'
                }
            }
        }
        
        if wordcount(`"`ci'"') > 0 {
            gen ropts = `"`ci'"'
            qui split ropts, gen(ropt) p("||")
            
            forvalues i = 1/`r(nvars)' {
                forvalues j = 1/`labels2' {
                    cap qui replace rcap`i'`j' = rcap`i'`j' + " " + ropt`i'
                }
            }
        }

        if wordcount(`"`spikegroup'"') > 0 {
            gen sgopts = `"`spikegroup'"'
            qui split sgopts, gen(sgopt) p("||")

            forvalues i = 1/`labels1' {
                forvalues j = 1/`r(nvars)' {
                    cap qui replace spike`i'`j' = spike`i'`j' + " " + sgopt`j'
                }
            }
        }
        
        if wordcount(`"`cigroup'"') > 0 {
            gen rgopts = `"`cigroup'"'
            qui split rgopts, gen(rgopt) p("||")

            forvalues i = 1/`labels1' {
                forvalues j = 1/`r(nvars)' {
                    cap qui replace rcap`i'`j' = rcap`i'`j' + " " + rgopt`j'
                }
            }
        }
    }

    * ==========================================================================
    * Generate graph
    * ==========================================================================

    * Concatenate graph components
    if "`bar'" == "bar" {
        qui egen graph = concat(spike* rcap*), punct(") (")
    } 
    else {
        qui egen graph = concat(rcap* spike*), punct(") (")
    }
    qui replace graph = "(" + graph + ")"
    local graph = graph[1]

    * ==========================================================================
    * Get legend (single group case)
    * ==========================================================================  
    
    if `n_over' == 1 {
        forvalues j = 1/`labels1' {  
            local l`j' : label (over1_n) `j'  
            if "`bar'" == "bar" {
                local v`j' = `j'
            } 
            else {
                local v`j' = `j' + `labels1'
            }
            
            if `j' == 1 {
                local legend1 = `"`v`j'' "`l`j''""'
            }
            else {
                local legend1 = `"`legend1'"' + " " + `"`v`j'' "`l`j''""'
            }
        }
    
        local legend = `"legend(order(`legend1') region(lcolor(white)))"'  
    }

    * ==========================================================================
    * Get legend (multiple group case)
    * ==========================================================================  
    
    if `n_over' > 1 {
        forvalues j = 1/`labels1' {  
            local l`j' : label (over1_n) `j'  
            if "`bar'" == "bar" {
                local v`j' = `j' * 2
            } 
            else {
                local v`j' = (`j' + `labels1') * 2
            }
            
            if `j' == 1 {
                local legend1 = `"`v`j'' "`l`j''""'
            }
            else {
                local legend1 = `"`legend1'"' + " " + `"`v`j'' "`l`j''""'
            }
        }
    
        local legend = `"legend(order(`legend1') region(lcolor(white)))"'  
    }

    * ==========================================================================
    * Plot graph
    * ==========================================================================
    local format = `"`legend' plotregion(margin(bargraph)) graphregion(color(white))"' + " " + ///
                   `"`a2'title("") `a1'title("") `a1'title("", axis(2)) `a1'title("", axis(3))"' + " " + ///
                   `"`a1'scale(axis(2) noline) `a1'scale(axis(3) noline)"' + " " + ///
                   `"`a1'label(none, axis(2) noticks) `a1'label(none, axis(3) noticks)"' + " " + ///
                   `"`a1'label(, nogrid) `a2'label(, grid format(%9.3g))"'
              
    dis `"`graph', `format' `axis' `graphopts'"'

    twoway `graph', `format' `axis' `graphopts'
end

exit