[Tex/LaTex] Vertically align two separate TikZ figures below each other using the subfig package

horizontal alignmentsubfloatstikz-pgf

The following minimal working example does not vertically align two rectangles drawn by TikZ. The result can be found here. Somehow the second rectangle seems bolded, but that is not the case when I open the .pdf on my PC.

I would like the two rectangles to be vertically aligned and centered (which is equivalent to both centering them). Why is the second rectangle indented?

\documentclass[a4paper]{article}

\usepackage{subfig}
\usepackage{tikz,pgfplots}\pgfplotsset{compat = 1.11}

\newcommand{\rect}{%
\begin{tikzpicture}%
\draw (0,0) rectangle (4,4);%
\end{tikzpicture}%
}%

\begin{document}%

\begin{figure}%
\centering%
\subfloat[First rectangle.]{\rect}%
\newline%
\subfloat[Second rectangle.]{\rect}%
\caption{This is a figure with two rectangles that do not horizontally align.}
\end{figure}%

\end{document}

Best Answer

The second rectangle is not indented, the first one is not really centered and this is not due to the subfig package nor to the use of figures created using TikZ.

The problem here is that, inside \centering (\raggedleft and \raggedright and similar), \newline behaves as the "normal" \\ which is basically \@normalcr\relax and this produces undesired behaviours illustrated in the example below. \centering redefines \\ (but \newline keeps its standard definition) to (essentially) \par\addvspace{-\parskip} so when using \centering (\raggedleft and \raggedright and similar) you should use \\ or \par but no \newline:

\documentclass{article}
\usepackage[showframe,a6paper]{geometry}% just for visualization purposes

\begin{document}

\noindent
\begin{minipage}{\linewidth}
\centering
Center \\
Center \par
Center?
\newline 
Center
\end{minipage}

\end{document}

enter image description here

Your example code using \par and \\:

\documentclass[a4paper]{article}
\usepackage{subfig}
\usepackage{tikz}

\newcommand\rect{%
\begin{tikzpicture}
\draw (0,0) rectangle (4,4);
\end{tikzpicture}%
}

\begin{document}

\begin{figure}
\centering
\subfloat[First rectangle.]{\rect}
\par
\subfloat[Second rectangle.]{\rect} 
\\
\subfloat[Third rectangle.]{\rect}
\caption{This is a figure with three rectangles horizontally aligned}
\end{figure}

\end{document}

The output:

enter image description here

Related Question