[Tex/LaTex] \hat with \bar in subscript when using amsmath

subscripts

I want to have the variance symbol (sigma squared) with an {X with bar} in the subscript and a hat on top of everything. The following code produces a mess (The X is not subscripted). Can anyone tell me why? (Using \overline instead of \bar is not an option.)

\documentclass{standalone}

\usepackage{amsmath}

\begin{document}

$\hat{\sigma^2_{\bar{X}}}$

\end{document}

X aligned with sigma

Best Answer

I can't explain why the problem arises in the first place, but one solution is to box the initial item, and apply the \hat at the end. I also provide a 2nd alternative where I apply the \hat only to the \sigma; that may be preferable.

\documentclass{article}
\usepackage{amsmath}
\begin{document}
$
\setbox0=\hbox{$\sigma^2_{\bar{X}}$}
\hat{\box0}
$
$\setbox0=\hbox{$\hat\sigma$}\box0^2_{\bar{X}}$
\end{document}

enter image description here

If one wanted the first approach, but with a really wide hat, my answer at Really wide hat symbol might be applicable:

\documentclass{article}
\usepackage{scalerel,stackengine}
\stackMath
\newcommand\reallywidehat[1]{%
\savestack{\tmpbox}{\stretchto{%
  \scaleto{%
    \scalerel*[\widthof{\ensuremath{#1}}]{\kern-.6pt\bigwedge\kern-.6pt}%
    {\rule[-\textheight/2]{1ex}{\textheight}}%WIDTH-LIMITED BIG WEDGE
  }{\textheight}% 
}{0.5ex}}%
\stackon[1pt]{#1}{\tmpbox}%
}
\usepackage{amsmath}
\begin{document}
$
\reallywidehat{\sigma^2_{\bar{X}}}
$
\end{document}

enter image description here