6

I am able to add code to a Latex document with the listings package. Here's some simple code:

\documentclass{minimal}
\usepackage{listings} 
\begin{document}

\begin{lstlisting}[language=Mathematica,caption={Simple Code}]
f1 = Cos[2*Pi*freq1*t]; 
freq = 1 + 2*t;
f2 = Cos[2*Pi*Integrate[freq, t]*t];
\end{lstlisting}

\end{document}

However, there is a problem. My thesis can only include only figures or tables. From my university's formatting guidelines:

Do not use any designation other than Figure or Table ... in the manuscript

So I want to have beautifully formatted code, but it should be "Figure 3.4" or whatever.

Is there a way to do this?

5

You can wrap the code listing in a figure environment as demonstrated below.

\documentclass{article}
\usepackage{listings} 
\begin{document}

See Figure~\ref{code.1} for my code.

\begin{figure}[hbtp]
    \caption{Code}
    \label{code.1}
    \begin{lstlisting}[language=Mathematica,frame=single]
        f1 = Cos[2*Pi*freq1*t]; 
        freq = 1 + 2*t;
        f2 = Cos[2*Pi*Integrate[freq, t]*t];
    \end{lstlisting}
\end{figure}

\end{document}

enter image description here

8
  • Yes, that works – axsvl77 Aug 9 '19 at 13:57
  • Just be careful not to use the float or caption options. – John Kormylo Aug 9 '19 at 14:21
  • im having 2 problems with this code: the referencing does not work for me and this box is not included. how do i add a box? – Britta Oct 4 '20 at 13:18
  • @Britta: Hi, I added "frame=single" to the lstlisting environment. I also added an example line demonstrating how to reference the figure. Hopefully that helps you. – James Oct 4 '20 at 21:40
  • @James, thanks for the quick reply. Ive tried it but it sadly doesn't help. I keep getting Figure ?? in my code, which is so strange... – Britta Oct 4 '20 at 22:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.