[Tex/LaTex] Cross reference figure appears as “??”

cross-referencing

I'm using Texmaker for a report and am fairly new to latex.

My cross referenced equations seem to appear just fine, but not my figures. I've labelled them and referenced the label using ref. I ran PDFLatex, then BibTex, then PDFLatex again, then Quick Build, but I keep getting "??"

\documentclass{article}

\usepackage{cite}
\usepackage{harvard}
\usepackage{url}
\renewcommand{\harvardurl}[1]{\textbf{URL:} \url{#1}}
\usepackage{caption}
\usepackage{mathtools}
\citationmode{abbr}
\citationstyle{dcu}
\begin{document}


\section{Results\label{results}}{}
\subsection{Measuring Detection Rate\label{detection}}{}
\subsubsection{Cross-correlation\label{crosscorrdetect}}

{
\begin{figure}[h]
    \begin{centering}
        \includegraphics[width=\textwidth]{corrDetectTest.png}
        \caption{This is the $CrossCorrelation.h5$. $2$ is the value}
    \end{centering}
    \label{corrdetectdiag}
\end{figure}
}

{\ref{corrdetectdiag} shows the resulting...} 

\newpage
\bibliographystyle{dcu}
\bibliography{BIB_FILE}
\end{document}

I liked how math mode formats the text, so I used it every time I mention a file name, value, or equation.

Best Answer

I suggest loading the cleveref package, then using the command \cref{} which automatically adds fig. to the referred image number. You can also choose between these options:

  • noabbrev, it will change fig. to figure. It must be added as an option to the package. I would advise in favour of this option in case you plan to start a sentence with Figure and not Fig.
  • capitalise (or capitalize) will set all references with a capital letter (so Figure), used the same way as above.
  • Alternatively, you can select which is capitalised and which is not, by using \cref for lowercase, and \Cref for uppercase. See example:

Output

figure 1

Code

\documentclass{article}
\usepackage{cite}
\usepackage{harvard}
\usepackage{url}
\usepackage{caption}
\usepackage{mathtools}
\usepackage[noabbrev]{cleveref}

\citationmode{abbr}
\citationstyle{dcu}
\renewcommand{\harvardurl}[1]{\textbf{URL:} \url{#1}}

\begin{document}
\section{Results\label{results}}{}
\subsection{Measuring Detection Rate\label{detection}}{}
\subsubsection{Cross-correlation\label{crosscorrdetect}}

\begin{figure}[h]
    \centering
        \includegraphics[width=\textwidth]{example-image-a}
        \caption{This is the $CrossCorrelation.h5$. $2$ is the value}
    \label{corrdetectdiag}
\end{figure}

\Cref{corrdetectdiag} shows the resulting...\\

\cref{corrdetectdiag} shows the resulting...

\newpage
\bibliographystyle{dcu}
\bibliography{BIB_FILE}
\end{document}
Related Question