Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add latex figure captions below jupyter / matplotlib figures

From within the jupyter notebook, is there a way to add latex figure caption below each inline matplotlib figure? This is desired so that each figure is annotated when running nbconvert --to latex.

But I am not clear on how to position the LaTeX relative to the figure which ends up in \begin{verbatim} block. I can place it in a markdown cell just after the plot; but, that does not wrap the figure as I want.

like image 935
tnt Avatar asked Sep 30 '15 00:09

tnt


2 Answers

You can add captions by following the example at Making Publication Ready Notebooks a blog post by a Mr. Julius Schulz. The technique basically boils down to adding the caption as part of the JSON metadata for the cell in which you generate the figure and then providing the right instructions in the template you pass to nbconvert. I have directly copy pasted the section of Julius' template file which draws the figures as I am not too hot on the Jinja templates front. The blog post was very helpful for me.

like image 109
seanysull Avatar answered Oct 20 '22 17:10

seanysull


A bit of a workaround but the following helper function calls plt.close() to keep the inline figures from being displayed leaving only the generated LaTeX block for the figure.

bShowInline = True  # Set = False for document generation

def makeplot( plt, figlabel, figcaption):
    figname = figlabel+'.png'

    plt.savefig(figname)

    if bShowInline:
        plt.show()
    else:
        plt.close()

    strLatex="""
    \\begin{figure}[b]
    \centering
        \includegraphics[totalheight=10.0cm]{%s}
        \caption{%s}
        \label{fig:%s}
    \end{figure}"""%(figname, figcaption, figlabel) 
    return display(Latex(strLatex)) 

Is there a cleaner way?

like image 42
tnt Avatar answered Oct 20 '22 15:10

tnt