[Tex/LaTex] How to use figure inside a minipage

floatsgraphicsminipage

I'm trying to include an image, and keep it centered, and prevent from wrapping from the next page. The following code works for that:

\begin{minipage}{\textwidth}
    \begin{center}
        Caption for image

        \includegraphics[scale=0.5]{myimage.png} 
    \end{center}
\end{minipage}

I'd like this image to be in a figure, with a caption. The following doesn't compile:

\begin{minipage}{\textwidth}
    \begin{figure}
        \includegraphics[scale=0.5]{myimage.png}
        \caption{Caption for image}
        \label{fig:sample_figure}
    \end{figure}
\end{minipage}

I get the errors:

! LaTeX Error: Not in outer par mode.
! Undefined control sequence.

How can I fix this?

Best Answer

Figure is a floating environment and minipage is, unfortunately, not. Therefore, if you put a floating object inside a non-floating minipage, you will get an error. But the other way around is possible--you can put a minipage inside a figure environment:

\begin{figure}
\centering
\begin{minipage}[c]{\textwidth}
\centering
    \includegraphics[width=3.0in]{example-image-a}
    \caption{Caption for image}
    \label{fig:sample_figure}
\end{minipage}
\end{figure}

Another method is to avoid using figure entirely. This can be done with help of the caption package (with its captionof facility, so that you can have a caption for the figure):

.....in preamble
\usepackage{caption}

......in document body

\begin{minipage}[c]{\textwidth}
\centering
\includegraphics[width=3.0in]{example-image-a}
\captionof{figure}{Caption for image}
\label{fig:sample_figure}
\end{minipage}

The total mwe will be:

\documentclass{article}
\usepackage{mwe} % new package from Martin scharrer
\usepackage{caption}
\begin{document}

 \begin{figure}
 \centering
 \begin{minipage}[c]{\textwidth}
 \centering
        \includegraphics[width=3.0in]{example-image-a}
        \caption{Caption for image}
        \label{fig:sample_figure}
 \end{minipage}
 \end{figure}

 \noindent
\begin{minipage}[c]{\textwidth}
\centering
        \includegraphics[width=3.0in]{example-image-a}
        \captionof{figure}{Caption for image}
        \label{fig:sample_figure}
 \end{minipage}

\end{document}

The result will be:

enter image description here