[Tex/LaTex] wrong numbering in subfigure environment when caption is on top

cross-referencingnumberingsubfloats

I got wrong numbering with \subfigure environment when I use \ref to call a figure in the text. The problem only happens when I change caption position to the top of the figures (and yes, I need on top). Here an example:

\documentclass{article}
\usepackage{subfigure}
\begin{document}
\begin{figure}[ht]
\centering
\caption[Optional caption for list of figures]{Caption of subfigures \subref{fig:subfig1}, \subref{fig:subfig2} and \subref{fig:subfig3}}
\subfigure[Caption of subfigure 1]{
\rule{4cm}{3cm}
\label{fig:subfig1}
}
\subfigure[Caption of subfigure 2]{
\rule{4cm}{3cm}
\label{fig:subfig2}
}
\subfigure[Caption of subfigure 3]{
\rule{4cm}{3cm}
\label{fig:subfig3}
}
\label{fig:subfigureExample}
\end{figure}
Reference to figure \ref{fig:subfigureExample}. Second figure is \ref{fig:subfig2}.
\end{document}

PS: I know subfigure is obsolete but it's used many times in this document. I want to try to fix this bug instead of substitute everything by subfloat, for example.

Best Answer

This is why subfigure provides the option figtopcap which assumes that you'll use a figure caption at the top of the figure:

enter image description here

\documentclass{article}
\usepackage[figtopcap]{subfigure}
\begin{document}
\begin{figure}[ht]
  \centering
  \caption[Optional caption for list of figures]{Caption of subfigures 
    \subref{fig:subfig1}, \subref{fig:subfig2} and \subref{fig:subfig3}}

  \subfigure[Caption of subfigure 1]{
    \rule{4cm}{3cm}
    \label{fig:subfig1}
  }
  \subfigure[Caption of subfigure 2]{
    \rule{4cm}{3cm}
    \label{fig:subfig2}
  }
  \subfigure[Caption of subfigure 3]{
    \rule{4cm}{3cm}
    \label{fig:subfig3}
  }
  \label{fig:subfigureExample}
\end{figure}
Reference to figure \ref{fig:subfigureExample}. Second figure is \ref{fig:subfig2}.
\end{document}

If you only do this occasionally (and don't want a global option set during package load), you have to add \addtocounter{figure}{-1} after the \caption.


Here is an option using subcaption:

\documentclass{article}
\usepackage{subcaption}
\captionsetup[subfigure]{position=bottom,labelformat=simple,font=small}
\renewcommand{\thesubfigure}{(\alph{subfigure})}
\begin{document}
\begin{figure}[ht]
  \centering
  \caption[Optional caption for list of figures]{Caption of subfigures \subref{fig:subfig1}, \subref{fig:subfig2} and \subref{fig:subfig3}}

  \subcaptionbox{Caption of subfigure 1\label{fig:subfig1}}{%
    \rule{4cm}{3cm}%
  }
  \subcaptionbox{Caption of subfigure 2\label{fig:subfig2}}{%
    \rule{4cm}{3cm}%
  }
  \subcaptionbox{Caption of subfigure 3\label{fig:subfig3}}{%
    \rule{4cm}{3cm}%
  }
  \label{fig:subfigureExample}
\end{figure}
Reference to figure \ref{fig:subfigureExample}. Second figure is \ref{fig:subfig2}.
\end{document}