9

For most of my interactive plotting with matplotlib, I don't want to use latex processing of math. (Mostly because it's too slow, but also because it's just that little bit too blurry for frequent use IMHO.) But I also use my own macros all the time when writing latex. As just one example, rather than doing something like $M_{\odot}$ I define $\Msun$. So when using matplotlib, I have a tendency to just write the latter automatically, and then get an error and have to fix it. This is just one particularly simple example, and I'd like to have the flexibility to redefine a macro in my papers and my plots simultaneously without too much work.

So, is there any reasonably nice way I could extend the mathtext parser to understand things like $\Msun$? Or would I have to hack mathtext.py or something?

(My fallback is defining Msun as the string r'M_{\odot}' so I could write something like r'$M = 10\,' + Msun + '$', but that's unpleasant and certainly wouldn't be any more automatic for me.)

2 Answers 2

4

Macros are not supported by matplotlib's mathtext, you'd have to edit mathtext.py. Maybe the easiest thing to do is to do your own macro expansion before passing the string to the mathtext parser, e.g. text(x,y,expand(r'$M = \Msun$')) where expand replaces your own macros such as \Msun with its meaning.

Sign up to request clarification or add additional context in comments.

2 Comments

And to save on writing effort, you could make your own 'text' function which first calls 'expand' and then passes the results to matplotlib's 'text'. Now you simply call mike.text(x,y,'$\Msun$') or whatever other latex macro you like.
Yeah, this should work. Moreover, because I just use ipython --pylab anyway, I think I can del text, then import mike.text, which will call matplotlib.pyplot.text -- and similarly for xlabel, ylabel, etc. (Though I'm a python newbie, so please correct me if that's stupid.) Thanks!
0

You can add your latex \newcommands into the preamble, like here: Matplotlib latex working directory / search path

1 Comment

But this is for when I specifically don't want to use tex processing (rcParams['text.usetex']=False), so the latex preamble doesn't get used.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.