Hi all, I have a panel dataset and I am trying to generate percentiles for variables and then graph them. This is how I did it but I feel like there could a more efficient way to go about it using loops for the graphs. I tried looping it but I was not successful. Here is how I went about it

global controls gdp income
preserve
foreach var of varlist $controls {
collapse (p50) $controls, by(time)
}
foreach var of varlist $controls{
rename `var' `var'_50
}


*********Then I save it and then do it for the 75th percentile:

restore
preserve
foreach var of varlist $controls{
collapse (p75) $controls, by(time)
}
foreach var of varlist $controls {
rename `var' `var'_75
}

*********Then I save it and then do it for the 25th percentile:

restore
preserve
foreach var of varlist $controls{
collapse (p25) $controls, by(time)
}
foreach var of varlist $controls {
rename `var' `var'_25
}

*****Then I save it and merge all the three files to get this example table below:
time income_50 income_75 income_25 gdp_50 gdp_75 gdp_25
-2 98 103 72 98 104 79
-1 95 100 75 98 105 79
0 94 99 73 100 105 80
1 97 101 76 101 106 82
2 98 102 79 102 107 84
*****Then I make my figures:

*for gdp*

twoway rarea gdp_75 gdp_25 time, fcolor(gs12%70) lpattern(dot)|| line gdp_50 time, lc(black) lw(medium) || line gdp_25 time, lc(gs14) lw(thin)|| line gdp_75 time,lc(gs10) lw(thin) subtitle(GDP, size(small))legend( label (1 "75th Percentile/25th Percentile") label (2 "Median"))

*for income*
twoway rarea income_75 income_25 time, fcolor(gs12%70) lpattern(dot)|| line income_50 time, lc(black) lw(medium) || line income_25 time, lc(gs14) lw(thin) || line income_75 time,lc(gs10) lw(thin) subtitle(income, size(small))legend( label (1 "75th Percentile/25th Percentile") label (2 "Median"))


I think there may be a more efficient way of doing this. Thanks!