Live data from Hacker News

Tips and tricks to write LaTeX papers in with figures generated in Python

github.com

31–40 of 68 posts

Re: Tips and tricks to write LaTeX papers in with figures generated in Python

#31

I have one tip for anyone using LaTeX: Please stop using the awful Computer Modern typeface.

Any typeface in particular that you do recommend?

\usepackage{mathpazo}

Or

\usepackage[utopia]{mathdesign}

Some people like garamond (also a mathdesign font).

Re: Tips and tricks to write LaTeX papers in with figures generated in Python

#33

I find it useful to work with plots in Jupyter notebooks. Use the "%matplotlib notebook" cell magic to get interactive plots inline. Then you can use savefig when it looks good. Then save the code you used into some file near the Latex sources.

I also use this approach.

To standardize appearance I put appearance modifiers in `notebook_context/__init__.py`, and then in my second jupyter cell

  from notebook_context import *
  configure_plotting_for_publication()
Example notebook_context: https://github.com/maksimt/empirical_privacy/blob/master/src...

Re: Tips and tricks to write LaTeX papers in with figures generated in Python

#34

Having just completed a dissertation in LaTex, with figures online in Overleaf and Dropbox (some of them screenshots), scripts and data spread across two computers and an external hard drive, desperate last minute plot text changes right in the pdf, I just have to ask: WHY DIDN"T YOU POST ALL THIS SOONER?

I'm sorry ! It has been online for 4 years now, I simply never thought of sharing...

Re: Tips and tricks to write LaTeX papers in with figures generated in Python

#35
Re: figures in EPS. I think SVG is the way to go. It can be generated with matplotlib or even a simpler script (it's just an XML after all). It can be hand edited. It's viewable with a browser. And it can be converted to PDF with rsvg-convert.

I personally find matplotlib a bit unintuitive to use, so I made a 100-line script for generating SVG. It's great.

Re: Tips and tricks to write LaTeX papers in with figures generated in Python

#36
post #12

One itch which (curiously) I can't seem to quite scratch in LaTeX is that it should be possible to say "plot equation \ref{eq:smth} for X in (-4,4)" and just get the bloody graph. Why should I need to define the equation again in a separate place, perhaps even in a separate file?

LaTeX doesn't have enough information about what your notations mean. You can very well write nonsensical formulas that look pretty in LaTeX but are absolutely meaningless.

I wish I had read the texbook or something similar sooner to gain knowledge like this. Used latex for years without knowing the basics and I regret that a lot.

Also, (v)phantom and smash are something I really should have learned before all those fancy packages, nowadays I'm mostly using context anyways.

Re: Tips and tricks to write LaTeX papers in with figures generated in Python

#37
I'd also add that for figures Inkscape is invaluable [1]. Save as svg once, and export it as whatever later. I typically export it to PDF (from within Inkscape) for pdflatex.

While its typically indispensable for schematics, I often seem to run into the use case of combining previously generated plots or figures, or adding a label/text. Since Inkscape can import pngs, this is a breeze with it. I don't have to go back to the original code to regenerate plots, or fiddle around with latex to make minor adjustments.

For stuff generated via matplotlib, I'd strongly recommend seaborn as an additional library [2]. This is a wrapper over matplotlib. It can prettify plots with just an import and a 'set' command. You can, of course, use it to plot too, and for stuff doable in matplotlib using the seaborn alternative is much easier and looks better with little or no work. And they support pandas dataframes.

[1] https://inkscape.org/

[2] https://seaborn.pydata.org/

Re: Tips and tricks to write LaTeX papers in with figures generated in Python

#38

One itch which (curiously) I can't seem to quite scratch in LaTeX is that it should be possible to say "plot equation \ref{eq:smth} for X in (-4,4)" and just get the bloody graph. Why should I need to define the equation again in a separate place, perhaps even in a separate file?

This is not what you asked for, since it still requires a separate file. However it might be close enough to what you want, and -- for complicated expressions -- possibly even better.

You can write (or derive) the expression using sympy, then have sympy generate a numpy expression that can be evaluated. Sympy can also generate the LaTeX code for any expression. So while that isn't an in-LaTeX solution, it may be close to what you want.

Johansson's "Numerical Python" shows several examples of this. I will scavenge one of his examples below (trusting it falls under "fair use", and hoping I transcribe it correctly -- note I have left out the imports). The example uses sympy to generate and plot Taylor series expansions of sin(x).

The key bit to look for in the example is `sympy.lambdify()`.

    sym_x = sympy.Symbol("x")
    x = np.linspace(-2 * np.pi, 2 * np.pi, 100)

    def sin_expansion(x, n):
        return sympy.lambdify(sym_x, sympy.sin(sym_x).series(n=n+1).removeO(), 'numpy')(x)

    fig, ax = plt.subplots()
    ax.plot(x, np.sin(x), linewidth=4, color="red", label='exact')
    colors = ["blue", "black"]
    linestyles = [':', '-.', '--']

    for idx, n in enumerate(range(1, 12, 2)):
        ax.plot(x, sin_expansion(x, n), color=colors[idx // 3],
            linestyle=linestyles[idx % 3], linewidth=3,
            label="order %d approx." % (n+1))

    ax.set_ylim(-1.1, 1.1)
    ax.set_xlim(-1.5*np.pi, 1.5*np.pi)

    ax.legend(bbox_to_anchor=(1.02, 1), loc=2, borderaxespad=0.0)
    fig.subplots_adjust(right=.75)
I highly recommend the book. It's full of nuggets like this.

Re: Tips and tricks to write LaTeX papers in with figures generated in Python

#39
post #8

Earlier quoted context omitted.

I had problems using pyplot over ssh because it can assume there's a display and fail when it couldn't find one. Maybe this has changed. I use the OO interface. For example https://matplotlib.org/gallery/api/agg_oo_sgskip.html

Changing the plot backend should fix this. import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt https://stackoverflow.com/questions/2801882/generating-a-png...

I believe Agg is only for bitmap output. While there are probably backends that work with a headless system, I find the OO option much more flexible.

Re: Tips and tricks to write LaTeX papers in with figures generated in Python

#40
post #37

I'd also add that for figures Inkscape is invaluable [1]. Save as svg once, and export it as whatever later. I typically export it to PDF (from within Inkscape) for pdflatex. While its typically indispensable for schematics, I often seem to run into the use case of combining previously generated plots or figures, or adding a label/text. Since Inkscape can import pngs, this is a breeze with it. I don't have to go back…

I do this as well. And you can save svg files from matplotlib for editing or composition in Inkscape!
Post reply on HN