28

How to show an easy latex-formula in python? Maybe numpy is the right choice?

I have python code like:

a = '\frac{a}{b}'

and want to print this in a graphical output (like matplotlib).

6
  • What do you mean 'show latex formula in python'. Do you want to extract a formula from a .tex file and print it to python's stdout, implement a formula shown in a a .tex (pdf/ps) file in python or what?
    – Matti Lyra
    Commented Oct 26, 2010 at 21:46
  • Can you clarify? Where do you want to print it? Do you want to generate images or are you looking for something inside a gui?
    – Wolph
    Commented Oct 26, 2010 at 21:47
  • sorry for the unclear question. :/ Please see the edit.
    – kame
    Commented Oct 26, 2010 at 21:56
  • See the docs on the matplotlib site: - Text rendering With LaTeX
    – ars
    Commented Oct 26, 2010 at 22:07
  • 1
    Possible duplicate of How to programmatically generate markdown output in Jupyter notebooks?
    – Paul Wintz
    Commented Nov 28, 2018 at 20:21

7 Answers 7

22

As suggested by Andrew little work around using matplotlib.

import matplotlib.pyplot as plt
a = '\\frac{a}{b}'  #notice escaped slash
plt.plot()
plt.text(0.5, 0.5,'$%s$'%a)
plt.show()
2
  • Can someone explain line 3 to me? Is the semi-colon just a typo?
    – AnnanFay
    Commented Dec 12, 2014 at 17:13
  • @Annan The semicolon is just separates two lines. You may just as well put plt.text(0.5,0.5,'$%s$'%a) on a new line.
    – ostrokach
    Commented Mar 11, 2015 at 12:32
21

An answer based on this one specific to Jupyter notebook, using f-string to format an $x_i$ variable:

from IPython.display import display, Latex
for i in range(3):
    display(Latex(f'$x_{i}$'))

Screenshot of the output

Note: The f-string (formatted string literal) uses curly braces to insert the value of the Python variable i. You’ll need to double the curly braces (f'{{}}') to actually use {} in the LaTeX code. Otherwise, you can use single curly braces directly in a normal Python string (not an f-string).

Side Note: I'm surprised Stack Overflow still doesn’t have a math markup.

3
  • In my opinion, this should be the answer. Clear and concise
    – smellerbee
    Commented Jun 20, 2020 at 1:35
  • 1
    On my end it shows "<IPython.core.display.Latex object>". Is that a bug or am I missing to enable something. (I'm on MacOS) Commented May 24, 2022 at 4:15
  • 3
    @Shaheerziya maybe because you are not inside a jupyter notebook or lab? Are you executing the code at a python prompt or inside a notebook? Commented May 24, 2022 at 14:40
8

Creating mathematical formulas in Pandas.

a = r'\frac{a}{b}'
ax = plt.axes([0,0,0.3,0.3]) #left,bottom,width,height
ax.set_xticks([])
ax.set_yticks([])
ax.axis('off')
plt.text(0.4,0.4,'$%s$' %a,size=50,color="green")

enter image description here

a = r'f(x) = \frac{\exp(-x^2/2)}{\sqrt{2*\pi}}'
ax = plt.axes([0,0,0.3,0.3]) #left,bottom,width,height
ax.set_xticks([])
ax.set_yticks([])
ax.axis('off')
plt.text(0.4,0.4,'$%s$' %a,size=50,color="green")

enter image description here

5

Matplotlib can already do TeX, by setting text.usetex: True in ~/.matplotlib/matplotlibrc. Then, you can just use TeX in all displayed strings, e.g.,

ylabel(r"Temperature (K) [fixed $\beta=2$]")

(be sure to use the $ as in normal in-line TeX!). The r before the string means that no substitutions are made; otherwise you have to escape the slashes as mentioned.

More info at the matplotlib site.

4
  • Is matplotlibrc in the matplotlib-folder? I cant find it :/
    – kame
    Commented Oct 26, 2010 at 22:23
  • On UNIX systems, it's in the directory I mention above. On windows, I don't know. Check the Docs. Commented Oct 26, 2010 at 22:56
  • I'm using Ubuntu 12 and installed matplotlib in the system (not user), in my case its on /etc/matplotlibrc
    – neu-rah
    Commented Feb 8, 2013 at 22:18
  • 1
    Is that option really necessary? The documentation states that's if you want to use an actual LaTeX installation for advanced features, while TeX-math rendering is natively supported Commented Apr 9, 2013 at 6:04
3

Without ticks:

a = r'\frac{a}{b}'
ax = plt.axes([0,0,0.1,0.2]) #left,bottom,width,height
ax.set_xticks([])
ax.set_yticks([])
plt.text(0.3,0.4,'$%s$' %a,size=40)
1

Draw with matplotlib,

import matplotlib.pyplot as plt
a = r'\frac{a}{b}'
ax=plt.subplot(111)
ax.text(0.5,0.5,r"$%s$" %(a),fontsize=30,color="green")
plt.show()

enter image description here

1

To echo off Andrew's answer earlier, by far the easiest way to let matplotlib handle the latex rendering. But instead of modifying the matplotlibrc file, you can just set the parameter using rcParams:

plt.rcParams['text.usetex'] = True

Include this in your code and latex rendering in a matplotlib figure (or its derivatives should work much better. See here for more documentation:

https://matplotlib.org/stable/gallery/text_labels_and_annotations/tex_demo.html

(Sorry Andrew, I would've posted a follow-up comment but I don't have the reputation)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.