How to add latex figure captions below jupyter / matplotlib figures - latex

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.

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.

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?

Related

Render latex preview of equation like in latex export (with preceeding/trailing newline)

I am struggling with latex preview in org-mode.
Basically I am trying to preview someting like this:
* Section2
\[
X=\frac{1}{2}
\]
In general this works, but the overlay image does not contain preceeding/trailing newlines before/after the math environment. Full latex export however would introduce these newlines.
In addition I use the following options in my header in order to keep the original org spacing in my pdf:
#+OPTIONS: \n:t
The combination of employed header and fragment mismatch, however, either messes up readability of my org file, i.e. the preview fragment is put too close to the heading "Section2". Or, when I insert a new line in org, in order to increase the readability, the spacing of my latex export looks strange, due to this extra line plus the preceeding/trailing lines from the math environment.
Can someone give me a hint how I can convince org-mode to create the fragment in accordance with the full latex export?
I am using emacs 26.3 with miktex.
Thanks,
Daniel

latex \vec accent misplaced in jupyter markdown / mathjax

I'm a long-time latex user just learning to use jupyter notebooks. I've noticed that whenever I try to create latex-formatted equations in a markdown cell, the vector accents (created with "\vec{...}") are badly misplaced -- they show up way to the right of the character they are supposed to be accenting.
This seems like it must be a known/solved issue (probably an issue with MathJax, which I guess is what jupyter is using to process the latex?) but I couldn't find an answer anywhere. Indeed, searching around for an explanation/fix, I found a number of pages that explain how to create latex-formatted equations in mathjax/markdown that show (without identifying that it is a problem!) this misplacement, e.g.:
https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference (see the "\vec{x}" under accents near the bottom of the page)
http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Typesetting%20Equations.html (see Maxwell's equations)
http://data-blog.udacity.com/posts/2016/10/latex-primer/ (see again the "\vec{x}" under accents)
Why are the vector accents mis-placed like this, and how can this be fixed?
Any help appreciated!

Loading AMSmath explicitly in IPython notebook causes "[Math Processing Error]"

I am a relatively new IPython Notebook user and I am using IPython 3.2.1. So upfront, my apologies if I did not read some documentation carefully!
I am trying to typeset some LaTeX in my Notebook intended for a presentation. I tried to utilize MathJax capabilities better than what's (supposedly) available by default and so tried incorporating other extensions that come with MathJax explicitly. In particular, I tried getting my IPython Notebook to load AMScd.js, AMSsymbols.js and unicode.js through the following sequence of steps:
Obtain the .js files for these extensions from the latest MathJax (v2.5) source
Add them to my ~/.ipython/nbextensions
Modify custom.js in ~/.ipython/profile_<mine>/static/custom by appending IPython.load_extensions("AMScd"), etc.
Now, all these work fine, and I am able to typeset commutative diagrams nicely in my IPython notebook. So, while at all this, I decided to also include/load AMSmath.js that comes along with MathJax and this is problematic. (To me, this seems like a natural thing to do given that other extensions work well!) However, attempting to include AMSmath.js via IPython.load_extensions("AMSmath") causes LaTeX math in my Notebook to display [Math Processing Error] everywhere. Here's my minimal example and the output with and without including IPython.load_extensions("AMSmath").
Markup:
## A minimal working example
\\[
\Delta u = f \text{ on } \Omega
\\]
(I would totally like to include images here, alas, my not being an active participant in the community here leaves me with not even 10 reputation!)
So, what am I missing here? Why is this inclusion of AMSmath problematic? Any help would be appreciated! Thanks!
It should work without extra configuration. Have a look here.
Your example in a markdown cell should be
(If you want the equation inline you can use $...$)
Inline equation $\Delta u = f \text{ on } \Omega$
(Or if you want the equation centered in their own line you can use $$...$$)
$$\Delta u = f \text{ on } \Omega$$
The result of both snippets in the same markdown cell is rendered as:
How it is loaded?
IPython/Jupyter notebook preloads some MathJax extensions including the extension you want to load. This extension is not an IPYthon/Jupyter extension so it shouldn't work if you try to load this MathJax extension as an IPython/Jupyter extension. See here to know more about how to load other MathJax extensions.

How to fit the paper-size to the content in LaTeX

I'd like to create a pdf/ps/eps that contains only one single formula.
I thought the easiest way would be to use latex.
Unfortunately, I found no option to specify, that the paper-size should automatically be set to fit the contents.
I found that dvipng has a "-T tight" option, that actually does the trick, but...
I want it in vector-graphics format.
Any suggestions?
Thanks.
With the standalone class, you get exactly what you want.
\documentclass{standalone}
\begin{document}
\[
x + y = z
\]
\end{document}
Try pdfcrop, it crops your pdf to the minimum. You need to have Perl installed.
for Mac, there is a little app called LaTeXit which does exactly that. http://chachatelier.fr/programmation/latexit_en.php
Fixing the bounding box of generated EPS should help:
epstopdf --gsopt=-dEPSCrop blah.eps
or eps2pdf has a -B option that detects the tightest possible Bounding Box.
Somewhat perversely, you can generate your Tex using Metapost: include your formula between btex and etex tags, and compile it following the instructions in either mptopdf(1) (prefered, part of pdftex) or mpost(1) (you'll need to run Tex separately as well, I think). It is perverse to invoke Metapost just to have it invoke Tex, but it you will get formula-sized output without any evil pdf hackery.
If you need any Latex (as opposed to plain Tex), then you need a bit of boilerplate to get this to work, cf. LaTeX labels in MetaPost.

How to customize an existing LaTeX environment without interfering with other environments?

I'm using Sphinx for documenting a project. It produces LaTeX files from reStructuredText.
I would like to set a gray background color to the tips and notes, so I customized the notice environment after creating a graybox environment:
\definecolor{MyGray}{rgb}{0.80,0.80,0.80}
\makeatletter\newenvironment{graybox}{%
\begin{lrbox}{\#tempboxa}\begin{minipage}{\columnwidth}}{\end{minipage}\end{lrbox}%
\colorbox{MyGray}{\usebox{\#tempboxa}}
}\makeatother
\makeatletter
\renewenvironment{notice}[2]{
\begin{graybox}
\bf\it
\def\py#noticetype{#1}
\par\strong{#2}
\csname py#noticestart##1\endcsname
}
{
\csname py#noticeend#\py#noticetype\endcsname
\end{graybox}
}
\makeatother
Everything works fine except if I place a figure environment inside the notice environment. In that case, I get this error:
LaTeX Error: Not in outer par mode
Is there a way to set a gray background to that notice environment ?
This is a FAQ. It does not make sense to put a figure (or any other "float" which can move elsewhere in the output) inside a gray box; if you want your figure to contain a gray box, put the gray box environment inside the figure environment.
Thank you godbyk and Jouni for answering my question.
The problem is that I don't code directly in LaTeX. I write the documentation in restructured text and Sphinx output the LaTeX files.
But I found a solution: I redefine the figure environment to use the staticfigure from the flowfram package:
\usepackage{flowfram}
\definecolor{MyGray}{rgb}{0.80,0.80,0.80}
\makeatletter\newenvironment{graybox}{%
\begin{lrbox}{\#tempboxa}\begin{minipage}{\columnwidth}}{\end{minipage}\end{lrbox}%
\colorbox{MyGray}{\usebox{\#tempboxa}}
}\makeatother
\makeatletter
\renewenvironment{notice}[2]{
\begin{graybox}
\bf\it
\def\py#noticetype{#1}
\par\strong{#2}
\csname py#noticestart##1\endcsname
}
{
\csname py#noticeend#\py#noticetype\endcsname
\end{graybox}
}
\makeatother
\renewenvironment{figure}[6]{
\begin{staticfigure}
}{
\end{staticfigure}
}
PS: I had to put 6 to the number of arguments when redefining 'figure': if I don't do that it outputs some 'htbp' in the pdf files (I'm not a LaTeX expert. it's just the solution I found for this problem)
As Jouni correctly pointed out, figures and tables (i.e., floats) can be moved around, and your gray box can't contain them. To achieve the desired effect, you have two options:
Put your entire notice into a figure environment (so that the entire notice can be floated around on the page or to a new page if LaTeX so chooses).
Don't use a float (figure environment) -- just use \includegraphics to pop your image directly into the notice environment. You won't be able to use a caption with this non-figure, however, as captions only work inside a figure or table environment. If you want a caption associated with this image, you can use the caption package:
\documentclass{article}
\usepackage{caption}% let's us use captions outside of floats
\usepackage{lipsum}% provides filler text
\begin{document}
\lipsum[1]
\begin{center}
\includegraphics{mypic}
\captionof{figure}{This is my picture.}% makes a caption for non-floats
\label{fig:mypic}
\end{center}
\lipsum[2]
\end{document}
I haven't used Sphinx, so I'm afraid I can't help you too much with integrating this into their output.

Resources