Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render equation to .png file using Python

I want to render equations to PNG files and embed them in the HTML documentation of my library. I am already using pylab (matplotlib) in other projects.

I have not found any clues in http://matplotlib.sourceforge.net/users/usetex.html and http://matplotlib.sourceforge.net/users/mathtext.html

When I do

plt.title(r'$\alpha > \beta$')
plt.show()

I get a titled empty figure with axes.

Update:

After doing some research I found, that the easiest way of rendering LaTeX to png is using mathext ( http://code.google.com/p/mathtex/ ).

Suprisingly, I had all requiered libraries to build it from source.

Anyway, thanks to everyone for replies.

Update 2:

I did some testing of mathtex and found it does not support matrices (\begin{pmatrix}) and some other things I need. So, I'm going to install LaTex (MikTeX).

Update 3:

I installed proTeXt. It's huge, but easy-to-use and fast. IMHO, for now it's the only way of rendering equations.

like image 596
peterdemin Avatar asked Mar 22 '12 07:03

peterdemin


3 Answers

This worked for me:

# https://gist.github.com/tonyseek/95c90638cf43a87e723b

from cStringIO import StringIO

import matplotlib.pyplot as plt

def render_latex(formula, fontsize=12, dpi=300, format_='svg'):
    """Renders LaTeX formula into image.
    """
    fig = plt.figure(figsize=(0.01, 0.01))
    fig.text(0, 0, u'${}$'.format(formula), fontsize=fontsize)
    buffer_ = StringIO()
    fig.savefig(buffer_, dpi=dpi, transparent=True, format=format_, bbox_inches='tight', pad_inches=0.0)
    plt.close(fig)
    return buffer_.getvalue()

if __name__ == '__main__':
    image_bytes = render_latex(
        r'\theta=\theta+C(1+\theta-\beta)\sqrt{1-\theta}succ_mul',
        fontsize=10, dpi=200, format_='png')
    with open('formula.png', 'wb') as image_file:
        image_file.write(image_bytes)
like image 84
warvariuc Avatar answered Oct 14 '22 01:10

warvariuc


  • (source) If you are using IPython interpreter, it renders all single matplotlib step into a figure window by default.

    Thus, plt.title(r'$\alpha > \beta$') in IPython would immediately create a figure even before calling .show(). On the other hand, using terminal/cmd/IDLE won't.

  • plt.show() would create a figure window whether you're using IPython or not, you want to change that line to:

    plt.savefig('filename.png')
    

Edit: Okay, I misunderstood your question. As @Li-aung Yip said, you may want to use Sympy for pure equation image. We can still do some trick in matplotlib to achieve what you want though (you may need to readjust or resize accordingly):

import matplotlib.pyplot as plt

#add text
plt.text(0.01, 0.8, r'$\alpha > \beta$',fontsize=50)

#hide axes
fig = plt.gca()
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.draw() #or savefig

This is done by hiding axes ticks and adding text inside the plot figure.

But...this doesn't really "not drawing" a figure :\ Though you can post-process such as cropping the image with PIL.

like image 22
EwyynTomato Avatar answered Oct 14 '22 03:10

EwyynTomato


It sounds like you want to render LaTeX equations to images. See linked question for a variety of ways of doing this with minimal dependencies. (Some even involve matplotlib, I believe.)

Alternately, if you can install LaTeX or rely on LaTeX being installed, you can just use LaTeX itself to render the equation to postscript and thence into an image format.

like image 37
Li-aung Yip Avatar answered Oct 14 '22 02:10

Li-aung Yip