# “\caption outside float” error

I am trying to have a caption in a commutative diagram using the xypic package. But it is not working. I have written the code below:

\documentclass[a4paper,12pt]{article}
\usepackage{xypic}
\begin{document}

\xymatrix{ A \ar[r] \ar[d]& B\ar[d] \\
C \ar[r]& D
}

\caption{commutative diagram}
\label{fig1}

From \ref{fig1} we...

\end{document}


Is there any way to create a caption and a cross-reference in the diagram?

• Enclosing the diagram, the caption and the label in a figure environment should do the trick. – T. Verron May 1 '13 at 17:02
• @T.Verron Maybe you want to write an answer? – Mario S. E. May 1 '13 at 22:56
• @Jubobs : Sorry for your wasted time, we were writing the same thing simultaneously. :/ – T. Verron May 1 '13 at 23:15

The problem is that you can't simply put a \caption in a document, out of nowhere. To name only one of the problems, Latex has no way of knowing what it should be the caption of. You have (at least) two solutions to overcome that issue.

The most natural, from your code, is to use a figure environment. It is the environment one usually uses for illustrations, and it comes with captions and labels.

\documentclass[a4paper,12pt]{article}
\usepackage{xypic}
\begin{document}

\begin{figure}
\xymatrix{ A \ar[r] \ar[d]& B\ar[d] \\
C \ar[r]& D
}

\caption{commutative diagram}
\label{fig1}
\end{figure}

From \ref{fig1} we...

\end{document}


Note that this solution has one big issue. The figure environment is a floating environment, which means you will never be able to position the picture exactly where you want it.

One would expect a commutative diagram to be typeset exactly where is appears in the code, I guess. But one wouldn't expect a commutative diagram to have a caption either. So, if the floating thing doesn't matter (that is, if the commutative diagram is an illustration rather than a part of the text), you can skip the second solution below.

Else, here it is. You can skip the figure environment, but you have to tell latex what the caption is for. One option is to use the \captionof environment from the caption package (this package does much more than defining this command, but that's all we need here).

\documentclass[a4paper,12pt]{article}
\usepackage{xypic}
\usepackage{caption}

\begin{document}

\xymatrix{ A \ar[r] \ar[d]& B\ar[d] \\
C \ar[r]& D
}

\captionof{figure}{commutative diagram}
\label{fig1}

From \ref{fig1} we...

\end{document}


You can find some more details in this entry of the TeX FAQ.