[Tex/LaTex] Using subcaption with graphicx: How to solve the “Missing number treated as zero” problem

graphicssubcaptionsubfloats

I'm trying to use the subcaption package to build composite figures. When I try to include an image using \includegraphics{}. I get the error beneath. I know this is very similar to Subfloat with subcaption package: Missing number, treated as zero but that question did not have an accepted answer and the proposed solution was confusing. Any clear explanations of why this problem occurs and how to fix it are very welcome. 🙂

Error:

! Missing number, treated as zero.
<to be read again> 
                   \let 
l.54 \includegraphics
                     {./Figures/For_testing/test.png}

MWE:

\documentclass{article}
\usepackage[demo]{graphicx}
\usepackage{caption}
\usepackage{subcaption}

\begin{document}

\begin{figure}
\centering
\begin{subfigure}
\includegraphics{anything}
\phantomsubcaption
\end{subfigure}
\\
\begin{subfigure}
\includegraphics{anything2}
\phantomsubcaption
\end{subfigure}
\caption{Test Caption}
\end{figure}

\end{document}

Best Answer

The subfigure and subtable environments have a mandatory argument used for the width that will be reserved; not providing this argument produces the error mentioned since LaTeX expects a length. To prevent the error, you need to provide the width for the subfigure environment using the mandatory argument:

\documentclass{article}
\usepackage[demo]{graphicx}
\usepackage{caption}
\usepackage{subcaption}

\begin{document}

\begin{figure}
\centering
\begin{subfigure}{\linewidth}
\centering
\includegraphics{anything}
\phantomsubcaption
\end{subfigure}\\
\begin{subfigure}{\linewidth}
\centering
\includegraphics{anything2}
\phantomsubcaption
\end{subfigure}
\caption{Test Caption}
\end{figure}

\end{document}

The subfigure and subtable environments have the same optional and mandatory arguments of a minipage, so the syntax is:

\begin{subfigure}[<pos>][<height>][<inner-pos>]{<width>}
...
\end{subfigure}

where <pos> is the vertical positioning with respect to the baseline (possible values: c (center), b (bottom), t (top)); <height> is a length controlling the height reserved for the contents, and <inner-pos> determines the position of the contents (possible values: c , b, t).