[Tex/LaTex] why subfigure doesn’t occupy the full textwidth

floatssubfloats

I have 5 subfigures with width set to be 0.2 \textwidth, I want them to be in one row, but I have to set their width smaller than 0.2 to do that.
Does anyone know the reason?
Thank you!

Best Answer

You didn't state which package you use to help create the subfigure environments: subfigure -- which is deprecated and ought not to be used anymore -- subfig, or subcaption. I'll assume you're using subcaption.

One needs to remember that TeX converts single line breaks into space tokens. Thus, if each subfigure environment is terminated with a newline directive, the total width is 5*0.2\textwidth + 4*(width of space token), which exceeds \textwidth.

You have two choices: insert a % (comment character) at the end of the first four subfigure environments (to suppress the implicit insertion of a space character) or choose a width for each subfigure that's slightly less than 0.2\textwidth. I actually prefer the second approach.

enter image description here

\documentclass{article}
\usepackage{subcaption}  
\usepackage[demo]{graphicx}
\begin{document}

\hrule  %% just to illustrate width of text block

%% Five subfigures, width 0.2\textwidth, 
%% use "%" to assure no gap,
%% set image widths to 0.95\textwidth
\begin{figure}[h!]
\begin{subfigure}{0.2\textwidth}
\centering
\includegraphics[width=0.95\textwidth]{figa}
\caption{First}
\end{subfigure}%
\begin{subfigure}{0.2\textwidth}
\centering
\includegraphics[width=0.95\textwidth]{figb}
\caption{Second}
\end{subfigure}%
\begin{subfigure}{0.2\textwidth}
\centering
\includegraphics[width=0.95\textwidth]{figc}
\caption{Third}
\end{subfigure}%
\begin{subfigure}{0.2\textwidth}
\centering
\includegraphics[width=0.95\textwidth]{figd}
\caption{Fourth}
\end{subfigure}%
\begin{subfigure}{0.2\textwidth}
\centering
\includegraphics[width=0.95\textwidth]{fige}
\caption{Fifth}
\end{subfigure}
\end{figure}

%% Five subfigures, width 0.18\textwidth, 
%% use "\hspace{\fill}" to maximize gaps,
%% set image widths to 1\textwidth
\begin{figure}[h!]
\begin{subfigure}{0.18\textwidth}
\includegraphics[width=1\textwidth]{figa}
\caption{First}
\end{subfigure}\hspace{\fill}
\begin{subfigure}{0.18\textwidth}
\includegraphics[width=1\textwidth]{figb}
\caption{Second}
\end{subfigure}\hspace{\fill}
\begin{subfigure}{0.18\textwidth}
\includegraphics[width=1\textwidth]{figc}
\caption{Third}
\end{subfigure}\hspace{\fill}
\begin{subfigure}{0.18\textwidth}
\includegraphics[width=1\textwidth]{figd}
\caption{Fourth}
\end{subfigure}\hspace{\fill}
\begin{subfigure}{0.18\textwidth}
\includegraphics[width=1\textwidth]{fige}
\caption{Fifth}
\end{subfigure}
\end{figure}

\end{document}
Related Question