Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format a float using matplotlib's LaTeX formatter?

I have a number in my python script that I want to use as part of the title of a plot in matplotlib. Is there a function that converts a float to a formatted TeX string?

Basically,

str(myFloat)

returns

3.5e+20

but I want

$3.5 \times 10^{20}$

or at least for matplotlib to format the float like the second string would be formatted. I'm also stuck using python 2.4, so code that runs in old versions is especially appreciated.

like image 785
Dan Avatar asked Jun 25 '13 20:06

Dan


4 Answers

With old stype formatting:

print r'$%s \times 10^{%s}$' % tuple('3.5e+20'.split('e+'))

with new format:

print r'${} \times 10^{{{}}}$'.format(*'3.5e+20'.split('e+'))
like image 51
perreal Avatar answered Nov 11 '22 11:11

perreal


You can do something like:

ax.set_title( "${0} \\times 10^{{{1}}}$".format('3.5','+20'))

in the old style:

ax.set_title( "$%s \\times 10^{%s}$" % ('3.5','+20'))
like image 36
Saullo G. P. Castro Avatar answered Nov 11 '22 13:11

Saullo G. P. Castro


Just a trivial elaboration on the previous answer in case you want to do this with an arbitrary float. Note that you need to use the split from the re package to account for the possibility of a negative exponent.

import re
val = 3.5e20
svals = re.split('e+|e-',f'{val:4.2g}')
print(r'${} \times 10^{{{}}}$'.format(*svals))
like image 2
Laurence Lurio Avatar answered Nov 11 '22 12:11

Laurence Lurio


Install the num2tex package:

pip install num2tex

and format your title as:

ax.set_title('${}$'.format(num2tex(3.5e20)))

or use the _repr_latex_() method:

ax.set_title(num2tex(3.5e20)._repr_latex_())

which will give you the same thing.

num2tex inherits from str so the format function can be used as you would use it for a string:

ax.set_title('${:.2e}$'.format(num2tex(3.5e20)))

Disclaimer: I (very recently) created num2tex. It works well for my workflow and I am now trying to get feedback from others who might be interested in using it.

like image 1
MountainDrew Avatar answered Nov 11 '22 13:11

MountainDrew