[Tex/LaTex] How to refer to label created by new command

cross-referencingmacros

I have several pairs of graphs. I need to display these graphs in latex. I am using the following which works Great.

\begin{figure}
  \centering
  \begin{subfigure}{.5\textwidth}
    \centering
    \fbox{\includegraphics[width=.8\linewidth]{4-byVar1.png}}
    \caption{``Here's a question?'' (by Var1)}
    \label{fig:4-byVar1}
  \end{subfigure}%
  \begin{subfigure}{.5\textwidth}
    \centering
    \fbox{\includegraphics[width=.8\linewidth]{4-byVar2.png}}
    \caption{``Here's a question?'' (by Var2)}
    \label{fig:4-byVar2}
  \end{subfigure}
  \caption{``Here's a question?''}
  \label{fig:comboFig-4}
\end{figure}

However, that's a lot of code to repeat for each such pair of figures. I created a

\newcommand

to do the work for me, but it seems that when I try to ref a figure created by my newcommand, i get an error (fig undefined).

Can anyone recommend how I can refer to a label created by a newcommand?

The newcommand I created looks like this

\newcommand{\graphPairs}[2]{
  \begin{figure}
    \centering
    \begin{subfigure}{.5\textwidth}
      \centering
      \fbox{\includegraphics[width=.8\linewidth]{#2-byCar1.png}}
      \caption{#1 (by Var 1)}
      \label{fig:#2-byVar1}
    \end{subfigure}%
    \begin{subfigure}{.5\textwidth}
      \centering
      \fbox{\includegraphics[width=.8\linewidth]{#2-byVar2.png}}
      \caption{#1 (by Var 2)}
      \label{fig:#2-byVar2}
    \end{subfigure}
    \caption{#1}
    \label{fig:comboFig-#2}
  \end{figure}
}

Best Answer

It does not matter, that \label is hidden in a \newcommand. For referencing you need the label name that depends on the second argument of \graphPairs. The first example would be generated by:

\graphPairs{``Here's a question?''}{4}

And the labels can be referenced by

\ref{fig:4-byVar1}
\ref{fig:4-byVar2}
\ref{fig:comboFig-4}
Related Question