2

I want to use the nice answer to the similar question How to Label and Caption a Tikzpicture inside a tabular environment. The problem is I want two pictures side by side, with a caption for each. I duplicate the MWE to get:

\documentclass{article}
\usepackage{tikz}
\usepackage{caption}
\begin{document}
\listoffigures
\bigskip
\section*{Test table}
\begin{tabular}{lp{4cm}}
   \begin{tikzpicture}
         \draw [red](0,0) -> (4,0);
   \end{tikzpicture}
   \captionof{figure}{Picture 1}
   \label{tikz1}
&
   \begin{tikzpicture}
         \draw (0,0) -> (4,0);
   \end{tikzpicture}
   \captionof{figure}{Picture 2}
   \label{tikz2}
\end{tabular}

\

See fig. \ref{tikz1} and  \ref{tikz2}.
\end{document}

but this does not compile, the error is

(./captnof.lof) ! You can't use `\hrule' here except with leaders. \caption@hrule ->\hrule @height \z@
l.12 \captionof{figure}{Picture 1}

Once the line

\captionof{figure}{Picture 1}

is commented out, it does. So the

\captionof

works for the right picture but not for the left one! Is there a way around?

c05772
  • 864
  • 6
  • 15

1 Answers1

2

The \captionof command requires one to specify the text width. So an ad hoc solution is to set the column type of the left column also to p. However, this requires us to know how the column will be. Since you are using tikz, there is an arguably better solution: let tikz measure the picture and adjust the text width accordingly. Both solutions are contained in the following MWE.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\tikzset{caption/.style={insert path={
let \p1=($(current bounding box.east)-(current bounding box.west)$) in
(current bounding box.south) node[below,text width=\x1-4pt,align=center] 
{\captionof{figure}{#1}}}}}
\usepackage{caption}
\begin{document}
\listoffigures
\bigskip
\section*{Test table}
\begin{tabular}{p{4cm}p{4cm}}
   \begin{tikzpicture}
         \draw [red](0,0) -> (4,0);
   \end{tikzpicture}
   \captionof{figure}{Picture 1}
   \label{tikz1}
&
   \begin{tikzpicture}
         \draw (0,0) -> (4,0);
   \end{tikzpicture}
   \captionof{figure}{Picture 2}
   \label{tikz2}
\end{tabular}

See figs.~\ref{tikz1} and  \ref{tikz2}.

\bigskip

\begin{tabular}{cc}
  \begin{tikzpicture}
         \draw [red](0,0) -> (4,0);
         \path[caption={Picture 3.\label{tikz3}}];
   \end{tikzpicture}  
&
   \begin{tikzpicture}
         \draw (0,0) -> (4,0);
         \path[caption={Picture 4.\label{tikz4}}];
   \end{tikzpicture}
\end{tabular}

See figs.~\ref{tikz3} and  \ref{tikz4}.
\end{document}

enter image description here