Skip to content

Instantly share code, notes, and snippets.

@ahwillia
Last active March 31, 2020 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahwillia/c7e54f875913ebc3de3852e9f51ccc69 to your computer and use it in GitHub Desktop.
Save ahwillia/c7e54f875913ebc3de3852e9f51ccc69 to your computer and use it in GitHub Desktop.
Plot a LaTeX equation as a matplotlib figure
# Majority of credit goes to Chris Holdgraf, @choldgraf, and this StackOverflow
# post: http://stackoverflow.com/questions/5320205/matplotlib-text-dimensions
import pylab as plt
import numpy as np
def plot_equation(eq, fontsize=50, outfile=None, padding=0.1, **kwargs):
"""Plot an equation as a matplotlib figure.
Parameters
----------
eq : string
The equation that you wish to plot. Should be plottable with
latex. If `$` is included, they will be stripped.
fontsize : number
The fontsize passed to plt.text()
outfile : string
Name of the file to save the figure to.
padding : float
Amount of padding around the equation in inches.
Returns
-------
ax : matplotlib axis
The axis with your equation.
"""
# clean equation string
eq = eq.strip('$').replace(' ', '')
# set up figure
f = plt.figure()
ax = plt.axes([0,0,1,1])
r = f.canvas.get_renderer()
# display equation
t = ax.text(0.5, 0.5, '${}$'.format(eq), fontsize=fontsize,
horizontalalignment='center',verticalalignment='center')
# resize figure to fit equation
bb = t.get_window_extent(renderer=r)
w,h = bb.width/f.dpi,np.ceil(bb.height/f.dpi)
f.set_size_inches((padding+w,padding+h))
# set axis limits so equation is centered
plt.xlim([0,1])
plt.ylim([0,1])
ax.grid(False)
ax.set_axis_off()
if outfile is not None:
plt.savefig(outfile, **kwargs)
return ax
@ahwillia
Copy link
Author

plot_equation('x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}',outfile='test',padding=0.1)

test

@mvww11
Copy link

mvww11 commented Mar 31, 2020

Very valuable for me. Thank you very much!
Is it possible to set DPI resolution?

@ahwillia
Copy link
Author

Yes, I just slightly modified the code to take **kwargs and pass them to savefig.

So you should be able to do plot_equation(..., outfile="test.png", dpi=500).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment