83

I want to label my x axis at follows :

pylab.xlabel('metres 10^1')

But I don't want to have the ^ symbol included .

pylab.xlabel('metres 10$^{one}$')

This method works and will superscript letters but doesn't seem to work for numbers . If I try :

pylab.xlabel('metres 10$^1$')

It superscripts a letter N for some reason .

Anyone know how to superscript numbers in python plots ? thanks .

Jakob
  • 19,815
  • 6
  • 75
  • 94
Kantura
  • 5,763
  • 5
  • 18
  • 17
  • 2
    Try to remove the curly braces as they are superfluous when superscripting only one character. – halex Jan 20 '14 at 05:39
  • You are right , the curly braces were superfluous , but unfortunately I still end up with a letter N instead of the number 1 . – Kantura Jan 20 '14 at 06:16
  • 1
    Sounds like you're missing some fonts? I guess using `rc('text', usetex=True)` works? – Jakob Jan 20 '14 at 07:03
  • @Jakob . Excuse my ignorance but how exactly do I implement that ? Where do I type it ? – Kantura Jan 20 '14 at 07:08
  • 1
    Try `from matplotlib import rc` and `rc('text', usetex=True)` see http://matplotlib.org/1.3.1/users/usetex.html – Jakob Jan 20 '14 at 07:28

3 Answers3

147

You just need to have the full expression inside the $. Basically, you need "meters $10^1$". You don't need usetex=True to do this (or most any mathematical formula).

You may also want to use a raw string (e.g. r"\t", vs "\t") to avoid problems with things like \n, \a, \b, \t, \f, etc.

For example:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set(title=r'This is an expression $e^{\sin(\omega\phi)}$',
       xlabel='meters $10^1$', ylabel=r'Hertz $(\frac{1}{s})$')
plt.show()

enter image description here

If you don't want the superscripted text to be in a different font than the rest of the text, use \mathregular (or equivalently \mathdefault). Some symbols won't be available, but most will. This is especially useful for simple superscripts like yours, where you want the expression to blend in with the rest of the text.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set(title=r'This is an expression $\mathregular{e^{\sin(\omega\phi)}}$',
       xlabel='meters $\mathregular{10^1}$',
       ylabel=r'Hertz $\mathregular{(\frac{1}{s})}$')
plt.show()

enter image description here

For more information (and a general overview of matplotlib's "mathtext"), see: http://matplotlib.org/users/mathtext.html

Joe Kington
  • 275,208
  • 71
  • 604
  • 463
17

Alternatively, in python 3.6+, you can generate Unicode superscript and copy paste that in your code:

ax1.set_ylabel('Rate (min⁻¹)')
xyzzyqed
  • 472
  • 4
  • 12
4

If you want to write unit per meter (m^-1), use $m^{-1}$), which means -1 inbetween {}

Example: plt.ylabel("Specific Storage Values ($m^{-1}$)", fontsize = 12 )

codedge
  • 4,754
  • 2
  • 22
  • 38
Engr M Faysal
  • 149
  • 1
  • 5