'Can I integrate MathJax into a Python program?
This might be a silly question, but is it possible to merge MathJax into Python code? Many times I've wished the program output would look more neat, and honestly MathJax looks awesome.
I know MathJax runs on Javascript, yet I have not given up hope. If the answer is no, are there some simple modules to use instead?
For example, if:
1.234 / e^23 [and] (I^-)_(aq) +I _(2(s)) -> (I^-)_3(aq)
could be formatted as:
that would be ideal.
Solution 1:[1]
I can only presume that maybe you want to output something to the display for printing. Hence the common usage in Python is probably Matplotlib (albeit Gnuplot is a good alternative that is python compatible). If you create a blank plot using Matplotlib then you can input normal plain LaTeX maths instructions (near identical to MathJax):
A small example:
import matplotlib
matplotlib.use('TkAgg')
import pylab
import matplotlib.pyplot as plt
from matplotlib import rc
plt.clf()
plt.rc('text', usetex=True)
plt.rcParams["figure.figsize"] = (8, 5)
plt.rc('font', **{'family':'serif', 'serif':['Computer Modern Roman'], 'size': 16})
plt.axis("off")
plt.text(0.5, 0.5, "Maths $e = mc^2$")
gives the following output
which can trivially be saved, as a .pdf, and then the apparent graininess of my screenshot is removed.
Solution 2:[2]
Following the answer of oliversm, one can use the class mathtext of mathplotlib:
from matplotlib import mathtext, font_manager
import matplotlib as mpl
mpl.rcParams['savefig.transparent'] = True
#texFont = font_manager.FontProperties(size=30, fname="./OpenSans-Medium.ttf")
texFont = font_manager.FontProperties(size=30, family='serif', math_fontfamily='cm')
mathtext.math_to_image(r"Maths $e = mc^2$", "output.png", prop=texFont, dpi=300, format='png')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | oliversm |
| Solution 2 |


