How can I hide a figure but keep its numbering?

It would be best to put these possibly-invisible figures inside their own environment. That way you can control how they are managed. Below I suggest something like conditionalfigure together with \hidefigurestrue to hide them, or \hidefiguresfalse (the default) to keep them in the document.

enter image description here

\documentclass{article}

\usepackage{graphicx,environ}

\newsavebox{\figsavebox}% Box to capture figure content

\newif\ifhidefigures % Conditional to hide figures or keep them in the document

\NewEnviron{conditionalfigure}[1][ht]{%
  \ifhidefigures
    % Hide this figure
    \let\oldlabel\label
    \renewcommand{\label}[1]{\gdef\labelname{##1}}% Store label name
    \renewcommand{\caption}[1]{##1}% Make \caption just print its argument
    \begin{lrbox}{\figsavebox}
      \BODY % Capture enture figure body
    \end{lrbox}
    \refstepcounter{figure}\oldlabel{\labelname}% Step counter with reference and mark with label
  \else
    % Traditional figure environment
    \begin{figure}[#1]
      \BODY
    \end{figure}
  \fi
}

\begin{document}

\hidefigurestrue % Remove conditional figures from document
%\hidefiguresfalse % Keep conditional figures in document (default)

Figure \ref{figure1} shows \ldots

\begin{conditionalfigure}[ht]
  \centering
  \includegraphics[width=5cm]{example-image-a}
  \caption{\label{figure1}}
\end{conditionalfigure}

Figure \ref{figure2} shows \ldots

\begin{figure}[ht]
    \centering
    \includegraphics[width=5cm]{example-image-b}
    \caption{\label{figure2}}
\end{figure}

\end{document}

Capturing the entire conditionalfigure contents ensures that it doesn't impede with the placement of floats within the document, otherwise the "invisible" float may still take up space above/below it.


Is this what you are looking for? Using resizebox and minipage you can make the includegraphics and caption have zero height.

enter image description here

\documentclass{article}
\usepackage{graphicx}

\begin{document}

Figure \ref{figure1} shows \ldots

\begin{figure}[ht]
    \centering
    \resizebox{!}{0cm}{\begin{minipage}{\textwidth}
    \includegraphics[width=5cm]{example-image-a}
    \caption{}
    \label{figure1}
    \end{minipage}}
\end{figure}

Figure \ref{figure2} shows \ldots

\begin{figure}[ht]
    \centering
    \includegraphics[width=5cm]{example-image-b}
    \caption{}
    \label{figure2}
\end{figure}

\end{document}