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?
Best Answer
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.Your MWE would become:
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 thecaption
package (this package does much more than defining this command, but that's all we need here).So, your example becomes:
You can find some more details in this entry of the TeX FAQ.