robintw
robintw

Reputation: 28511

How to remove strange space in LaTeX-style maths in matplotlib plot

I am using the following as an axis label in matplotlib:

"Pixel Radiance ($W/m^2/\mu m$)"

But when I produce a graph with this as the y-axis label I get the image below, which has a strange space between the m^2 and the \mu which makes it look rather strange. How can I remove this strange space?

example graph

A reproducible example, without using any of my own data, is:

from matplotlib.pyplot import *
plot([1, 2, 3], [1, 2, 3])
ylabel("($W/{m^2}/\mu m$)")

Upvotes: 10

Views: 2653

Answers (2)

pwuertz
pwuertz

Reputation: 1325

Matplotlib tries to interpret Latex code and has its own method of printing the text. The results do not necessarily match the output of the real Latex compiler. If you want real Latex text rendering, you must enable the text.usetex rc parameter. This also allows you to load Latex packages (like siunitx) and to create figures that match your document if you are planning to include them.

The extra space does not appear when using Latex. You could just use the workaround and add a negative space, but I tend to use Latex when creating figures for documents.

Upvotes: 2

Luke Woodward
Luke Woodward

Reputation: 64959

You can use a negative space, \!:

r"Pixel Radiance ($W/m^2\!/\mu m$)"

Incidentally, I'd recommend using raw-strings with LaTeX formulae, as that will prevent LaTeX commands (or parts of them) being interpreted as backslash-escapes: you probably wouldn't want \tau ending up as a tab followed by au.

Upvotes: 18

Related Questions