I was having trouble with ordering the legend in a graph with two y-axes. I couldn't find anything on this forum that addresses this issue. I resolved it. Read on if you have the same weird problem.
I expected this to be correct. scatter of mpg mean is key 3 in the list, rspike of mpg CI is key 1 in the list.
But it doesn't match up:

Solution:
Index the keys first only among the first axis from top to bottom.
Then index the keys only among the second axis from top to bottom.

Code:
sysuse auto, clear
set scheme stmono2
local path_output_figures "C:\Users\reddinjl\Desktop\"
local opt_rspike_a "lcolor(ebblue%40) msymbol(none) lw(thick)"
local opt_rspike_b "lcolor(purple%40) msymbol(none) lw(thick)"
local opt_scatter_a "mcolor(ebblue) msymbol(circle)"
local opt_scatter_b "mcolor(purple) msymbol(X)"
local graph_opt_png_sm "width(640)"
local graph_opt_png_lg "width(1280)"
local jitter_mag 0.1
collapse ///
(mean) mpg_mean = mpg ///
(semean) mpg_se = mpg ///
(mean) displacement_mean = displacement ///
(semean) displacement_se = displacement ///
, by(foreign)
gen mpg_h = mpg_mean + 1.96*mpg_se
gen mpg_l = mpg_mean - 1.96*mpg_se
gen displacement_h = displacement_mean + 1.96*displacement_se
gen displacement_l = displacement_mean - 1.96*displacement_se
* Jitter the x-position
gen mpg_x = foreign - `jitter_mag'
gen displacement_x = foreign + `jitter_mag'
twoway ///
rspike mpg_h mpg_l mpg_x, `opt_rspike_a' ///
|| rspike displacement_h displacement_l displacement_x, `opt_rspike_b' yaxis(2) ///
|| scatter mpg_mean mpg_x, `opt_scatter_a' ///
|| scatter displacement_mean displacement_x, `opt_scatter_b' yaxis(2) ///
legend(order(3 "mpg mean" 1 "mpg 95% CI" 4 "displacement mean" 2 "displacement 95% CI") pos(6) cols(1) al(middle) region(lcolor(black))) ///
xlabel(0 "Domestic" 1 "Foreign") xti("")
graph export "`path_output_figures'graphic0.png", replace `graph_opt_png_lg'
But it doesn't match up:
Solution:
Index the keys first only among the first axis from top to bottom.
Then index the keys only among the second axis from top to bottom.
Code:
twoway ///
rspike mpg_h mpg_l mpg_x, `opt_rspike_a' ///
|| rspike displacement_h displacement_l displacement_x, `opt_rspike_b' yaxis(2) ///
|| scatter mpg_mean mpg_x, `opt_scatter_a' ///
|| scatter displacement_mean displacement_x, `opt_scatter_b' yaxis(2) ///
legend(order(2 "mpg mean" 1 "mpg 95% CI" 4 "displacement mean" 3 "displacement 95% CI") pos(6) cols(1) al(middle) region(lcolor(black))) ///
xlabel(0 "Domestic" 1 "Foreign") xti("")
graph export "`path_output_figures'graphic2.png", replace `graph_opt_png_lg'
