Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Superscript in Python plots

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 .

like image 784
Kantura Avatar asked Jan 20 '14 05:01

Kantura


People also ask

How do you superscript a plot in Python?

Write Superscript in Matplotlib Plots Using the Dollar Sign To make subscripts, you have to write the expression inside the dollar sign using the _ and ^ symbols. If you use the _ symbol, the superscript will be under the character. If you use the ^ symbol, the superscript will be over the character.

How do you add a superscript to a string?

You need to use the ^ operator before the superscript. I presume you want to use this character string in a plot or Markdown so here's an example where the label of the X-axis contains a superscript.

What is Subscripting in Python?

The subscript operator is defined as square brackets [] . It is used to access the elements of string, list tuple, and so on.


1 Answers

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

like image 59
Joe Kington Avatar answered Sep 17 '22 22:09

Joe Kington